How to remove add / remove panel according to checkbox selection?

1

I'm adding a panel at the bottom of a JFrame , when a checkbox is selected, and when I unmark it, remove the panel, and leave only the checkbox, however, I'm not getting it, I think the manager layout is preventing the effect I wanted.

My question is, how can I remove the panel, and leave the check box always in the lower left corner, taking up little space?

Ex:

WhatIdid:

importjavax.swing.*;importjava.awt.*;publicclassTestextendsJFrame{privateJDesktopPanedesktopPane=newJDesktopPane();publicTest(){setTitle("Teste");
        getContentPane().add(desktopPane);
        add("South", new Info(comp()));
        setSize(700, 450);
        setVisible(true);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private JComponent comp() {
        JPanel painel = new JPanel();
        painel.add(new JLabel("Informações ... "));
        return painel;
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            try {
                new Test();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}

class Info extends JPanel {
    private JCheckBox checkBox = new JCheckBox("Click");
    private JComponent component;

    public Info(JComponent component) {
        this.component = component;
        setPreferredSize(new Dimension(30, 30));
        add(checkBox);

        checkBox.addActionListener(e -> {
            if (checkBox.isSelected()) {
                component.setVisible(true);
                component.setPreferredSize(new Dimension(500, 30));
            } else {
                component.setVisible(false);
                component.setPreferredSize(new Dimension(0, 0));
            }
            revalidate();
        });

        add(checkBox, BorderLayout.WEST);
        add(component, BorderLayout.EAST);
    }
}
    
asked by anonymous 24.06.2018 / 21:05

1 answer

4

I've made some changes to your code to work correctly:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;

public class JCheckBoxComJpanelLado extends JFrame {

    private JDesktopPane desktopPane = new JDesktopPane();
    private Info infoPanel =  new Info();

    public JCheckBoxComJpanelLado() {

        setTitle("Teste");
        setPreferredSize(new Dimension(700, 450));

        getContentPane().add(desktopPane, BorderLayout.CENTER);

        JPanel auxPanel = new JPanel(new BorderLayout());
        auxPanel.setPreferredSize(new Dimension(Integer.MAX_VALUE, 30));
        auxPanel.setBackground(desktopPane.getBackground());

        JCheckBox checkBox = new JCheckBox("Click");

        checkBox.addItemListener(e -> infoPanel.setVisible(e.getStateChange() == ItemEvent.SELECTED));

        auxPanel.add(checkBox, BorderLayout.WEST);
        auxPanel.add(infoPanel, BorderLayout.CENTER);

        getContentPane().add(auxPanel, BorderLayout.SOUTH);

        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> new JCheckBoxComJpanelLado());
    }
}

class Info extends JPanel {

    public Info() {

        add(new JLabel("Informações ... "));
        setVisible(false);
    }
}

What I changed in the code was as follows:

  • This catch taking Exception is a waste of resources, if you do not know if it will handle an exception, do not add generic try / catchs, since they do not help at all in the code.

  • >
  • When working with layout, you need to use preferred sizes , and how do I explain in this other answer , the setSize() method is not ideal for use in these situations. The pack() method must be invoked so that the screen is rendered correctly, taking these sizes into account;

  • >
  • I created an auxiliary panel to hold the checkbox and the other panel in the window footer. I had to set the height ( Integer.MAX_VALUE is to leave the width in charge of layoutManager) because when displaying the other panel, the checkbox and it seemed to have different sizes, and this corrects that problem.

  • To make the help panel appear to be shorter when the Info panel is not visible, set the background color to the same as your desktopPane. with equal colors, they blend into the screen.

  • In the helper panel I used BorderLayout for not forcing me to define custom sizes for the checkbox and panel info , making the latter fill the rest of the space to the right without having to define anything.

  • I think the panel needs to get hidden, so that it only appears when the checkbox is selected. So I changed the visibility right after it was created. revalidate() is unnecessary in this case.

  • I have simplified the change of state of the checkbox, after all, the visibility of the info panel is according to the state of its selection, so you do not have to do an if only to validate it.

  • >

The result is:

Irecommendreadingthe tutorial about layouts managers to learn more about them work and how to handle and combine them seamlessly.

    
24.06.2018 / 22:09