使用 JButton 在 JDialog 上重新加载组件

Reload components on a JDialog using JButton

我正在开发一个 JDialog,其中包含一些内部组件,如 JLabel、JButton 等...这些内容通过文件填充。还有一个 JComboBox,它定义应读取哪个文件,每次更改此 JComboBox 时,我都需要刷新我的 JDialog。找到了 this,但我还不知道如何处理它。

这就是我现在正在做的事情:

public class ConfDialog extends JDialog
{

     public ConfDialog(JFrame parent, String title, int whidth, int eight)
     {
         super(parent, title, Dialog.ModalityType.APPLICATION_MODAL);

         this.setSize(new Dimension(whidth, eight));
         this.setLocation(200, 200);
         this.setResizable(false);
         this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

         components();
     }

     public void components()
     {

         //JLabels, JButtons, ecc... declarations

         final JComboBox<File> box = new JComboBox<File>(stuffInFolder);

         box.addActionListener(new ActionListener()
         {
             public void actionPerformed(ActionEvent e)
             {
                 validate();//<----
                 repaint(); //<----
             }
         });

         //...something else...

     }

     @Override
     public void repaint()
     {
         components();
         super.repaint();
     }

 }

JComboBoxActionListener被触发时,读取选中的文件,然后根据文件中的信息,更新UI的state/properties根据需要添加组件,例如,在您的标签、字段和按钮上调用 setText

public class ConfDialog extends JDialog {

    public ConfDialog(JFrame parent, String title, int whidth, int eight) {
        super(parent, title, Dialog.ModalityType.APPLICATION_MODAL);

        this.setSize(new Dimension(whidth, eight));
        this.setLocation(200, 200);
        this.setResizable(false);
        this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

        components();
    }

    public void components() {

        //JLabels, JButtons, ecc... declarations
        final JComboBox<File> box = new JComboBox<File>(stuffInFolder);

        box.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                File file = (File) box.getSelectedItem();
                if (file != null) {
                // Read file
                    // Update the fields on your UI, using things like setText 
                    // and other methods which change the output of the UI
                }
            }
        });

        //...something else...
    }

}

大多数组件都足够智能,可以自我更新。如果仍有问题,可以调用 revalidate 然后调用 repaint