2012-11-24 30 views
1

的JFrame setresizeable爲什麼不工作這個計劃? (它不打印「運行...」)線程沒有運行,爲什麼不工作

package eu.inmensia.learn; 

import java.awt.Canvas; 
import java.awt.Dimension; 

import javax.swing.JFrame; 

public class Client extends Canvas implements Runnable { 

    private static final long serialVersionUID = 1L; 
    public static final int WIDTH = 300; 
    public static final int HEIGHT = WIDTH/16 * 9; 
    public static final short SCALE = 3; 

    private Thread thread; 
    private JFrame frame = new JFrame(); 
    private boolean running = false; 

    public Client() { 
     Dimension size = new Dimension(WIDTH * SCALE, HEIGHT * SCALE); 
     setPreferredSize(size); 
    } 

    public synchronized void start() { 
     running = true; 
     thread = new Thread("display"); 
     thread.start(); // start the thread 
    } 

    public synchronized void stop() { 
     running = false; 
     try{ 
      thread.join(); // end the thread 
     }catch(InterruptedException e){ e.printStackTrace(); } 
    } 

    public void run() { 
     while(running){ 
      System.out.println("Running..."); 
     } 
    } 

    public static void main(String[] args) { 
     Client client = new Client(); 
     client.frame.setResizeable(false); 
     client.frame.setTitle("Program test"); 
     client.frame.add(client); 
     client.frame.pack(); 
     client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     client.frame.setLocationRelativeTo(null); 
     client.frame.setVisible(true); 

     client.start(); 
    } 
} 

我努力學習線程,這是一個,如果不是最硬的,事情我曾經學到。 OOP是沒有這個的xD

回答

1

因爲這

new Thread("display"); 

改變它的到

new Thread(this) 

我只是希望你知道你在做什麼。

+0

按秒打我! 1+ –

+1

謝謝,現在我明白了!只是忘了添加它。 (PS。我把它改爲新的主題(這一點,「顯示),它也適用。 –

0

您已經創建了一個通用(讀取空白)線程對象。你需要通過你的課程作爲參數。

thread = new Thread(this); 

這會將您的run方法綁定到Thread對象。線程的名稱通常不是那麼重要。請參閱this example

2

你在錯誤的方式做到這一點, 當你調用client.start();它會調用在Client類啓動功能,並在功能您做出具有默認run方法是空線程類的新實例

您可能意味着這個代碼:

public synchronized void start() { 
    running = true; 
    thread = new Thread(this); 
    thread.start(); // start the thread 
} 

我希望這可以幫助您