2014-03-25 37 views
1

我試圖用java編寫程序,其中包含圖像的標籤每秒都在移動,但不幸的是,儘管代碼包含零錯誤,但代碼並未運行。任何人都可以弄清楚發生了什麼。這裏是代碼:在Java中移動JLabel

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


       } 


} 

請問,任何人都可以幫助我。

+0

你得到的輸出是什麼? –

+1

沒有什麼程序不會執行 –

回答

5

你正在一個線程中執行一個無限循環。當創建new what();時,循環開始並且永不結束。如此c.setVisible(true);永遠不會到達。

您將需要爲此循環運行創建一個單獨的線程。您可以創建以下類;

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

然後在你的main方法中實例化並運行,就像這樣;

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

我希望這有助於:)

+0

非常感謝在另一個線程中啓動該循環來解決這個問題 –

+0

它會的。但是你必須將你的'JLabel'實例傳遞到這個新的線程中,並且每次改變邊界時都要調用'revalidate()'和'repaint()'。我將添加一個可運行的示例,供您使用。 –

+0

謝謝,請添加一個例子 –

1

你需要的,而(真)環線頭脫落進入一個新的線程,使擺動線程可以繪製並顯示該幀。