Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Graphics repaint() on ButtonClick

Tags:

java

swing

I have this code and want to repaint my graphic when the Button gets pressed:

public class JDraw extends JFrame {

/**
 * Draws a figur in a JFrame.
 * The color of it is random and can get changed by a button.
 */

public static JButton okButton = new JButton("change color");

public JDraw(String newTitel) {
    super.setTitle(newTitel);
}

//Main method
public static void main(String str[]) {
    JDraw window = new JDraw("Graphic");
    window.setSize(300, 450);
    window.setVisible(true);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.add(okButton, BorderLayout.SOUTH);

    okButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            //JDraw.repaint(); <-- problem
        }
    });
}



@Override
public void paint(final Graphics g) {

    super.paint(g);

    Random rand = new Random();
    int r1 = rand.nextInt(255);
    int b1 = rand.nextInt(255);
    int g1 = rand.nextInt(255);
    g.setColor(new Color(r1, g1, b1));

    //head
    g.drawOval(100, 50, 100, 100);
    g.fillOval(100, 50, 100, 100); // filled
    //more drawing stuff.....

}
}

However I have no idea how to do it, because I cant do the repaint in my ActionPerfomed. Error: non-static method repaint() cannot be referenced from a static context

I hope somebody can help. :)

like image 999
RandomUser123 Avatar asked Dec 06 '22 10:12

RandomUser123


2 Answers

You need to make the following call in your actionPerformed:

window.repaint();

To be able to reference window from within you actionPerformed, you need to make your window variable final:

final JDraw window = ...;

However, if I can suggest a few improvements:

  1. Don't extend JFrame
  2. Don't override paint(Graphics) of JFrame
  3. Instead create a class that extends JComponent or JPanel and set it as the content pane of the JFrame
  4. Instead of overrding paint(Graphics), rather override paintComponent(Graphics)
  5. Your okButton should not be static. Instead move all your code in a non-static method like initUI() and have a code like new JDraw().initUI();
  6. Wrap the code starting your UI in a SwingUtilities.invokeLater(Runnable) so that your UI is properly initiated from the Event Dispatching Thread.
like image 68
Guillaume Polet Avatar answered Dec 14 '22 22:12

Guillaume Polet


You can't refer to the class JDraw. You should use an object instead. The object in your case is window. So, use:

window.repaint();

It is like saying: Human, walk to the door. Human is the class. You can't tell Human to do something, you need an instance of Human, like Obama or Santa Claus. In your case: you can't tell JDraw to repaint, but the object of type JDraw, i.e.: window.

like image 21
Martijn Courteaux Avatar answered Dec 14 '22 23:12

Martijn Courteaux