Search code examples
javaactionlistenergraphics2d

JAVA Changin a graphics Color


everyone I have a code which creates a circle and a button. Circle has a color in the beginning and button has to change the color of this circle everytime I click on it but it does not whenever I click on it console gives errors. Since I am new in JAVA I could not find a solution. Here is the code:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class GUI extends JPanel implements ActionListener {

JFrame frame;
public static void main(String[] args) {

    GUI gui = new GUI();
    gui.go();

}

public void go() {

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JButton button = new JButton("change colors");
    button.addActionListener(this);

    MyDrawPanel drawPanel = new MyDrawPanel();

    frame.getContentPane().add(BorderLayout.SOUTH, button);
    frame.getContentPane().add(BorderLayout.CENTER, drawPanel);
    frame.setSize(300, 300);
    frame.setVisible(true);



}


 public void actionPerformed(ActionEvent event) {

    frame.repaint();
}


}

My function to repaint:

 import java.awt.*;
import javax.swing.*;

  public class MyDrawPanel extends JPanel {




public void paintComponent(Graphics g) {


    Graphics2D g2d = (Graphics2D) g;

    int red = (int) (Math.random()*256);
    int green = (int) (Math.random()*256);
    int blue = (int) (Math.random()*256);

    Color starColor = new Color(red, green, blue);      ;


    red = (int) (Math.random() * 256);
    green = (int) (Math.random() * 256);
    blue  = (int) (Math.random() * 256);
    Color endColor = new Color(red, green, blue);

    GradientPaint gradient = new GradientPaint(70, 70,starColor, 150, 150,endColor);
    g2d.setPaint(gradient);
    g2d.fillOval(70, 70, 100, 100);

}
}

Solution

  • It's easier for us if you include the stack-trace in the post. But I guess this issue is quite clear.

    In the go-method, you store the JFrame in a local variable with:

    JFrame frame = new JFrame();
    

    Simply change this line to:

    frame = new JFrame();
    

    This will actually store the variable in a way you want - as a member variable of the class GUI