gpt4 book ai didi

java - JPanel 改变颜色以用鼠标绘制

转载 作者:行者123 更新时间:2023-11-30 02:20:37 27 4
gpt4 key购买 nike

我正在尝试使用 JPanel 使用鼠标在 Canvas 上绘画。到目前为止一切正常。我可以画画。我可以将颜色设置为我选择的任何颜色。不过,我试图做到这一点,以便当我单击按钮时,它会将颜色更改为按钮所附加的任何颜色。

就像如果我用黑色绘制,然后点击“蓝色”按钮,它会变成蓝色而不是黑色......但我不确定我哪里出错了。这是我的 paintComponent 部分。

@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);

button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1)
g.setColor(Color.BLUE);
}
});

for (Point point : points)
g.fillOval(point.x, point.y, 4 , 4);
}

最佳答案

不,不,不。为什么要向绘制方法内的按钮添加 ActionListener ?重绘管理器可以快速连续调用paint方法十几次,现在您有十几个或更多的ActionListener注册到按钮..它们不会执行任何操作。

首先创建一个可以存储所需油漆颜色的字段。可能通过类构造函数将 ActionListener 注册到您的按钮,这会更改“绘制颜色”并触发新的绘制周期。当调用 paintComponent 时,应用所需的绘画颜色

private Color paintColor = Color.BLACK;

protected void setupActionListener() {
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {
paintColor = Color.BLUE;
repaint();
}
}
});
}

@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(paintColor);
for (Point point : points)
g.fillOval(point.x, point.y, 4 , 4);


}

现在,去阅读 Performing Custom PaintingPainting in AWT and Swing更好地了解 Swing 中绘画的实际工作原理

关于java - JPanel 改变颜色以用鼠标绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46946425/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com