java - 将文本字段数据添加到列表中。 Swing

标签 java swing jtextfield jlist

我想创建一个小型 swing 应用程序,它从文本字段获取输入并将其放入 ArrayList 中。该代码无法正常工作,我需要一些帮助。

编辑。修复了语法。现在我无法让代码工作。它不会将文本字段数据添加到列表中。请帮忙。

这是代码:

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

}

我是 Swing 新手,编码才几周时间。 :/

最佳答案

您需要将 ActionListener 添加到 JButton

button.addActionListener(this);

然后在 actionPerformed 中将 JTextfield 的文本添加到列表中:

player.add(txt.getText());

关于java - 将文本字段数据添加到列表中。 Swing ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26929739/

相关文章:

java - @Bean注解的使用

java - Apache POI - 如何在 Grails 应用程序中提供 excel 文件下载

Java FTP 无法在 SwingWorker 线程内工作

java - 用于呈现未知行数的 JTable

java - 调整许多 JTextField 的高度

java - 我们可以在我们的 Java 应用程序中使用 MST 吗?

Java:检查给定的IP和端口是否是代理服务器

java - Swing 中 "Container c=getContentPane();"的用途是什么?

java - 如何通过按 JButton 将单个字符添加到 JTextField

java - 重叠 JTextField 和 JLabel