Question

I have tried to write the program in java in which a label containing an image is moving every second, but unfortunately the code is not running despite it contains zero error. Can anyone make out what is happening. Here is the code:

import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

public class what extends JFrame {
         private JPanel  panel;
         private Random r= new Random();
         private JLabel image;
         private Random s = new Random();


         public what (){
             super("Catch him!");
             panel = new JPanel();
             Icon b = new ImageIcon(getClass().getResource("img.JPG"));
             image = new JLabel(b);
             panel.add(image);
             add(panel,BorderLayout.CENTER);
             panel.setBackground(Color.yellow);

             panel.add(image);
        while(true){
                int x = s.nextInt(1000);
                 int y = s.nextInt(900);

                  try{
                      Thread.sleep(1000);
                  }catch(Exception e){

             }

                 image.setBounds(x, y,200, 200);
          }




}
        public static void main(String[] args){
            what c = new what();
            c.setVisible(true);
            c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
            c.setSize(1920,1080);


                }


}

Please, Can anyone help me.

Was it helpful?

Solution

You're executing an infinite loop inside a single thread. When new what(); is created, the loop starts and never ends. As such c.setVisible(true); is never reached.

You will need to create a separate thread for this loop to be run in. You could create the following class;

public class Infout implements Runnable{

    private JFrame frame;
    private JLabel image;
    private Random s = new Random();

    public Infout(JFrame frame, JLabel image){
        this.frame = frame;
        this.image = image;
    }

    @Override
    public void run() {
        while(true){
           int x = s.nextInt(1000);
           int y = s.nextInt(900);

           try{ Thread.sleep(1000); }
           catch(InterruptedException e){ }
           image.setBounds(x, y, 200, 200);
        }
    }
}

and then instantiate and run in your main method like so;

Infout inf = new Infout(c, image);
new Thread(inf).start();

I hope this helps :)

OTHER TIPS

You'll need to thread off the while(true) loop into a new thread so that the swing thread can paint and display the frame.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top