JButton无法改变线条的颜色

时间:2016-10-29 19:44:06

标签: java jbutton

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

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();
      }
   });

}

1 个答案:

答案 0 :(得分:1)

这不是要走的路。当你单击一个按钮时,它将执行paint方法,它将再次绘制洋红色的线条。您应该将颜色值移动到某个全局变量/字段,在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);
}