用Java代码写一个椭圆按钮
时间: 2024-01-26 17:02:33 浏览: 75
以下是用Java代码实现椭圆按钮的示例:
```java
import javax.swing.*;
import java.awt.*;
public class EllipseButton extends JButton {
public EllipseButton(String label) {
super(label);
setContentAreaFilled(false);
}
@Override
protected void paintComponent(Graphics g) {
if (getModel().isArmed()) {
g.setColor(Color.lightGray);
} else {
g.setColor(getBackground());
}
g.fillOval(0, 0, getSize().width-1, getSize().height-1);
super.paintComponent(g);
}
@Override
protected void paintBorder(Graphics g) {
g.setColor(getForeground());
g.drawOval(0, 0, getSize().width-1, getSize().height-1);
}
Shape shape;
@Override
public boolean contains(int x, int y) {
if (shape == null || !shape.getBounds().equals(getBounds())) {
shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
}
return shape.contains(x, y);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Ellipse Button Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
EllipseButton button = new EllipseButton("Click Me!");
button.setPreferredSize(new Dimension(100, 100));
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(button);
frame.setVisible(true);
}
}
```
在这个示例中,我们继承了JButton类并覆盖了它的paintComponent和paintBorder方法,用fillOval和drawOval方法来画出椭圆形状的按钮。我们还重写了contains方法,以便为按钮提供正确的形状,以便识别点击事件。最后,我们创建一个JFrame并将我们的椭圆按钮添加到其中。
阅读全文