I have a program that is supposed to draw circles every twentieth of a second every time a button is clicked. When the button is pressed, a function is called and a for-loop is executed 25 times. Within that for-loop, repaint ()
should be called. Within the paintComponent
function, random coordinates are produced and a red circle is drawn. However, the paintComponent
function appears to NOT be called 25 times, but only once. I've run into this problem many times in the past and I've always eventually "fixed" it, but I've never really understood what's going on. Any ideas?
// MainFrame.java
import java.awt.Container;
import javax.swing.*;
public class MainFrame extends JFrame
{
MainPanel mp;
public MainFrame ()
{
this.setSize (800, 800);
mp = new MainPanel ();
Container container = this.getContentPane ();
container.add (mp);
this.setVisible (true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main (String args[])
{
MainFrame mf = new MainFrame ();
}
}
// MainPanel.java
import java.awt.*;
import java.util.logging.*;
import javax.swing.*;
public class MainPanel extends JPanel
{
Panel1 panel1;
Panel2 panel2;
public MainPanel ()
{
panel1 = new Panel1 (this);
panel2 = new Panel2 (this);
this.setLayout (new GridLayout (2, 1));
this.add (panel1);
this.add (panel2);
}
public void RandomAnimation ()
{
for (int i = 0; i < 25; i++)
{
try
{
Thread.sleep(50);
panel1.repaint();
}
catch (InterruptedException ex)
{
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
// Panel1.java
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class Panel1 extends JPanel
{
Random random;
MainPanel mp;
public Panel1 (MainPanel mainpan)
{
random = new Random ();
mp = mainpan;
}
@Override
public void paintComponent (Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint (RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int x = random.nextInt (200) + 100;
int y = random.nextInt (200) + 100;
System.out.println ("Inside Panel1 paintComponent function.");
g2.setColor (Color.RED);
g2.fillOval (x, y, 50, 50);
}
}
// Panel2.java
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Panel2 extends JPanel implements ActionListener
{
JButton animateButton;
MainPanel mp;
public Panel2 (MainPanel mainpan)
{
mp = mainpan;
animateButton = new JButton ("Animate");
animateButton.addActionListener (this);
this.add (animateButton);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource () == animateButton)
{
mp.RandomAnimation ();
}
}
}