[英]Java Swing - Dynamically create JTextField
I want to create several JTextFields that I can then get the user data from once they hit a submit button. 我想创建几个JTextField,然后在用户单击提交按钮时从中获取用户数据。 I am using the code below to dynamically create labels for the text fields and was planning on creating the text fields in a similar way, but I realized that if I do that the fields won't have variable names and I won't be able to extract the data. 我正在使用下面的代码为文本字段动态创建标签,并计划以类似的方式创建文本字段,但是我意识到,如果这样做,那么这些字段将没有变量名,并且我将无法提取数据。 Is there a way to dynamically assign variable names or otherwise retrieve the data from the text fields if I create them in a way similar to what's shown below? 如果我以类似于下面所示的方式创建变量名,是否可以动态分配变量名或从文本字段检索数据?
int autoX = 0;
int autoY = 0;
for (int i = 0; i< units.numOfUnits(); i++ ){
c.gridx = (autoX % 5);
c.gridy = autoY;
if((autoX % 5) == 4){
autoY++;
}
mainPanel.add(new JLabel(units.getUnit(i)),c);
autoX++;
}
You need to keep a reference to the text fields you create. 您需要保留对创建的文本字段的引用。 Like this: 像这样:
List<JTextField> textFields = new ArrayList<JTextField>();
int autoX = 0;
int autoY = 0;
for (int i = 0; i< units.numOfUnits(); i++ ){
c.gridx = (autoX % 5);
c.gridy = autoY;
if((autoX % 5) == 4){
autoY++;
}
mainPanel.add(new JLabel(units.getUnit(i)),c);
JTextField textField = new JTextField();
mainPanel.add(textField);
textFields.add(textField);
autoX++;
}
Then you can refer to a specific text field with: 然后,您可以使用以下内容引用特定的文本字段:
textFields.get(0).getText();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.