JAVA事件处理:画一个变色圆
要求描述
界面如下图所示
当点击不同的按钮时,圆的填充颜色会随之改变
用鼠标点击圆内部时,圆的 填充颜色会依照”面板背景色-红色-绿色-蓝色”循环改变
鼠标移到圆内时,光标变成十字形
效果展示
代码部分
package backage7;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
public class ColorChangingCircle extends JFrame {
private Color[] colors = {null, Color.RED, Color.GREEN, Color.BLUE};
private int currentColorIndex = 0;
public ColorChangingCircle() {
setTitle("ColorChangingCircle");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JButton redButton = new JButton("Red");
JButton greenButton = new JButton("Green");
JButton blueButton = new JButton("Blue");
redButton.addActionListener(e -> changeColor(Color.RED));
greenButton.addActionListener(e -> changeColor(Color.GREEN));
blueButton.addActionListener(e -> changeColor(Color.BLUE));
JPanel buttonPanel = new JPanel();
buttonPanel.add(redButton);
buttonPanel.add(greenButton);
buttonPanel.add(blueButton);
JPanel circlePanel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (colors[currentColorIndex] != null) {
g.setColor(colors[currentColorIndex]);
int diameter = 200;
g.fillOval(getWidth() / 2 - diameter / 2, getHeight() / 2 - diameter / 2, diameter, diameter);
} else {
g.setColor(Color.BLACK);
int diameter = 200;
g.drawOval(getWidth() / 2 - diameter / 2, getHeight() / 2 - diameter / 2, diameter, diameter);
}
}
};
circlePanel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (isMouseInsideCircle(e)) {
cycleColors();
circlePanel.repaint();
}
}
});
circlePanel.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
if (isMouseInsideCircle(e)) {
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
} else {
setCursor(Cursor.getDefaultCursor());
}
}
});
setLayout(new BorderLayout());
add(buttonPanel, BorderLayout.NORTH);
add(circlePanel, BorderLayout.CENTER);
setVisible(true);
}
private void changeColor(Color color) {
currentColorIndex = indexOfColor(color);
repaint();
}
private void cycleColors() {
currentColorIndex = (currentColorIndex + 1) % colors.length;
}
private int indexOfColor(Color color) {
for (int i = 0; i < colors.length; i++) {
if ((colors[i] == null && color == null) || (colors[i] != null && colors[i].equals(color))) {
return i;
}
}
return -1;
}
private boolean isMouseInsideCircle(MouseEvent e) {
int mouseX = e.getX();
int mouseY = e.getY();
int circleX = getWidth() / 2;
int circleY = getHeight() / 2 - 35;
int radius = 100; // 半径为圆的直径的一半
return Math.pow(mouseX - circleX, 2) + Math.pow(mouseY - circleY, 2) <= Math.pow(radius, 2);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(ColorChangingCircle::new);
}
}
- 感谢你赐予我前进的力量
赞赏者名单
因为你们的支持让我意识到写文章的价值🙏
本文是原创文章,采用 CC BY-NC-ND 4.0 协议,完整转载请注明来自 郭同学的笔记本
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果