我想创建一个小型 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/