I am trying to clear all of the contents of a JFrame so I can display something else. I don't want to use the paint(Graphics g) method because I am trying to clear the screen from within a timer and I'm unable to use
clearRect( int , int , int , int )
This is what I have already tried but the IDE gives an error and it doesn't clear the screen.
EDIT: my new code
JFrame frame = new JFrame("...");
/*...*/
Timer timer = new Timer(5000, new RemoveContentsTask(frame));
timer.start();
/*...*/
public abstract class RemoveContentsTask implements Runnable {
private JFrame frame;
public RemoveContentsTask(JFrame frame) {
this.frame = frame;
}
public void actionPerformed(ActionEvent evt) {
frame.getContentPane().removeAll();
System.out.println("Timer");
}
}
javax.swing.Timer
instead of java.util.Timer
to make sure you are honoring the single thread nature of Swing and making your updates within the EDT. this.getContentPane().removeAll()
, this
is referring to the instance of TimerTask
Instead you should try something more like...
import javax.swing.Timer;
/*...*/
JFrame frame = new JFrame("...");
/*...*/
Timer timer = new Timer(5000, new RemoveContentsTask(frame));
timer.start();
/*...*/
public class RemoveContentsTask implements Runnable {
private JFrame frame;
public RemoveContentsTask(JFrame frame) {
this.frame = frame;
}
public void actionPerformed(ActionEvent evt) {
frame.getContentPane().removeAll();
}
}
Take a look at Concurrency in Swing for more details
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.