How to remove add/remove dashboard as you select from checkbox?

Asked

Viewed 112 times

1

I’m adding a panel at the bottom of a JFrame, when a checkbox this selected, and when I uncheck it, remove the panel, and leave only the checkbox, however, I’m not getting, I think the layout manager 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:

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

What I did:

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

public class Test extends JFrame {
    private JDesktopPane desktopPane = new JDesktopPane();

    public Test() {
        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);
    }
}
  • Why are you using desktoppane for something so trivial? What’s the need?

  • In my system, I use, it has more screens, menus and etc. I didn’t want to waste time putting it here, since it won’t influence.

  • You need a panel for that Jlabel anyway?

  • The label was just to show, I will put other things, the important thing, is to exbir and remove this panel, leaving the label always there in the corner

1 answer

4


I made some changes to your code to make it work properly:

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 this:

  • This catch catching Exception is a waste of resource, if you do not know if you will treat an exception, do not add generic Try/catchs as they do not help at all in code.

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

  • As the checkbox will control the visibility of the other panel, I turned it into a class attribute and moved as a direct component on the screen, this facilitates visibility control and simplifies code;

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

  • to give the effect of the auxiliary panel appears to be shorter when the panel Infois not visible, set its background color to the same as your desktopPane. with equal colors, they mix on the screen.

  • On the auxiliary panel I used BorderLayout by not forcing me to set custom sizes for the checkbox and dashboard info, making this last fill the rest of the space on the right without having to define anything.

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

  • I simplified the checkbox status change, after all, the info panel visibility is according to its selection state, so you don’t need to do an if just to validate it.

The result is:

inserir a descrição da imagem aqui

I recommend reading the tutorial regarding managers layouts to learn better how they work and how to handle and combine them smoothly.

  • I had been trying to put the smaller checkbox panel because I was trying to get it on the side of the panel with the information label. The intention was to leave the area occupied by comp() free, because it is in front of a screen if it is too large. That way, if you hide it, the checkbox panel will still occupy that area

  • @The Alunooracle that borders the Gambiarra and it is not possible to do it simply, nor with that Eneric code that Oce provided. It might work well for him, but if yours is different, it might not work.

  • and send him behind the desktopPane, it is possible ?

  • 1

    @Alunooracle actually, now rereading his doubt, I understood what he wants to do and after a brief research, I saw that it is possible to organize components by superimposing. I’ll edit the answer with this option.

  • @Alunooracle see the update.

  • that’s it! Thank you !

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.