简体   繁体   中英

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.
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.

 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");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM