首页 > 解决方案 > 如何从 Java Swing 中多次使用的同一文本字段中获取文本

问题描述

我正在尝试从通过我的代码迭代的 JTextField 获取文本(显然,我无法从按钮添加不同的文本字段)。以下是“添加项目”按钮的作用:

addButton.addActionListener(new ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent e) {
        tf = new JTextField("Name",20);
        tfv = new JTextField("Value", 7); 
        
        p.revalidate();
        p.repaint();   
        
        p.add(tf);
        p.add(tfv);
    }
});

它使用 FlowLayout 在面板中添加了两个新的文本字段。现在,我想通过单击“确定”按钮从文本字段中获取用户给出的文本,每个文本字段都分配给不同的变量,或者可能进入 ArrayList,但 getText() 方法似乎不起作用。

okButton.addActionListener( e -> {
    
        String txt = tfv.getText(); //only captures the text from the last field in the panel

});

现在好像什么都想不起来。

在此处输入图像描述

标签: javaswingjtextfield

解决方案


在此代码中,当您重新初始化tf并且丢失对先前定义的文本字段的引用时tfvaddButton

tf = new JTextField("Name",20);
tfv = new JTextField("Value", 7);

所以要解决这个问题,您需要定义一个 ArrayList 来保存对所有已定义文本字段的引用,然后您可以访问所有这些:

ArrayList<JTextField> arrayNames  = new ArrayList<JTextField>();
ArrayList<JTextField> arrayValues = new ArrayList<JTextField>();

addButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        tf = new JTextField("Name",20);
        tfv = new JTextField("Value", 7); 
        
        p.revalidate();
        p.repaint();   
        
        p.add(tf);
        p.add(tfv);

        arrayNames.add(tf);
        arrayValues.add(tfv);
    }
});

访问

okButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        for (JTextField txtValue : arrayValues) {
            System.out.println(txtValue.getText());
        }
    }
});

推荐阅读