Kharbora
Kharbora

Reputation: 129

Add textField data to a list. Swing

I want to create a little swing application that takes input from the text field and puts it in a ArrayList. The code is not working and I need some help.

EDIT. Fixed the syntax. Now the i cant get the code to work. It wont add the textfield data to the list. Please help.

Here is the code:

public class GUI extends JPanel implements ActionListener{

JButton button = new JButton(" >> CLICK ME <<");
final JTextField txt = new JTextField("Enter player name.");
static List <String> player = new ArrayList <String> ();

public GUI(){

    txt.setBounds(1, 1, 300, 30);

    JButton button = new JButton(" >> ADD PLAYER <<");

    button.setBounds(40, 40, 200, 40);

    setLayout(null);
    add(txt);
    add(button);

    button.addActionListener(this);


}

public void actionPerformed(ActionEvent e) {

    if (e.getSource().equals(button)) {
        player.add(txt.getText());
        System.out.println("Added: " + txt.getText() + " to the list.");
    }
    else
        System.out.println("Adding the textField data to the list did not work.");


}


public static void main(String[] args) {

    JFrame frame1 = new JFrame("Memory Game. Add player function.");
    frame1.getContentPane().add(new GUI());

    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame1.setSize(310, 130);
    frame1.setVisible(true);

}

I am new to swing and have only been coding for a couple of weeks. :/

Upvotes: 0

Views: 4433

Answers (3)

Johny
Johny

Reputation: 2188

You can get text from JtextField getText() method and use add() to add it to a list player. Given below is the code.

player.add(txt.getText());

Check the links below for more details:

Upvotes: 2

dor47
dor47

Reputation: 61

You need to add the ActionListener to the JButton with

button.addActionListener(this);

And then add in the actionPerformed the text of the JTextfield to the list :

player.add(txt.getText());

Upvotes: 2

Lukas Hieronimus Adler
Lukas Hieronimus Adler

Reputation: 1094

You only need to get the text from the textfield.

player.add(txt.getText())

This will do what you want to have.

There you will get the current String which is in the TextField. So you can add it into your List.

Upvotes: 1

Related Questions