[英]Java- How to set a variable/id name to different JTextFields?
I have created a frame and 2 panels in Java, the first panel have some buttons and the other panel will show the new TextFields.我在 Java 中创建了一个框架和 2 个面板,第一个面板有一些按钮,另一个面板将显示新的 TextFields。 After those textfields are created.
创建这些文本字段之后。 I want to get the text in each textfield but i dont know how to get each text if i dont have an specific variable name for each one.
我想获取每个文本字段中的文本,但如果我没有每个文本的特定变量名,我不知道如何获取每个文本。
public class GUIListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
if(e.getSource()==boton2){
System.out.println("boton 2");
takeData();
}else if(e.getSource()==boton3){
System.out.println("boton 3");
createTextFields(4);
}
}
}
public void createTextFields(int quantity){
panel2.removeAll();
for(int i =0;i<quantity;i++){
texto = new JTextField("TF # "+i);
panel2.add(texto);
}
panel2.validate();
panel2.repaint();
}
public void takeData(){
System.out.println(texto.getText());
//Only prints the text of the last textfield created
}
Save all the JTextField
s in a collection or array and return them.将所有
JTextField
保存在集合或数组中并返回它们。
public JTextField[] createTextFields(int quantity) {
panel2.removeAll();
JTextField[] textFields = new JTextField[quantity];
for(int i =0;i<quantity;i++) {
texto = new JTextField("TF # "+i);
panel2.add(texto);
textFields[i] = texto;
}
panel2.validate();
panel2.repaint();
return textFields;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.