无需单击按钮即可动态添加组件

时间:2011-09-06 07:04:11

标签: java swing runtime jcomponent

我在点击按钮时在运行时动态添加组件。 但现在我想动态添加组件而不点击按钮。 我怎样才能做到这一点..??这是我在单击Button时添加组件的源代码。

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        String[] items = new String[4];
        items[0]="English";
        items[1]="French";
        items[2]="Spanish";
        items[3]="Hindi";
        JTextField jtextfield = new JTextField();
        jtextfield.setPreferredSize(new Dimension(50, 20));
        JButton jbutton = new JButton();
        jbutton.setText("Remove");
        jbutton.setPreferredSize(new Dimension(89, 23));

        JLabel jlabel = new JLabel();
        jlabel.setText("Text:");
        jlabel.setPreferredSize(new Dimension(40, 20));
        JLabel jlabel2 = new JLabel();
        jlabel2.setText("Language:");
        jlabel2.setPreferredSize(new Dimension(65, 20));

        JComboBox jcombo = new JComboBox();
        jcombo.setPreferredSize(new Dimension(80,20));
        jcombo.addItem(items[0]);
        jcombo.addItem(items[1]);
        jcombo.addItem(items[2]);
        jcombo.addItem(items[3]);

        jPanel6.add(jlabel);
        jPanel6.add(jtextfield);
        jPanel6.add(jlabel2);
        jPanel6.add(jcombo);
        jPanel6.add(jbutton);

        jbutton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                Component[]storeAllButtonInPanel = jPanel6.getComponents();

                if(storeAllButtonInPanel.length!=0) {
                    jPanel6.remove(storeAllButtonInPanel.length-1);
                    jPanel6.remove(storeAllButtonInPanel.length-2);
                    jPanel6.remove(storeAllButtonInPanel.length-3);
                    jPanel6.remove(storeAllButtonInPanel.length-4);
                    jPanel6.remove(storeAllButtonInPanel.length-5);

                    jPanel6.revalidate();
                    validate();
                    repaint();
                }
            }

        });



        jPanel6.validate();
        jPanel6.repaint();
    }

如果我只有2个Text值,那么它也显示两行,如果有3个值那么应该只有3行.. !!我怎么能这样做??

2 个答案:

答案 0 :(得分:2)

不知道你想要什么,需要/需要一些控制,作为输出到GUI和使用一些Listener(作为你的ActionListener),

可能(完全控制)JPopupMenuAPI,示例herehere

答案 1 :(得分:2)

javax.swing.Timer的实例可以定期调用ActionListeneractionPerformed()方法,如example中所建议的那样添加和删除JLabel。< / p>