Grigore Dodon
Grigore Dodon

Reputation: 147

align left and right two JLabels in a "North" BorderLayout

I am using BorderLayout for my application. setLayout(new BorderLayout()); I need to align two JLabels in left and right in the "NORTH" of the JPanel.

Here is my code:

JPanel top = new JPanel();
top.add(topTxtLabel);
top.add(logoutTxtLabel);
add(BorderLayout.PAGE_START, top);

So I need topTxtLabel in left and logoutTxtLabel in right. I tried to implement Border Layout again to use "WEST" and "EAST", but it didn't worked. Ideas?

Upvotes: 2

Views: 7449

Answers (1)

BluesSolo
BluesSolo

Reputation: 608

Assuming your application consists of a JFrame with BorderLayout you could try this: Set the layout mode of your JPanel again to BorderLayout. Add the panel in the north of the frame. Then add the 2 JLabels in the east and west. You can also replace the JFrame with another JPanel.

import java.awt.BorderLayout;

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


public class Main 
{

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

    Main()
    {
        JFrame frame = new JFrame("MyFrame");
        frame.setLayout(new BorderLayout());

        JPanel panel = new JPanel(new BorderLayout());
        JLabel left = new JLabel("LEFT");
        JLabel right = new JLabel("RIGHT");
        JPanel top = new JPanel(new BorderLayout());

        top.add(left, BorderLayout.WEST);
        top.add(right, BorderLayout.EAST);
        panel.add(top, BorderLayout.NORTH);
        frame.add(panel, BorderLayout.NORTH);
        frame.add(new JLabel("Another dummy Label"), BorderLayout.SOUTH);

        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Upvotes: 2

Related Questions