简体   繁体   English

不使用paint清除JFrame(Graphics g)

[英]Clearing a JFrame without using paint(Graphics g)

I am trying to clear all of the contents of a JFrame so I can display something else. 我试图清除JFrame的所有内容,以便我可以显示其他内容。 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 我不想使用paint(Graphics g)方法,因为我试图从计时器中清除屏幕而我无法使用

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. 这是我已经尝试过但IDE出错并且不清除屏幕。

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"); 
    }
}
  1. You should be using a 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. 您应该使用javax.swing.Timer而不是java.util.Timer来确保您遵守Swing的单线程特性并在EDT中进行更新。
  2. In the context of you question, this.getContentPane().removeAll() , this is referring to the instance of TimerTask 在你提问的上下文中, this.getContentPane().removeAll()this是指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 有关更多详细信息,请参阅Swing中的Concurrency

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM