Millie Millie - 1 month ago 11
Java Question

JButton not working to change color of a line

I have posted this already, and made some progress, the button is still not working, but I think it is closer. Can anyone tell me what needs to be changed in order to get it fully functioning upon user click? It is supposed to change the color of a line when it is clicked. Thanks!

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

}

Answer

It's not the way to go. When you click a button it is going to execute paint method and it will just draw the line with magenta color again. You should rather move color value to some global variable/field, change the value of it in actionPerformed and call repaint as you do.

Another thing is that you should not call addActionListener in paint method and I don't know what for is action JButton. Anyway you may want to check this out(not tested though):

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