Search code examples
javaarraysarraylistbuttonclick

Enter a string and add to a list every time a button is clicked, while displaying all strings entered


I am trying to create a Java program where you enter a word into a textfield, and click a button and the string is added to an output box.

I got that part, but I am trying to make it so that every time the button is clicked, a word gets added, and then all the words are listed in the output box.

I tried using Arrays and Arraylists with loops, but no success. Any help is appreciated.

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

import java.util.ArrayList;
import java.util.Arrays;

public class test extends JFrame {

    private JLabel label;
    private JButton button;
    private JTextField textfield;
    private JTextArea result;
    // private String [] words;
    private ArrayList<String> list = new ArrayList<String>();

    // Contructor
    public test() {
        setLayout(new FlowLayout());

        label = new JLabel("Word:");
        add(label);

        textfield = new JTextField(15);
        add(textfield);

        button = new JButton("Add data to list");
        add(button);

        result = new JTextArea(10, 15);
        add(result);

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                result.setText(textfield.getText());
                // int n = list.size();
                // for(int i = 0; i < n ; i++)
                // result.setText(list.get(i));
            }
        });

    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        // System.out.println("Hello");
        test gui = new test();
        gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.setVisible(true);
        gui.setSize(200, 325);
        gui.setTitle("Title");
    }
}

Solution

  • What you're doing now completely replaces the contents of the JTextArea with that of the JTextField, which is not what you want. You instead want to add the contents of textfield to what already exists in result, with something along the lines of:

    result.setText(result.getText() + "\n" + textfield.getText());