Maxime Ozenne Maxime Ozenne -4 years ago 160
Java Question

Java components replacement JPanel

I'm trying to create an application in 3 parts : 3 labels and 3 gridlayouts. When we click on a label, the corresponding gridlayout disappear and the frame replace automatically the components at the right place. I created a simple snippet :

import java.awt.Button;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class TestLayout extends JFrame{
private JPanel content;
private JLabel[] lbl;
private JPanel[] pnl;
private Boolean[] ih;

public TestLayout(){
setSize(new Dimension(300, 400));

lbl = new JLabel[3];
pnl = new JPanel[3];
ih = new Boolean[3];

content = new JPanel(new GridLayout(6, 1));
for(int i=0; i<3; i++){
lbl[i] = new JLabel("Label" + i);
lbl[i].addMouseListener(new MouseAdapter()
public void mouseClicked(MouseEvent e)
for(int i=0; i<3; i++){
if(e.getSource() == lbl[i]){
if(ih[i]) content.remove(pnl[i]);
else content.add(pnl[i]);
ih[i] = !ih[i];

pnl[i] = new JPanel(new GridLayout(3, 3));

for(int i=0; i<9; i++){
pnl[0].add(new Button("" + (i+1)));
pnl[1].add(new Button("" + (i+10)));
pnl[2].add(new Button("" + (i+19)));

for(int i=0; i<3; i++){
ih[i] = true;

public static void main(String[] args){
new TestLayout();

The first problem is the use of a global gridlayout which resize all the components at the same size, but I think it would be better if labels could be smaller than the grilayouts.

The second problem is that even if the gridlayout is removed or setVisible(false), it still take a blank place in the global container.

What I get :

enter image description here

What I was expecting :

enter image description here

The only thing I don't wanna use is a GridBagLayout.

I was thinking about create a method init() which one remove all components of the global container then re add all the labels and all the panels, then create another method which do the exact same as the init() method but take a number as parameter (for example 2) then re add all the components excepting the second gridlayout. But I think it's a dirty way to do that because the container will content an empty case at the end and I think there is a better way than removing and re adding all the components (which basically doesn't solve the first problem of label's size)

How can I avoid theses problems ?

Answer Source

Try using a vertical BoxLayout.

Read the section from the Swing tutorial on How to Use BoxLayout for more information and working examples.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download