鼠标点击时在指定按钮绘制一个绿色方块:
时间: 2024-02-22 17:00:48 浏览: 31
要在Java Swing中实现鼠标点击时在指定按钮绘制一个绿色方块的效果,您可以使用ActionListener接口来监听按钮点击事件,并在适当的位置绘制标记。
以下是一个简单的示例代码,演示了如何在按钮点击时在指定位置绘制一个绿色方块:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ClickOnButton extends JPanel implements ActionListener {
private JButton button;
private int buttonX, buttonY;
private boolean buttonClicked;
public ClickOnButton() {
setPreferredSize(new Dimension(400, 400));
setBackground(Color.WHITE);
button = new JButton("Click Me!");
button.addActionListener(this);
add(button);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (buttonClicked) {
g.setColor(Color.GREEN);
g.fillRect(buttonX - 5, buttonY - 5, 10, 10);
}
}
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
Rectangle bounds = source.getBounds();
buttonX = bounds.x + bounds.width / 2;
buttonY = bounds.y + bounds.height / 2;
buttonClicked = true;
repaint();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Click on Button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ClickOnButton());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
```
您可以将`buttonClicked`变量设置为true,以在按钮点击时绘制标记。在`actionPerformed`方法中,您可以获取按钮的位置并设置标记的位置。您可以根据需要调整绘制标记的大小。
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)