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

时间:2015-07-03 06:28:48

标签: java swing repaint

我正在开发一个包含JLabels,JButtons等内部组件的JDialog ......这些东西都是通过文件填充的。 Ther也是一个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();
     }

 }

1 个答案:

答案 0 :(得分:2)

当触发ActionListener的{​​{1}}时,读取所选文件,然后根据文件中的信息,根据需要更新UI组件的状态/属性,例如,调用标签,字段和按钮上的JComboBox

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