2012-12-14 51 views
1

JFrame WaitingFrame中的內容未按預期顯示。這在本質上是什麼,我試圖做的:從特定方法調用時,JFrame中的內容未顯示

package org.brbcoffee.missinggui; 

import java.net.*; 
import java.io.*; 
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 

public class Main { 
    public static KeynoteServer server; 
    public static void main(String[] args){ 
     JFrame frame = new JFrame("SSCCE"); 
     JButton btn = new JButton("Test"); 
     btn.addActionListener(new ActionListener(){ 
      @Override 
      public void actionPerformed(ActionEvent arg0) { 
       connectToPhone(); 
      } 
     }); 
     frame.add(btn); 
     frame.pack(); 
     frame.setVisible(true); 
    } 
    public static void connectToPhone(){ 
     WaitingFrame wf = new WaitingFrame(); 
     wf.setVisible(true); 
     server = new KeynoteServer(); 
     if (server.setup()){ 
      System.out.println("Server set up and connected"); 
     } else { 
      System.out.println("Couldn't connect"); 
     } 
     wf.dispose(); 
    } 
} 

@SuppressWarnings("serial") 
class WaitingFrame extends JFrame { 
    public WaitingFrame(){ 
     setTitle("Waiting"); 
     this.setLocationByPlatform(true); 

     JLabel label = new JLabel("Waiting for client..."); // This will never show 
     JPanel content = new JPanel();   
     content.add(label); 

     this.add(content); 
     pack(); 
    } 
} 
class KeynoteServer{ 
    private int port = 55555; 
    private ServerSocket server; 
    private Socket clientSocket; 

    public boolean setup() { 
     try { 
      server = new ServerSocket(55555); 
      server.setSoTimeout(10000); 
      clientSocket = server.accept(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      return false; 
     } 
     return true; 
    } 
} 

當設置()被稱爲WaitingFrame確實出現,但內容缺失。我嘗試過不同的圖像格式,但它可以從其他方法和類中使用,所以這應該不重要。有人知道這裏發生了什麼嗎?

+0

1)爲了更快提供幫助,請發佈[SSCCE](http://sscce.org/)。 2)請參閱[多個JFrames的使用,好/壞的實踐?](http://stackoverflow.com/a/9554657/418556)3)不要阻塞EDT(Event Dispatch Thread) - GUI將「凍結'當這種情況發生時。爲長時間運行的任務實現'SwingWorker'。有關更多詳細信息,請參見[Swing中的併發](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/)。 –

+1

謝謝安德魯,我會努力使它成爲SSCCE並更新我的問題。我還會將所有項目從使用多個JFrame移開,特別是關於在我的任務欄中有幾個圖標的部分實際上一直困擾着我,所以爲什麼我一直在做這件事超出了我的想象。 – BjornSnoen

+0

良好的編輯(但仍希望看到一個SSCCE)。 –

回答

2

使用SwingUtilities.invokeLater()/invokeAndWait()來顯示您的框架,因爲所有的GUI應該從EDT更新。

+0

謝謝!正確使用(至少我希望我正確使用它)解決了我的問題。我整晚都在搔着頭,把頭髮扯出來,現在我終於可以睡着了,謝謝你。如果只有我有足夠的聲望來投票你... – BjornSnoen