2015-12-15 130 views
-2

我想将按钮自动移动到另一个按钮。请帮我解决这个问题,我刚学过睡眠方法。可能有些问题他们将如何自动将按钮移动到另一个按钮?

import javax.swing.*; 
import java.awt.*; 
public class tr extends JFrame 
{ 
public static void main(String []args) 
{ 
JFrame f1=new JFrame("Hit & Run"); 
JPanel p1=new JPanel(); 
JButton mv = new JButton(); 
JButton hit=new JButton("Hit It"); 
f1.getContentPane().add(p1); 
int x; 
for(x=0;x<=600;x++) 
{ try{ 
Thread.sleep(50); 
} 
catch(InterruptedException e) 
{ 
System.err.println("sleep exception"); 
} 
mv.setBounds(x,220,53,35); 
} 
hit.setBounds(680,30,90,500); 
p1.setBackground(Color.black); 

hit.setBackground(Color.green); 
mv.setBackground(new Color(255,204,0)); 
p1.setBackground(Color.black); 
p1.setLayout(null); 
p1.add(mv); 
p1.add(hit); 

f1.setVisible(true); 
f1.setSize(800,600); 
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
} 
} 

回答

0

根据您当前的代码你PROGRAMM睡了很多,而不是甚至创建窗口完成。首先,不要将GUI线程发送到睡眠状态,否则窗口会在睡眠状态下休眠,而应该唤醒并与用户交互。
要做你想要的,你需要启动另一个线程来执行你的按钮的移动。
所以把你的for循环出来的初始化代码,并在你的最后一行添加以下内容。

new Thread(new Runnable(){ 
    @Override 
    public void run() { 
     int x; 
     for(x=0;x<=600;x++) 
     {   
      try{ 
       Thread.sleep(50); 
      } 
      catch(InterruptedException e) 
      { 
       System.err.println("sleep exception"); 
      } 
      mv.setBounds(x,220,53,35); 
     } 
    } 
}).start(); 
+0

非常感谢,但现在又提出了另一个问题。当按下第二个按钮时,不能使按钮不可见。 System.err.println(“睡眠异常”)}。如果(x == 580){MV.set enabled(false);}。 MV.setBounds(x,220,53,35);} –

+0

尝试'mv.setVisible(false);'用setEnable你只能指定,如果按钮被激活意味着可点击或不可以。不要忘记upvote和/或接受我的回答:) – ArcticLord

+0

谢谢。我尝试设置可见,没有其他声明,但没有工作。但现在工作。无论如何感谢很多 –

相关问题