2014-01-23 56 views
0

我正在設計一個簡單的GUI(在Eclipse中使用WindowBuilder Pro),該按鈕只在按下按鈕(測試)後在textArea之後顯示「Hello World」按鈕不會顯示文本區域中的文本

http://i.stack.imgur.com/PbYo8.jpg

然而,當我按下按鈕,它不會在文本區域顯示出來!有人可以調整代碼或至少告訴我該怎麼做?

public class TextA { 

private JFrame frame; 


/** 
* Launch the application. 
*/ 
public static void main(String[] args) { 
    EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      try { 
       TextA window = new TextA(); 
       window.frame.setVisible(true); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

/** 
* Create the application. 
*/ 
public TextA() { 
    initialize(); 
} 

/** 
* Initialize the contents of the frame. 
*/ 
private void initialize() { 
    frame = new JFrame(); 
    frame.setBounds(100, 100, 450, 300); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.getContentPane().setLayout(null); 

    JTextArea textArea = new JTextArea(); 
    textArea.setBounds(113, 44, 226, 96); 
    frame.getContentPane().add(textArea); 

    JButton btnTesting = new JButton("Testing"); 
    btnTesting.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 

      JTextArea textArea = new JTextArea(); 
      textArea.setText("Hello World!"); 


     } 
    }); 
    btnTesting.setBounds(168, 167, 117, 29); 
    frame.getContentPane().add(btnTesting); 
} 
} 
+3

您正在動作偵聽器內部創建一個新的'JTextArea',並在其上設置文本。這與您添加到「JFrame」中的文本區域不同。 – crush

+2

Java GUI可能需要在多種平臺上工作,使用不同的屏幕分辨率並使用不同的PLAF。因此,它們不利於組件的準確放置。爲了組織強大的圖形用戶界面,請使用佈局管理器或[它們的組合](http://stackoverflow.com/a/5630271/418556)以及[空格]的佈局填充和邊框(http: //stackoverflow.com/q/17874717/418556)。 –

+0

或者,使用JavaFX,您可以製作更豐富,更精確的GUI。 – SnakeDoc

回答

1

您正在處理錯誤的JTextArea對象。它應該看起來像這樣:

final JTextArea textArea = new JTextArea(); // final added here 
textArea.setBounds(113, 44, 226, 96); 
frame.getContentPane().add(textArea); 

JButton btnTesting = new JButton("Testing"); 
btnTesting.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 

      //JTextArea textArea = new JTextArea(); this should be removed. 
      textArea.setText("Hello World!"); 


     } 
    }); 
+0

是的,它的工作!非常感謝你 – Mike

3

將您的代碼更改爲像這樣的東西。

final JTextArea textArea = new JTextArea(); 
frame.getContentPane().add(textArea); 
btnTesting.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      textArea.setText("Hello World!"); 
     } 
    }); 

您在裏面創建一個新的實例actionListener你想引用您要添加到幀的對象。而作爲@AndrewThompson總是勸告不使用null佈局的原因:

Java的圖形用戶界面可能需要在多個平臺上工作,使用不同PLAFs不同 屏幕分辨率&。因此,他們不是 有利於組件的準確放置。要組織可靠的GUI組件 ,請改爲使用佈局管理器或它們的組合,以及用於空白區域的佈局填充&邊框。

0

您正在actionPerformed(ActionEvent e)中創建一個新的JTextArea對象。只需使用已經定義的文本區域對象並進行最終確定,因爲它將用於動作事件方法。你可以在action事件方法中刪除行JTextArea textArea = new JTextArea(),它應該可以工作。

+0

這就是我說的或至少嘗試:)。也許我應該更清楚。 –