简体   繁体   English

在点击时动态地将swing组件添加到gui?

[英]Dynamically add swing component to gui on click?

Purely theoretically when adding new components like that 从理论上讲,当添加这样的新组件时

JButton buttonAdd= new JButton("Add More");
        buttonAdd.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                  panel.add(new JComboBox<String>(data);
                  panel.add(new JTextField();
                }
        });

Is there way to getSelectedIndex() or getText() when u don't declare it in normal way? 如果您没有以正常方式声明它,是否可以使用getSelectedIndex()getText()

Yes, you can add Swing components to the container this way. 是的,您可以通过这种方式将Swing组件添加到容器中。 However you need to call revalidate on the panel, otherwise they may not appear instantly. 但是,您需要在面板上调用revalidate ,否则它们可能不会立即显示。

If you need to access these components after they are created, assign the value returned by constructor to the field of your object, declared inside your class. 如果在创建这些组件后需要访问它们,请将构造函数返回的值分配给在类内部声明的对象的字段。 You cannot assign to the variable in the calling method as the constructors are called from the inner class. 您不能在调用方法中分配变量,因为构造函数是从内部类调用的。

there are several ways to reach dynamicaly added components to swing tree: 有几种方法可以将动态添加的组件添加到摆动树:

1st approach: 第一种方法:

panel.getComponent(n);

returns n'th component in the panel (Container). 返回面板中的第n个组件(容器)。 (n is the order, that component added to its parent (parent is panel here) ) (you need to know component's index) this way you can use ((JComboBox)panel.getComponent(3)).getSelectedIndex() (n是该组件添加到其父组件的顺序(父组件在此处是panel ))(您需要知道组件的索引)可以使用((JComboBox)panel.getComponent(3)).getSelectedIndex()

2nd approach 第二种方法

directly add some listeners when dynamically adding your components; 动态添加组件时直接添加一些侦听器;

JButton b1 = new JButton("add");
b1.addActionListener(e -> {  

    JComboBox<String> color = new JComboBox<String>();
    color.addActionListener(x -> { myFormBean.setColor(color.getSelectedItem();) });
    panel.add(color);

    JTextField name = new JTextField();
    name.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
            myFormBean.setName(name.getText());
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            myFormBean.setName(name.getText());
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            myFormBean.setName(name.getText());
        }
    });
    panel.add(name);

    panel.revalidate();
    panel.repaint();

});

this way you do not need to reach your dynamically added components. 这样,您无需访问动态添加的组件。

3rd approach may be using a framework for data binding, 第三种方法可能是使用框架进行数据绑定,

4rd approach ... 第四种方法 ...

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

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