[英]timer in java with threads?
I am using the code below to open a frame-1 every x time but when i go to an other frame and back the timer reset itself causing a second frame-1 to show up which is problematic since I only need 1 at a time tried to use isvisbile()
but did not work also. 我正在使用下面的代码每x次打开一个frame-1,但是当我转到另一个帧并返回计时器时,自身会重置,导致出现第二个frame-1,这是有问题的,因为我一次只需要1个使用
isvisbile()
但也无法正常工作。
Here is the code: 这是代码:
int timerTimeInMilliSeconds2 = 30000;
javax.swing.Timer timer2 = new javax.swing.Timer(timerTimeInMilliSeconds2, new ActionListener() {
public void actionPerformed(ActionEvent e) {
Pop p=new Pop();
p.setVisible(true);
new Thread(){
@Override
public void run() {
try {
Thread.sleep(5000); // time after which pop up will be disappeared.
p.dispose();
} catch (InterruptedException e) {
e.printStackTrace();
}
};
}.start();
}
});
timer2.start();
Instead of having the Pop p
object as a local variable inside your method having it as a member of your class. 而不是将
Pop p
对象作为方法的局部变量,而将其作为类的成员。 When actionPerformed
triggers check whether it is null (a better name that p
would be a good idea too) and only create the window if it is. 当
actionPerformed
触发器检查它是否为null(更好的名字p
也是个好主意),如果是,则仅创建窗口。
Rather than creating a thread to dispose the window after 5 seconds you should use another Timer
anyway. 而不是在5秒后创建线程来处理窗口,您应该仍然使用另一个
Timer
。
Your question is little bit uncleared. 您的问题有点不清楚。 As what I can understood, you need to create
Pop p
as a member variable of your defined class instead of local variable of method actionPerformed
so that you can check before triggering it weather the object is null
or not. 据我了解,您需要将
Pop p
创建为定义的类的成员变量,而不是方法actionPerformed
的局部变量,以便您可以在触发它之前检查对象是否为null
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.