[英]Adding elements from JTextField to ArrayList
所以我有一個包含GUI的作業,其中包含:
JTextField
,允許用戶在文本字段中輸入輸入 AddButton
將輸入添加到ArrayList中 ListButton
在JTextArea
顯示ArrayList的JTextArea
問題是:當我輸入[1,2,3]時,輸出僅顯示最后一個元素[3],該如何解決?
public class Example extends JFrame {
private final int WINDOW_WIDTH = 300;
private final int WINDOW_HEIGHT = 300;
private JPanel panel1, panel2;
private JLabel messageLabel;
private JTextField input;
private JTextArea output;
private JButton addButton, listButton;
String userInput;
ArrayList<String> list = new ArrayList<>();
public Example() {
setTitle("Array Exercise");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
panel1 = new JPanel();
panel1.setLayout(new GridLayout(6,1));
messageLabel = new JLabel("Input");
input = new JTextField(5);
addButton = new JButton("Add");
listButton = new JButton("List");
panel1.add(messageLabel);
panel1.add(input);
panel1.add(addButton);
panel1.add(listButton);
add (panel1, BorderLayout.WEST);
output = new JTextArea(12, 10);
panel2 = new JPanel();
panel2.add(output);
add(panel2, BorderLayout.EAST);
setVisible(true);
input.requestFocus();
ButtonListener bh = new ButtonListener();
addButton.addActionListener(bh);
listButton.addActionListener(bh);
}
private class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
userInput = input.getText();
if (e.getSource() == addButton) {
list.add(userInput);
output.setText(userInput + " added.");
input.setText("");
input.requestFocus();
}
else if (e.getSource() == listButton) {
list.stream().forEach(x-> output.setText(x));
}
}
}
JTextField將其文本更改為列表中每個元素的新文本。 您要做的是這樣的:
for(String s : list){
outPut.append(s + "\n");
}
//Use "\n" if you want each string on a new line. Otherwise, skip it
(為了清楚起見,我使用了這種類型的for循環)
現在,它“添加”(附加)列表中的每個新字符串。 在您的代碼中,它將文本設置為第一個String。 將文本設置為第二個String(依此類推)。 因此,請記住使用setText(“”);清除區域。 每次您想打印出來時,例如,一個新的字符串列表。
補充奧斯卡的答案:
setTest()
設置文本區域的整個文本,覆蓋以前的內容。 因此,最后一個值集是最后將保存的(唯一)一個值。
由於已經在使用Streams,因此可以使用:
output.setText(list.stream().collect(Collectors.joining("\n")));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.