For Each循环首先构建然后检索JTextField输入



我对编码还很陌生,现在有点碰壁了。

我有一个字符串数组,我在循环中使用它来构建JLabel和相应的JTextField。

String[] textFieldList = {"Name", "Age", "Height", "weight"};
formPanel.setLayout(new BoxLayout(formPanel, BoxLayout.Y_AXIS));
for (String tfL : textFieldList) {
    JLabel jl = new JLabel(tfL);
    JTextField jtf = new JTextField("");
    jtf.setName(tfL);
    formPanel.add(jl);
    formPanel.add(jtf);
}
addPanel.add(formPanel, BorderLayout.CENTER);

我有一个保存按钮,我想检索所有输入的值,所以我试图使用相同的数组来获得每个JTextField的名称,方法是使用相同的字符串数组来获取每个文本字段的值。

我还没能成功地构建一个对我有用的循环。

saveBtn.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent arg0) {     
        for (String tfL : textFieldList) {              
            tfL.getText()                   
        }
    }
});

有没有一种方法可以让我正确地构建循环来返回字符串结果,我可以测试返回的值,看看它们是否应该被解析为int。

如果有人能给我指明正确的方向,那就太好了。

您所需要做的就是创建jtextfield数组并使用普通循环来增强。在您的代码中,您不能使用tfL.getText(),因为tfL是字符串而不是jtextfield。但在我的代码中我已经标记了textfield array named jtextf,因此您可以使用.getText() 获取值

 JTextField[] jtextf;// global variable
 String[] textFieldList = {"Name", "Age", "Height", "weight"};
 jtextf=new JTextField[textFieldList.length];
 formPanel.setLayout(new BoxLayout(formPanel, BoxLayout.Y_AXIS));
    for (int i=0;i<textFieldList.length;i++) {
        JLabel jl = new JLabel(tfL);
        jtextf[i] = new JTextField("");
        jtextf[i].setName(textFieldList[i]);
        formPanel.add(jl);
        formPanel.add(jtextf[i]);
    }
}

当你想重新设定使用

saveBtn.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent arg0) {     
        for (JTextField field: jtextf) {              
            field.getText()                   
        }
    }
});

最新更新