gpt4 book ai didi

java - 从 vector 或数组创建动态形式

转载 作者:行者123 更新时间:2023-12-01 12:01:03 24 4
gpt4 key购买 nike

首先,我是java新手。我想基于数组动态生成表单,我能够生成字段,但我不知道如何读取它们,我找不到诸如文本字段索引之类的东西。所以基本上我问的是如何从没有引用的 TextField 组件中读取值。JTextField myText = new JTextField() 与 new JTextField(),添加到面板下面是一个简单的代码示例,欢迎任何想法。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Test extends JFrame{
private JPanel p1 = new JPanel();
private JButton btn = new JButton("Read Data");

public Test(){
super("Dynamic Form");
setLayout(new GridLayout(4,2));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

// Declare the Array with fields
String[] fList = new String[3];
fList[0] = "id";
fList[1] = "firstName";
fList[2] = "lastName";

//Iterate fields array and add elements
for(int i = 0; i<fList.length; i++){
add(new JLabel(fList[i]));
add(new JTextField("field: "+fList[i]));
}

add(p1);
add(btn);

btn.addActionListener(
new ActionListener(){
@Override
public void actionPerformed(ActionEvent ev){
String id = "id field value is: "; // + some code to get actual text field value
String firstName = "firstName field value is: "; // + some code to get actual text field value
String lastName = "lastName field value is: "; // + some code to get actual text field value

System.out.println(id+ " " + firstName + " " + lastName);
}
}
);

pack();
setLocationRelativeTo(null);
setResizable(true);
setVisible(true);
}

public static void main(String [] args){
new Test();
}
}

最佳答案

您需要将对这些文本字段的引用存储在某处。

List<JTextField> fields = new ArrayList<>();

...

for(int i = 0; i<fList.length; i++){
JTextField field= new JTextField("field: "+fList[i]);
add(new JLabel(fList[i]));
add(field);
fields.add(field);
}

现在您可以从字段列表中访问它们:

public void actionPerformed(ActionEvent ev){
String id = "id field value is: " + fields.get(0).getText();
String firstName = "firstName field value is: " + fields.get(1).getText();
String lastName = "lastName field value is: " + fields.get(2).getText();

System.out.println(id+ " " + firstName + " " + lastName);
}

关于java - 从 vector 或数组创建动态形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27980792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com