Repainting JPanel inside the frame

I have a JPanel inside the frame. The contents of the JPanel should be updated with every call paintComponent(which is called repaint()), but when I do this as shown below, I just see a white window. (Please excuse the distorted indentation, Eclipse does all sorts of weird stuff with tabs.)

private static void handleGUI() 
{       
    JFrame frame = new JFrame("Animation");
    frame.setPreferredSize(new Dimension(100, 100));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Board b = new Board();

    frame.getContentPane().add(b);

    frame.pack();
    frame.setVisible(true);

    while(true)
    {
        System.out.println("Repainting panel");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        b.repaint();
    }
}

public class Board extends JPanel
{
public Board() { t=0; }

    private int t;

public void paintComponent(Graphics g) 
{
    super.paintComponent(g);

    ++t;

    /* Variables snipped */

    g.setColor(Color.white);
    g.drawOval(0, 0, width, height);

    BufferedImage image = ImageIO.read(new File(imagePath));
    g.drawImage(image, x(t), y(t));
    /* There some more image and rectangle drawing ahead */
}

}

+5
source share
3 answers

, (1+ rep - , paintComponent, ), paintComponent , , while (true) Thread.sleep Swing, EDT, Swing . Swing. , ,

JPanel paintComponent ( repaint()),

, paintComponent? , , , , . , ( ) - , , .

, paintComponent, .

:

1) Swing 1000 ActionListener ActionPerformed, ( , - ) , .

2) TimerPerformed, increment t.

3) , , JPanel JPanel , . , , , GUI, . SwingWorker , PropertyChangeListener, SwingWorker , StateValue.DONE.

- , .

: , , . .

+6

. , .

+2

your paintComponent just calls super.paintComponent. Thus, JPanel at the same time draws itself, which will be light gray or white or light brown or something depending on your appearance.

+1
source

All Articles