如何每秒移动jlabel? [英] how to move jlabel every second?
本文介绍了如何每秒移动jlabel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试每秒向右移动(x ++)
i try to move it to the right(x++) every seconds
我尝试用线程移动它..
i try to move it with thread..
- 怎么办? (并且可以看到它每秒移动一次)
- 还有另一种方法可以不使用线程吗?
- 我应该使用哪种布局管理器?
继承人我试试..
public class help {
JFrame frame = new JFrame();
JLabel label = new JLabel("target");
public help() {
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(800,600);
frame.setLayout(new GridLayout());
frame.add(label);
label.setPreferredSize(new Dimension(100,100));
label.setLocation(400, 300);
frame.getContentPane().validate();
frame.repaint();
frame.setVisible(true);
mysterious();
}
void mysterious(){
////////////////////////////////
// part of edit responding David kroukamp
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try{
for (int z=0; z<10; z++){
label.setLocation((label.getLocationOnScreen().x+10), label.getLocationOnScreen().y);
Thread.sleep(1000);
}
}catch(Exception ae){
}
}
});
t.start();
//////////////////////////////
}
public static void main(String[]args){
new help();
}
}
非常感谢任何帮助
推荐答案
- 班级名称以大写字母开头,即
帮助
- 应在
事件派遣线程
-
新的
线程
是这样创建的:- Class names begin with capital letters i.e
Help
- Swing components should be created and modified on
Event Dispatch Thread
A new
Thread
is created like this:Thread t = new Thread(new Runnable() { @Override public void run() { //work here } }); t.start();//start thread
- Class names begin with capital letters i.e
- How to Use Swing Timers
但我建议使用Swing 计时器
,因为它在 EDT
上运行:
however I'd suggest a Swing Timer
as it runs on EDT
:
编辑:
根据您的问题,我建议使用计时器
创建线程点是为了一般知识。
As per your questions I suggest using a Timer
the creating thread point was for general knowledge.
问题是线程不在您的swing GUI的EDT线程上运行,其中计时器
确实:
The probelm is the Thread is not run on EDT Thread of your swing GUI where as a Timer
does:
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
int count=0;
public void actionPerformed(ActionEvent evt) {
if(count==10) {//we did the task 10 times
((Timer)evt.getSource()).stop();
}
label.setLocation((label.getLocationOnScreen().x+10), label.getLocationOnScreen().y);
System.out.println(SwingUtilities.isEventDispatchThread());
count++;
}
};
new Timer(delay, taskPerformer).start();
参考:
- http://docs.oracle.com/javase/7/docs/api/javax/swing/Timer.html
这篇关于如何每秒移动jlabel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文