Search code examples
javaswinguser-interfacecolorsgraphic

Update a graphic color using a button


I am trying to update the colors of some elipses and lines that are drawn when the frame is constructed. I then want to change the color using a button on the frame.

package animation.test;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;

import javax.swing.JButton;
import javax.swing.JFrame;

public class GraphDisplayTest extends JFrame {

static GraphDisplayTest gui;

private JButton changeColorBtn = new JButton("Change Color");
private Graphics2D g2;
private Ellipse2D e1;
private Ellipse2D e2;
private Ellipse2D e3;
private Ellipse2D e4;
int x = 50, y = 50, w = 20, h = 20;

public static void main(String[] args) {
    gui = new GraphDisplayTest();
    gui.launch();

}

public void launch(){
    gui.setLayout(new BorderLayout());
    gui.add(changeColorBtn, BorderLayout.SOUTH);

    changeColorBtn.addActionListener(new ChangeColor());

    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    gui.setTitle("Graph Display Example");
    gui.setSize(350, 400);
    gui.setVisible(true);
}

public class ChangeColor implements ActionListener{
    public void actionPerformed(ActionEvent e){

    //HERE IS THE PROBLEM - the colors are not being reset
        g2.setPaint(Color.BLACK);
        g2.fill(e1);
        g2.drawLine(x+10, y+10, x+210, y+10);
        g2.setColor(Color.WHITE);
    }
}


public void paint(Graphics g) {
    g2 = (Graphics2D)g;
    g2.drawLine(x+10, y+10, x+210, y+10);
    g2.setColor(Color.BLACK);
    g2.drawLine(x+210, y+10, x+210, y+210);
    g2.setColor(Color.BLACK);
    g2.drawLine(x+10, y+210, x+210, y+210);
    g2.setColor(Color.BLACK);
    g2.drawLine(x+10, y+10, x+10, y+210);
    g2.setColor(Color.BLACK);

    e1 = new Ellipse2D.Double(x, y, w, h);
    g2.setPaint(Color.BLUE);
    g2.fill(e1);
    e2 = new Ellipse2D.Double(x+200, y, w, h);
    g2.setPaint(Color.RED);
    g2.fill(e2);
    e3 = new Ellipse2D.Double(x, y+200, w, h);
    g2.setPaint(Color.GREEN);
    g2.fill(e3);
    e4 = new Ellipse2D.Double(x+200, y+200, w, h);
    g2.setPaint(Color.YELLOW);
    g2.fill(e4);

}


}

I have commened where i have no idea what to do! Can anyone help?!?!

Many thanks in advance Josh


Solution

  • Don't store the value of Graphics object (in this case: g2).

    Create a new attribute to store the color of e1:

    Color c = Color.BLUE;
    

    Delete all code in actionPerformed(...) and set the value of c to the new color. Then, call repaint().

    c = Color.BLACK;
    repaint();
    

    In paint(...), change the lines:

    g2.setPaint(Color.BLUE);
    g2.fill(e1);
    

    to:

    g2.setPaint(c);
    g2.fill(e1);