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. 🙂
You need to make the following call in your
actionPerformed:To be able to reference
windowfrom within youactionPerformed, you need to make your window variablefinal:However, if I can suggest a few improvements:
JFramepaint(Graphics)ofJFrameJComponentorJPaneland set it as the content pane of theJFramepaint(Graphics), rather overridepaintComponent(Graphics)okButtonshould not bestatic. Instead move all your code in a non-static method likeinitUI()and have a code likenew JDraw().initUI();SwingUtilities.invokeLater(Runnable)so that your UI is properly initiated from the Event Dispatching Thread.