Java Swing: Enabling/Disabling all components in JPanel

前端 未结 4 1321
醉梦人生
醉梦人生 2020-12-09 21:40

I have a JPanel which contains a JToolbar (including few buttons without text) and a JTable and I need to enable/disable (make internal widgets not clickable). I tried this:

4条回答
  •  温柔的废话
    2020-12-09 22:19

    It requires a recursive call.

    Disable All In Container

    import java.awt.*;
    import javax.swing.*;
    
    public class DisableAllInContainer {
    
        public void enableComponents(Container container, boolean enable) {
            Component[] components = container.getComponents();
            for (Component component : components) {
                component.setEnabled(enable);
                if (component instanceof Container) {
                    enableComponents((Container)component, enable);
                }
            }
        }
    
        DisableAllInContainer() {
            JPanel gui = new JPanel(new BorderLayout());
    
            final JPanel container = new JPanel(new BorderLayout());
            gui.add(container, BorderLayout.CENTER);
    
            JToolBar tb = new JToolBar();
            container.add(tb, BorderLayout.NORTH);
            for (int ii=0; ii<3; ii++) {
                tb.add(new JButton("Button"));
            }
    
            JTree tree = new JTree();
            tree.setVisibleRowCount(6);
            container.add(new JScrollPane(tree), BorderLayout.WEST);
    
            container.add(new JTextArea(5,20), BorderLayout.CENTER);
    
            final JCheckBox enable = new JCheckBox("Enable", true);
            enable.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent ae) {
                    enableComponents(container, enable.isSelected());
                }
            });
            gui.add(enable, BorderLayout.SOUTH);
    
            JOptionPane.showMessageDialog(null, gui);
        }
    
        public static void main(String[] args)  {
            SwingUtilities.invokeLater(new Runnable(){
                @Override
                public void run() {
                    new DisableAllInContainer();
                }
            });
        }}
    

提交回复
热议问题