将textField数据添加到列表。 Swing

问题描述:

我想创建一个小的swing应用程序,它将文本字段的输入内容放入ArrayList。代码无法正常工作,我需要一些帮助。将textField数据添加到列表。 Swing

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

下面是代码:

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

} 

我新的摆动,只被编码为两个星期。 :/

+0

1)Java的图形用户界面必须工作在不同的操作系统',屏幕大小,屏幕分辨率等。因此,它们不利于像素的完美布局。请使用布局管理器或[它们的组合](http://stackoverflow.com/a/5630271/418556)以及[white space]的布局填充和边框(http://stackoverflow.com/a/17874718/ 418556)。 2)源代码中的单个空白行是所有需要的。 '{'之后或'}'之前的空行通常也是多余的。 – 2014-11-14 12:17:13

+0

@AbdiTem你的新问题是什么? – 2014-11-14 12:37:46

+0

@LukasHieronimusAdler的添加功能不起作用。 – Kharbora 2014-11-14 12:51:34

您可以从JtextFieldgetText()方法获取文本并使用add()将它添加到一个list player。以下是代码。

player.add(txt.getText()); 

检查下面的详细信息的链接:

你只需要得到从文本框的文本。

player.add(txt.getText()) 

这会做你想要的。

在那里你会得到TextField中的当前String。所以你可以将它添加到你的列表中。

+0

谢谢。我已经更新了我的问题,请随时通读它。 :) – Kharbora 2014-11-14 12:30:41

您需要的的ActionListener添加到的JButton与

button.addActionListener(this); 

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

player.add(txt.getText()); 
+0

谢谢。我已经更新了我的问题,请随时通读它。 :) – Kharbora 2014-11-14 12:31:08

+0

尝试了解(使用system.out.println或调试模式)e.getSource()中的源代码是什么,如果它真的是您的按钮。 – dor47 2014-11-14 13:09:25