Arraylist and JTextArea Display issue

132 views Asked by At

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();
    }
}
2

There are 2 answers

1
MadProgrammer On BEST ANSWER

I believe you're looking for JTextArea#append, which will allow you to keep "appending" text to the end of the text area, as apposed to replacing it with new text, which is what setText will do

1
Programmer On

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