I want to move a button towards another button automatically. please help me out to solve this I just learned sleep method . may some problems their applying
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);
}
}
With your current code your programm sleeps alot while is not even finish with creating your window. And first of all never send your GUI Thread to sleep or your Window will sleep while it should be awake and interact with the user.
To do what you want you need to start another Thread that will perform the movement of your button.
So take your for loop out of the initialization code and add the following under your last line.
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();