【问题标题】:Add textField data to a list. Swing将 textField 数据添加到列表中。摇摆
【发布时间】: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


【解决方案1】:

您可以从JtextFieldgetText() 方法获取文本并使用add() 将其添加到list player。下面给出的是代码。

player.add(txt.getText());

查看以下链接了解更多详情:

【讨论】:

    【解决方案2】:

    您需要将 ActionListener 添加到 JButton 中

    button.addActionListener(this);
    

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

    player.add(txt.getText());
    

    【讨论】:

    • 谢谢。我已经更新了我的问题,请随时阅读。 :)
    • 尝试了解(使用 system.out.println 或调试模式)e.getSource() 中的源是什么,如果它真的是您的按钮。
    【解决方案3】:

    您只需要从文本字段中获取文本。

    player.add(txt.getText())
    

    这将做你想要的。

    您将在此处获得 TextField 中的当前字符串。所以你可以将它添加到你的列表中。

    【讨论】:

    • 谢谢。我已经更新了我的问题,请随时阅读。 :)
    猜你喜欢
    • 2012-02-29
    • 1970-01-01
    • 2020-11-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 2014-03-02
    • 2022-09-24
    • 2016-03-01
    相关资源
    最近更新 更多