javaswingjpanellayout-manager

Is there a way of moving JPanel in BorderLayout?


I am using a BorderLayout for the frame (the first one that "caught" my attention in the tuts) and a FlowLayout for the labels (the one I found appropriate for what I do), and the result shows up like this:

enter image description here

My objective is to push the "2*1" a little bit down, to sort of "center" it.

I looked around and found a lot of people saying to use a null layout, but then saying it's not the best alternative (even though my window is not resizable), and the other solution I found was using a combo of layouts (unless I misunderstood).

The question is the one on top of this, plus if not, what really is the best alternative? (The following is the code that makes this window (minus the vars and other methods, to simplify visualization).

public Frame() {
    super("Jogo de Multiplicar!");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new BorderLayout());
    setSize(300, 200);
    setResizable(false);
    getContentPane().setBackground(pink);

    mensagem = new TransparentPanel();
    operacao = new TransparentPanel();  

    //added stuff in mensagem and operacao

    add(operacao);
    add(mensagem, BorderLayout.SOUTH);
}

Solution

  • My objective is to push the "2*1" a little bit down, to sort of "center" it.

    If you just want more space at the top then you can use a Border:

    operacao.setBorder( new EmptyBorder(...) );

    Read the section from the Swing tutorial on How to Use Borders for more information.

    If you want to actually center it you can use a BoxLayout:

    Box box = Box.createVerticalBox();
    box.add( Box.createVerticalGlue() );
    box.add( topPanel );
    box.add( Box.createVerticalGlue() );
    box.add( bottomPanel );
    

    The tutorial also has a section on How to Use BoxLayout. Search the table of contents.