2015-06-18 112 views
0

我試圖將文本追加到JTextArea。我知道如何通過事件監聽器添加文本,但是我似乎無法理解如何從主要方法調用方法來添加文本。文本被追加到JTextArea中,但JTextArea組件沒有被更新/重繪/重新驗證/驗證(或者你應該說的:-))。將文本添加到JTextArea

GUITest

​​

GUI

public class GUI extends JPanel { 
    private static final long serialVersionUID = 1L; 

    private ConsolePanel console; 
    private static GUI instance; 

    private GUI() { 
     console = new ConsolePanel(); 

     add(console); 
    } 

    public static GUI getInstance() { 
     if(instance == null) instance = new GUI(); 

     return instance; 
    } 

    public void createAndShowGUI() { 
     // Create window 
     JFrame f = new JFrame("GUI"); 

     f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     f.setBackground(Color.decode("#333333")); 
     f.setResizable(false); 

     // Create the content pane 
     JComponent c = new GUI(); 

     c.setOpaque(false); 
     f.setContentPane(c); 

     // Draw the window 
     f.pack(); 
     f.setVisible(true); 
    } 

    public void addTxt(String txt) { 
     console.addTxt(txt); 
    } 
} 

ConsolePanel

public class ConsolePanel extends JPanel { 
    private static final long serialVersionUID = 1L; 
    private JTextArea console; 

    public ConsolePanel() { 
     console = new JTextArea("Init...", 10, 10); 

     add(console); 
    } 

    public void addTxt(String txt) { 
     console.append(txt); 
    } 
} 

如何正確執行addTxt法,使 「測試1」, 「Test2的」 ..也被添加並顯示在文本組件上?

修正:

改變了線JComponent c = new GUI()JComponent c = instance

+1

某個地方的東西很可能沒有適當地連線,但根據上面的代碼我看不到。您應該考慮創建併發布[sscce](http://sscce.org)或[最小示例程序/ mcve](http://stackoverflow.com/help/mcve),您可以將代碼壓縮到最小位仍然編譯和運行,沒有外部依賴性(例如需要鏈接到數據庫或圖像),沒有額外的代碼與您的問題無關,但仍顯示您的問題。請注意,您的sscce不應使用MigLayout或任何其他外部依賴項。把事情簡單化。 –

+2

我的猜測是:你可能會隱藏代碼中未顯示的變量。 –

+0

@AbishekManoharan:請刪除您誤導性的評論。在JTextArea上調用'append(...)'之後永遠不需要調用'revalidate()'。 –

回答

2

您正在createAndShowGUI方法中創建一個新的TestGUI(或GUI,具體取決於您如何命名它),因此您有兩個這樣的野獸。不要這樣做。只創建一個。

+0

你說得對。我已將它改爲「JComponent c = instance'。 – eli

+0

@ user2832479:正好。我自己,我會從GUI或TestGUI類完全取出createAndShowGUI方法,因爲它不屬於那裏。 –

+0

- 並解決了問題。你是我的英雄! :-) – eli