[英]Arraylist and JTextArea Display issue
I was wondering if someone can point me in the right direction. 我想知道是否有人可以指出我正确的方向。
I am trying to create a GUI that takes input, and when a button is pressed it adds it to a JTextArea. 我试图创建一个接受输入的GUI,并在按下按钮时将其添加到JTextArea。
I want to be able to keep doing this until the exit button is clicked. 我希望能够一直这样做,直到单击退出按钮。
I can get the first input to display, but I have spent a lot of time trying to figure out how to keep adding input till the exit button is clicked. 我可以显示第一个输入,但是我花了很多时间试图弄清楚如何继续添加输入,直到单击退出按钮为止。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.util.ArrayList;
public class Window extends JFrame{
private final int WIDTH=400;
private final int HEIGHT=200;
private JButton button;
private JTextArea textArea;
private JTextField textField;
private JPanel panel;
private JButton exit;
public Window() {
super("TextArea");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
buildPanel();
add(panel);
setVisible(true);
}
public void buildPanel(){
panel= new JPanel();
textField = new JTextField(10);
textArea = new JTextArea();
button = new JButton("Add");
button.addActionListener(new Calc());
exit = new JButton("exit");
exit.addActionListener(new ExitListener());
panel.add(textField);
panel.add(button);
panel.add(exit);
panel.add(textArea);
}
private class Calc implements ActionListener{
public void actionPerformed(ActionEvent e){
ArrayList<String> array= new ArrayList<String>();
String str = (String) textField.getText();
array.add(str);
textArea.setText(str);
}
}
private class ExitListener implements ActionListener{
public void actionPerformed(ActionEvent e){
System.exit(0);
}
}
public static void main(String []args){
new Window();
}
}
我相信您正在寻找JTextArea#append
,它将允许您将“追加”文本保留在文本区域的末尾,就像用新文本替换它一样,这是setText
作用
Try this code it should work and I also suggest that you should add JScrollPane in your TextArea. 试试这个代码,它应该可以工作,我也建议您在TextArea中添加JScrollPane。
private class Calc implements ActionListener{
public void actionPerformed(ActionEvent e){
ArrayList<String> array= new ArrayList<String>();
String str = (String) textField.getText();
array.add(str);
textArea.append(str + "\n");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.