Search code examples
javaswingjlabellayout-managerborder-layout

how to place jlabel in a specific position in the jpanel


in the below code i am trying to place a jlabel with the word "Demo" in the center of the upper horizontal axis of the jpanel.

but at run time the word "Demo" is aleays place in the center of the left vertical axis.

please let me know how can modify the code below to set the word "DEmo" in the center of the upper horizontal axis of the jpanel

Code:

public class GUITabs {

JFrame jFrame_Main;
JPanel jPanel_ContainerPanel;
JLabel jLabel_ContainerLabel;

public GUITabs() {
    // TODO Auto-generated constructor stub
    setUpGUI();
}

private void setUpGUI() {
    // TODO Auto-generated method stub
    jFrame_Main = new JFrame("Main Window");
    jPanel_ContainerPanel = new JPanel(new BorderLayout());
    jPanel_ContainerPanel.setBorder(BorderFactory.createLoweredBevelBorder());
    jLabel_ContainerLabel = new JLabel("Demo");

    jFrame_Main.add(jLabel_ContainerLabel, BorderLayout.CENTER);
    jFrame_Main.pack();
    jFrame_Main.setVisible(true);
}

Solution

  • If I understand correctly, you want the label to be at the top of the frame, centered horizontally.

    To place the label at the top, use BorderLayout.NORTH instead of BorderLayout.CENTER.

    To align the label to the center rather than left, use

    label.setHorizontalAlignment(SwingConstants.CENTER)