2017-09-23 53 views
0

GUI初學者在這裏。Java GUI按鈕不會將字符串打印到接口

我的問題是沒有創建一個GUI界面,但有2個按鈕打印界面內的JTextArea中的字符串。
第一個「學習」按鈕從數組中取一個隨機元素並打印出來。 第二個按鈕「清除」只是在按下時打印一個字符串 我對這兩個按鈕都有動作偵聽器,但仍然無法完全獲取它。

謝謝你的時間。

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.util.Random; 


public class GUI extends JFrame { 


String [] sentences = {"Random sentence 1", "random sentence 2", "random sentence 3", "random sentence 4", random sentence 5", "random sentence 6"}; 


private Container contents; 
JButton learned = new JButton("Learned"); 
JButton clear = new JButton("Clear"); 
JTextArea clearDisplay; 


public GUI() 
{ 
    super ("GUI"); //title bar text 

    contents = getContentPane(); 
    contents.setLayout(new FlowLayout()); //make buttons appear 

    //set the layout manager 

    //instantiate buttons 
    learned = new JButton("I Learned"); 
    clear = new JButton("Clear"); 

    //add components to window 
    contents.add(learned); 
    contents.add(clear); 



    //instantiate event handler 
    ButtonHandler bh = new ButtonHandler(); 

    //add event handler as listener for both buttons 
    learned.addActionListener (bh); 
    clear.addActionListener(bh); 

    setSize (400, 200); //size of window 
    setVisible (true); //see the window 

    } 


    public class ButtonHandler implements ActionListener 
    { 
    //implement ActionPerformed method 

    public void actionPerformed(ActionEvent e) 
    { 
     Container contentPane = getContentPane(); 
     if (e.getSource() == learned) 
     { 
     String random = (sentances[new Random().nextInt(sentances.length)]); //random from array   
     JTextArea learned = new JTextArea(random); 
     } 
     else if (e.getSource() == clear)   
     { 
      JTextArea clearDisplay = new JTextArea("This is where it will display what I learned. \\nMessage Displayed Here."); 
     } 

    } 

} 

public static void main(String[] args) 
{ 
    GUI basicGui = new GUI(); 
    basicGui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //program exits on close        
} 

} 

回答

2

你的問題是在這裏:

else if (e.getSource() == clear)   
    { 
     JTextArea clearDisplay = new JTextArea("This is where it will display what I learned. \\nMessage Displayed Here."); 
    } 

你正在創建一個從來沒有被添加到GUI一個新的JTextArea。你應該這樣寫:

else if (e.getSource() == clear)   
    { 
     clearDisplay = new JTextArea("This is where it will display what I learned. \\nMessage Displayed Here."); 
    } 

並將其添加到GUI。

您還應該考慮另一種方法:首先創建JTextField,將其添加到GUI中,然後只更改其上面代碼中的文本。

而且,你有一些拼寫錯誤的位置:

String random = (sentances[new Random().nextInt(sentances.length)]); 
+0

.................好的回答 –

1

不要創建你的動作偵聽器中的新JTextAreas。而是在GUI的構造函數和偵聽器中創建一個JTextArea,只需將適當的文本寫入JTextArea,或者通過調用.setText(...)來完全更改文本,或者.append(...)如果您想向現有文本添加其他文本。

+0

添加了public JTextArea textArea = new JTextArea();到構造函數。 並在components部分添加contents.add(textArea); 然後添加動作事件textArea.setText(random);和textArea.setText(「This ....」);它跑了!非常感謝! – Mike