用java编写编写程序,程序开始运行时在界面中显示一个白色的圆,当在圆中按下鼠标键时颜色变为蓝色,释放鼠标时颜色为红色。界面如下图所示:
时间: 2024-02-28 19:57:33 浏览: 30
可以使用Java的Swing库来实现该程序。以下是代码实现:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ColorfulCircle extends JPanel {
private Color circleColor;
private int x, y, radius;
public ColorfulCircle() {
circleColor = Color.WHITE;
x = 200;
y = 200;
radius = 50;
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.getX() > x - radius && e.getX() < x + radius && e.getY() > y - radius && e.getY() < y + radius) {
circleColor = Color.BLUE;
}
}
@Override
public void mouseReleased(MouseEvent e) {
circleColor = Color.RED;
}
});
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(circleColor);
g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Colorful Circle");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.add(new ColorfulCircle());
frame.setVisible(true);
}
}
```
运行程序后,就可以看到一个白色的圆了。按下鼠标键时,圆会变为蓝色,释放鼠标时,圆会变为红色。
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.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)