如何自动将一个按钮移向另一个按钮?

How to move a button towards another button automatically?

我想自动将一个按钮移向另一个按钮。请帮我解决这个我刚学会睡眠方法。他们申请时可能会遇到一些问题

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);
}
}

使用您当前的代码,您的程序会睡很多,甚至还没有完成创建您的 window。首先,永远不要让你的 GUI 线程进入睡眠状态,否则你的 Window 会在它应该处于清醒状态并与用户交互时进入睡眠状态。
要执行您想要的操作,您需要启动另一个线程来执行按钮的移动。
因此,将 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();