JButton 无法更改线条的颜色

JButton not working to change color of a line

我已经发布了这个,并取得了一些进展,按钮仍然不起作用,但我认为它更接近了。任何人都可以告诉我需要更改什么才能在用户单击时使其完全运行吗?它应该在单击时更改线条的颜色。谢谢!

JButton action =new JButton();
JButton red = new JButton();
JButton blue = new JButton(); 

public SimplePaint() {

blue.setBackground(Color.BLUE);    
panel.add(blue);

red.setBackground(Color.RED);
   panel.add(red);

}

public void paint(Graphics g) {
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
Line2D line = new Line2D.Float(0, 250, 2000, 300);
g2.setColor(Color.MAGENTA);
g2.setStroke(new BasicStroke(3));
g2.draw(line);    

action.addActionListener(new ActionListener() {     
    public void actionPerformed(ActionEvent e) {
    if (e.getSource() == blue) {
        g2.setColor(Color.BLUE);
    }
    else if(e.getSource() == red) {
        g2.setColor(Color.RED);
    }
    repaint();
      }
   });

}

这不是要走的路。当你点击一个按钮时,它会执行 paint 方法,它会再次绘制洋红色的线条。您应该将颜色值移动到某个全局 variable/field,在 actionPerformed 中更改它的值并像您一样调用重绘。

另一件事是你不应该在 paint 方法中调用 addActionListener 并且我不知道动作 JButton 有什么用。不管怎样,你可能想看看这个(虽然没有测试):

JButton red = new JButton();
JButton blue = new JButton();
Color color = Color.MAGENTA;

public SimplePaint() {

    blue.setBackground(Color.BLUE);    
    panel.add(blue);

    red.setBackground(Color.RED);
    panel.add(red);

    ActionListener actionListener = new ActionListener() {     
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == blue) {
                color = Color.BLUE;
            } else if (e.getSource() == red) {
                color = Color.RED;
            }
            repaint();
        }
    };

    blue.addActionListener(actionListener);
    red.addActionListener(actionListener);
}

public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2 = (Graphics2D) g;
    Line2D line = new Line2D.Float(0, 250, 2000, 300);
    g2.setColor(color);
    g2.setStroke(new BasicStroke(3));
    g2.draw(line);
}