views:

1321

answers:

3

I have a Java Applet (JApplet). This Applet uses a JComponent(PanelAux) to show values and images that change periodically. But the applet doesn't refresh itself. What can I do to refresh my applet?

//--------------------------------------------RUN

public void run()
    while (true) {
        try {
            myThread.sleep(1000);
        } 
        catch (InterruptedException e){
        }    
        repaint();
    }
}
//--------------------------------------------PAINT
public void paint(Graphics g)
{     

    dim  = new Dimension(image.getWidth(this)+50,image.getHeight(this)+50);
    this.resize(dim);
    this.setMaximumSize(dim);
    this.setMinimumSize(dim);

    PanelAux panel = new PanelAux(image);   //JComponent

    add(panel);

    super.paint(g);
}

Thank you

+3  A: 

Do you actually call the run() method at any place of start a Thread that uses it?

Also: you definitely don't want to add new components in your paint() method! That is screaming for problems!

Joachim Sauer
Or resize and set minimum and maximum size.
Tom Hawtin - tackline
+1  A: 

You should not override paint(Graphics g).

Are there any error exception throws in the applet console?

Dennis Cheung
+3  A: 

As a general tip, the Painting in AWT and Swing article describes how you should handle repainting in either AWT or Swing.

Since you mentioned that you are using a JApplet, the section on "Painting in Swing" is going to be relavent here.

Specifically, with Swing, rather than overloading the paint(Graphics g) method, the paintComponent(Graphics g) method should be used instead, with a call to the superclass' paintComponent method. Quoting from the "Paint Methods" section:

Swing programs should override paintComponent() instead of overriding paint().

This is because the paint method itself is broken down into three separate methods, overriding the paint method itself means that it will prevent calls to the paintComponent, paintBorder and paintChildren of the current class and its ancestor classes.

Also, in order for the run() method to be invoked, your JApplet should implement Runnable and also have a new Thread invoked from somewhere within your applet. (Probably in either the init or start methods.)

Edit:

It also should be noted that the paintComponent method is going to be called anytime the screen needs to be refreshed. The paintComponent method will be called multiple times, so as saua points out, it wouldn't be a very good idea to be instantiating new objects within the paintComponent method itself.

Also, it seems like the design is to have a separate thread (as the applet seems to be implementing the Runnable interface, as implied from the presence of the run method), the updating of the JComponent's state could take place in the run method itself, with a call to the repaint method if necessary.

coobird