【发布时间】:2015-01-11 19:54:37
【问题描述】:
我想创建一个小摇摆应用程序,它从文本字段中获取输入并将其放入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 新手,只写了几个星期的代码。 :/
【问题讨论】:
-
1) Java GUI 必须在不同的操作系统、屏幕尺寸、屏幕分辨率等上工作。因此,它们不利于像素完美布局。而是使用布局管理器,或combinations of them 以及white space 的布局填充和边框。 2) 源代码中的一个空白行是永远需要的。
{之后或}之前的空行通常也是多余的。 -
@AbdiTem 你的新问题是什么?
-
@LukasHieronimusAdler 添加功能不起作用。
标签: java swing jtextfield jlist