简体   繁体   English

JCombobox和JTextfield

[英]JCombobox and JTextfield

I'm trying to work to display a number of jtextfield according to one of the given values in a combobox. 我正在尝试根据组合框中的给定值之一显示一些jtextfield。

So, I will have a drop down menu with let's say 1 to 4. If the user selects number 3, 3 textfields will be displayed. 因此,我将使用一个1至4的下拉菜单。如果用户选择数字3,则将显示3个文本字段。 I've created the jcombobox with a selection of numbers. 我用数字选择创建了jcombobox。 But I'm not sure how to implement this. 但是我不确定如何实现这一点。 If I'm not mistaken I need to use 如果我没记错的话,我需要使用

ItemEvent.SELECTED

I think I need to create a reference to the JTextField object that will be available to the JComboBox's itemListener object. 我想我需要创建对JTextField对象的引用,该引用将可用于JComboBox的itemListener对象。

Any help would be greatly appreciated. 任何帮助将不胜感激。

I've added this to my class : 我已经将此添加到我的课程中:

// aOption is the combobox I declared 
aOptionComboBox.setModel(new DefaultComboBoxModel(new String[]{"1","2","3"})); 

public void itemStateChanged(ItemEvent event) {

    String num = (String)aOptionComboBox.getSelectedItem(); 
    int num1 = Integer.parseInt(num);
    JTextField[] textfields = new JTextField[num1];

    for (int i = 0; i < num1; i++) 
    {
        textfields[i] = new JTextField("Field");
        getContentPane().add(textfields[i]);
        textfields[i].setBounds(200, 90, 100, 25);

    }
}

am I on a right track? 我在正确的轨道上吗?

use the getSelectedItem() on the combobox. 在组合框上使用getSelectedItem()。 This will either yield a string or an integer (depending on how you implemented it). 这将产生一个字符串或一个整数(取决于您实现它的方式)。 Next use a for-loop to determine the amount of JTextField's and store them in an array. 接下来,使用for循环确定JTextField的数量并将其存储在数组中。

int amount = myJComboBox.getSelectedItem();

JTextField[] textfields = new JTextField[amount];

for (int i = 0; i < amount; i++) {
textfields[i] = new JTextField("awesome");
this.add(textfields[i]);
}

this way you can easily store the textfields and add them to your panel. 这样,您可以轻松地存储文本字段并将其添加到面板中。

Some added information. 一些补充信息。

The textfield-array must be accesible outside the eventListener, so you must implement it in your class. textfield-array必须在eventListener之外是可访问的,因此您必须在类中实现它。 that way the whole class can use it. 这样整个班级都可以使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM