I have a JFrame , which has a JPanel and a JButton . The JFrame is set to BorderLayout , and i expected my code to repaint the panel every 500 millisecs after the button has been clicked. But even though the setup goes into a loop , the frame does not repaint.
Here is what i wrote for when the button is clicked
public void actionPerformed(ActionEvent e) {
while(true){
try {
frame.repaint(); // does not repaint
Thread.sleep(500);
} catch (InterruptedException exp) {
exp.printStackTrace();
}
}
}
and this for the setup :
public void go() {
b.addActionListener(new ButtonListener()); // b is the JButton
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // frame is the JFrame
frame.setLayout(new BorderLayout());
frame.add(BorderLayout.CENTER, p); // p is a MyPanel
frame.add(BorderLayout.SOUTH, b);
frame.setSize(300, 300);
frame.setVisible(true);
}
class MyPanel extends JPanel { // p is an instance of this MyPanel class
public void paintComponent(Graphics gr) {
gr.fillRect(0, 0, this.getWidth(), this.getHeight());
int r, g, b, x, y;
r = (int) (Math.random() * 256);
g = (int) (Math.random() * 256);
b = (int) (Math.random() * 256);
x = (int) (Math.random() * (this.getWidth() - 15 ));
y = (int) (Math.random() * (this.getHeight() - 15));
Color customColor = new Color(r, g, b);
gr.setColor(customColor);
gr.fillOval(x, y, 30, 30);
}
}