簡體   English   中英

在點擊時動態地將swing組件添加到gui?

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

從理論上講,當添加這樣的新組件時

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();
                }
        });

如果您沒有以正常方式聲明它,是否可以使用getSelectedIndex()getText()

是的,您可以通過這種方式將Swing組件添加到容器中。 但是,您需要在面板上調用revalidate ,否則它們可能不會立即顯示。

如果在創建這些組件后需要訪問它們,請將構造函數返回的值分配給在類內部聲明的對象的字段。 您不能在調用方法中分配變量,因為構造函數是從內部類調用的。

有幾種方法可以將動態添加的組件添加到擺動樹:

第一種方法:

panel.getComponent(n);

返回面板中的第n個組件(容器)。 (n是該組件添加到其父組件的順序(父組件在此處是panel ))(您需要知道組件的索引)可以使用((JComboBox)panel.getComponent(3)).getSelectedIndex()

第二種方法

動態添加組件時直接添加一些偵聽器;

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();

});

這樣,您無需訪問動態添加的組件。

第三種方法可能是使用框架進行數據綁定,

第四種方法 ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM