我試圖將文本追加到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
。
某個地方的東西很可能沒有適當地連線,但根據上面的代碼我看不到。您應該考慮創建併發布[sscce](http://sscce.org)或[最小示例程序/ mcve](http://stackoverflow.com/help/mcve),您可以將代碼壓縮到最小位仍然編譯和運行,沒有外部依賴性(例如需要鏈接到數據庫或圖像),沒有額外的代碼與您的問題無關,但仍顯示您的問題。請注意,您的sscce不應使用MigLayout或任何其他外部依賴項。把事情簡單化。 –
我的猜測是:你可能會隱藏代碼中未顯示的變量。 –
@AbishekManoharan:請刪除您誤導性的評論。在JTextArea上調用'append(...)'之後永遠不需要調用'revalidate()'。 –