Java Graphics repaint () on ButtonClick

I have this code and you want to redraw my graphics when the button is clicked:

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 do not know how to do this because I cannot redraw in my ActionPerfomed. Error: non-static repaint () method cannot reference static context

I hope someone can help. :)

+4
source share
2 answers

You need to make the following call to actionPerformed :

 window.repaint(); 

To be able to link window to you actionPerformed , you need to make your final window variable:

 final JDraw window = ...; 

However, if I can offer several improvements:

  • Do not JFrame
  • Do not override paint(Graphics) JFrame
  • Instead, create a class that extends JComponent or JPanel and sets it as a JFrame content JFrame
  • Instead of overriding paint(Graphics) , rather override paintComponent(Graphics)
  • Your okButton should not be static . Instead, move all your code to a non-stationary method, such as initUI() , and get code like new JDraw().initUI();
  • Wrap the code starting your user interface with SwingUtilities.invokeLater(Runnable) so that your user interface is correctly triggered from the event dispatch thread.
+10
source

You cannot reference the JDraw class. Instead, you should use an object. The object in your case is window . So use:

 window.repaint(); 

This is how to say: β€œMan,” go to the door. Man is a class. You cannot tell the Man to do something, you need a copy of the Man, for example, Obama or Santa Claus. In your case: you cannot specify JDraw to redraw, but an object of type JDraw, i.e.: window .

+5
source

All Articles