java按钮点击事件点击画圆形画矩形
时间: 2023-07-05 10:18:05 浏览: 64
好的,我可以为您提供Java代码来实现按钮点击事件,并画出圆形和矩形的形状。以下是一个简单的代码示例:
```java
import java.awt.*;
import javax.swing.*;
public class MyButton extends JFrame {
private JPanel panel;
private JButton circleButton, rectButton;
public MyButton() {
panel = new JPanel();
circleButton = new JButton("Circle");
rectButton = new JButton("Rectangle");
circleButton.addActionListener(e -> {
Graphics g = panel.getGraphics();
g.setColor(Color.RED);
g.fillOval(50, 50, 100, 100);
});
rectButton.addActionListener(e -> {
Graphics g = panel.getGraphics();
g.setColor(Color.BLUE);
g.fillRect(200, 50, 100, 100);
});
panel.add(circleButton);
panel.add(rectButton);
add(panel);
setSize(400, 200);
setVisible(true);
}
public static void main(String[] args) {
new MyButton();
}
}
```
这里我们创建了一个`MyButton`类,它继承自`JFrame`类。在构造函数中,我们创建了一个`JPanel`面板和两个按钮:`circleButton`和`rectButton`。我们使用`addActionListener()`方法为每个按钮添加一个点击事件监听器。
当`circleButton`被点击时,我们使用`Graphics`对象获取面板的绘图上下文,并使用`fillOval()`方法绘制一个红色的圆形。当`rectButton`被点击时,我们使用`Graphics`对象获取面板的绘图上下文,并使用`fillRect()`方法绘制一个蓝色的矩形。
最后,我们将面板添加到窗口中,并设置窗口的大小和可见性。
希望这个代码示例对您有所帮助!