在练习学校编程实验题遇到的小问题,代码如下:
要求【点击“向右走”按钮,标签“向右移标签”会向向右移动10次,每次移动10个单位。同理“向左走”按钮。】
我按照以下运行,却出现窗体无限生成的情况。
定位确认是因为创建线程那几句导致的,删除就能正常显示窗体了。我想求教以下,我应该如何创建线程才不会出现这个问题呢(尽量利用Runnable接口实现)? 0.0
public class JButton_Move{
JFrame jf=new JFrame();
JLabel jl1=new JLabel("向右移标签");
JLabel jl2=new JLabel("向左移标签");
JButton jb1=new JButton("向右走");
JButton jb2=new JButton("向左走");
int jl1_X=10;
int jl2_X=200;
public void init(){
jf.setSize(300,150);
jf.setLayout(null);
jf.add(jb1);
jf.add(jb2);
jf.add(jl1);
jf.add(jl2);
jb1.setBounds(50,100,80,20);
jb2.setBounds(150,100,80,20);
jl1.setBounds(jl1_X,30,80,20);
jl2.setBounds(jl2_X,60,80,20);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
JButton_Move(){
init();
Thread t1=new Thread(new move());
t1.start();
}
public static void main(String[] args){
JButton_Move jm=new JButton_Move();
}
}
class move extends JButton_Move implements Runnable{
public void run(){
jb1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for(int i=0;i<10;i++){
try{
Thread.sleep(1000);
jl1.setLocation(jl1_X+10,30);
}catch (InterruptedException a){
System.out.println("error..");
}
}
}
});
jb2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for(int i=0;i<10;i++){
jl2.setLocation(jl2_X-10,60);
}
}
});
}
}