JPanel改变颜色以用鼠标绘制

JPanel changing colors to draw with mouse

我正在尝试使用 JPanel 用鼠标在 canvas 上作画。到目前为止一切正常。我能画。我可以将颜色设置为我选择的任何颜色。但是我正在努力做到这一点,以便当我单击一个按钮时,它会将颜色更改为按钮所连接的颜色。

就像我用黑色画画,然后点击 "Blue" 按钮,它会变成蓝色而不是黑色...不过我不确定哪里出错了。这是我的 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);
}

不不不。为什么要在 paint 方法中向按钮添加 ActionListener?重绘管理器可以快速连续调用 paint 方法十几次,现在你有十几个或更多 ActionListeners 注册到按钮..它们不会做任何事情。

首先创建一个可以存储所需油漆颜色的字段。可能通过 类 构造函数向您的按钮注册一个 ActionListener,这会更改 "paint color" 并触发新的绘制周期。当调用 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 Painting and Painting in AWT and Swing 以更好地了解绘画在 Swing 中的实际工作原理