Centering a Jlabel on a JPAnel

Centering a JLabel on a JPanel

By using Borderlayout, you can put any of JComponents to the CENTER area. For an example, see an answer to Stack Overflow question Get rid of the gap between JPanels. This should work.

How to center JLabel in a panel with BoxLayout

To vertically center the components you need to add "glue" at the start and end:

jpanel.add(Box.createVerticalGlue());
jpanel.add(label1);
jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
jpanel.add(label2);
jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
jpanel.add(label3);
jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
jpanel.add(label4);
jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
jpanel.add(label5);
jpanel.add(Box.createVerticalGlue());

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

Java align JLabel in center of JPanel

As I see it you need the label to be displayed at its preferred size and then you need a left and right panel to equally fill the remaining space available in the window.

You can use the Relative Layout class.

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

public class RelativeSSCCE extends JPanel
{
public RelativeSSCCE()
{
JPanel left = new JPanel( new FlowLayout(FlowLayout.LEFT) );
left.add( new JButton("L1") );
left.add( new JButton("L2") );
left.add( new JButton("L3") );

JLabel center = new JLabel("Centered");

JPanel right = new JPanel( new FlowLayout(FlowLayout.RIGHT) );
right.add( new JButton("Right1") );
right.add( new JButton("Right2") );
right.add( new JButton("Right3") );

// choose your layout manager here

setLayout( new RelativeLayout() );
Float ratio = new Float(1);
add(left, ratio);
add(center);
add(right, ratio);
}

private static void createAndShowUI()
{
JFrame frame = new JFrame("Basic RelativeSSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new RelativeSSCCE() );
frame.setSize(600, 100);
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}

public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}

How to center multiple JLabels on one JPanel and how to set the labels text orientation to centered

OK, adding an answer so that others don't waste time here:

As pointed out by Andrew, this can be achieved by combining GridLayout which can be used to create a column of the labels, and setting the text alignment in the labels themselves:

JPanel panel = new JPanel();
// Setting rows to 0 means that new rows are added as needed
panel.setLayout(new GridLayout(0, 1));
panel.add(new JLabel("text", SwingConstants.CENTER));
panel.add(new JLabel("longer text", SwingConstants.CENTER));

GridLayout makes the labels both the same size, so centering the text inside the labels also centers them relative to each other.

Positioning a JLabel in the center of a panel and a JLabel to the right of the same panel

I have tried several different Layout Managers (GridBagLayout, BorderLayout etc.)

Well, post your code. We can't guess what you might be doing.

I would use a BorderLayout.

Add one label to the BorderLayout.CENTER and the other to the BorderLayouyt.LINE_END.

setLayout( new BorderLayout() ):

JLabel center = new JLabel("CENTER");
center.setHorizontalAlignment(JLabel.CENTER); // maybe you are missing this
add(center, BorderLayout.CENTER);

JLabel right = new JLabel("RIGHT");
add(right, BorderLayout.LINE_END);

Which tell the text how to align itself when there is extra horizontal space.

Java Swing - Center a JLabel using BorderLayout

As i said in the comment above, you should clarify what do you mean when you say "the instructions also specify that I must use BorderLayout".

If you mean that your content pane must have a BorderLayout, and the other panels can have a different layout (like in your code, since you are using a FlowLayout in your sub panels), it's easy to solve your issue.

You just need to add your labels in a JPanel which uses a layout that aligns the labels at the center, like GridBagLayout does.
Your first label will have gridx = 0 and gridy = 0, the second label will have gridx = 0 and gridy = 1.
Your second will be exactly below the first one, you can use insets to create some empty space (in the code below i use 5 pixels for Insets.top).

Since your labsPanel will be at BorderLayout.CENTER, the panel will take all the empty space in your frame, and GridBagConstrains.anchor default value (GridBagConstrains.CENTER) makes sure your labels are centered inside your labsPanel. As a result, the labels will be vertically and horizontally aligned at the middle of the frame, like in the screeenshot below:

Sample Image

Code sample:

import java.awt.*;
import javax.swing.*;
public class Test
{
public static void main (String [] a) {
SwingUtilities.invokeLater (new Runnable () {
@Override public void run () {
createAndShowGUI ();
}
});
}
private static void createAndShowGUI () {
JFrame frame = new JFrame ("Test");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setContentPane (new MainPanel ());
frame.pack ();
frame.setLocationRelativeTo (null);
frame.setVisible (true);
}
}
class MainPanel extends JPanel
{
public MainPanel () {
super (new BorderLayout ());

JLabel nameAndReg = new JLabel ("My details", SwingConstants.CENTER);
JLabel errorMsg = new JLabel ("The error message", SwingConstants.CENTER);
nameAndReg.setForeground(Color.blue);

JPanel labsPanel = new JPanel (new GridBagLayout ());

labsPanel.add (nameAndReg);

GridBagConstraints c = new GridBagConstraints ();
c.gridy = 1;
c.insets = new Insets (5, 0, 0, 0);
labsPanel.add (errorMsg, c);

JButton butSubmit = new JButton("Submit");
JButton butReset = new JButton("Reset");

JTextField redVal = new JTextField(3);
JTextField greenVal = new JTextField(3);
JTextField blueVal = new JTextField(3);

JPanel butPanelSouth = new JPanel ();
JPanel butPanelNorth = new JPanel ();

butPanelSouth.add (redVal);
butPanelSouth.add (greenVal);
butPanelSouth.add (blueVal);
butPanelSouth.add (butSubmit);

butPanelNorth.add (butReset);

add (labsPanel, BorderLayout.CENTER);
add (butPanelNorth, BorderLayout.NORTH);
add (butPanelSouth, BorderLayout.SOUTH);
}
}

If all your panels must have a BorderLayout, it's very difficult to achieve what you want, but as i said, it would be a crazy requirement.

how to center JLabel in Jframe Swing?

Change your JLabel's horizontal alignment. The constructor can help you do this by changing:

timerLabel = new JLabel("Time Remaining 300 seconds");

to:

timerLabel = new JLabel("Time Remaining 300 seconds", SwingConstants.CENTER);

Also nest your JPanels each using its own layout. e.g.,

import java.awt.BorderLayout;
import java.awt.GridLayout;

import javax.swing.*;

public class TimerFoo extends JPanel {
public TimerFoo() {
JPanel centerPanel = new JPanel(new GridLayout(0, 2));
centerPanel.add(new JButton("Foo"));
centerPanel.add(new JButton("Bar"));

JLabel bottomLabel = new JLabel("Bottom Label", SwingConstants.CENTER);

int gap = 5;
setLayout(new BorderLayout(gap, gap));
setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
add(centerPanel, BorderLayout.CENTER);
add(bottomLabel, BorderLayout.PAGE_END);
}

private static void createAndShowGui() {
JFrame frame = new JFrame("TimerFoo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TimerFoo());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Centering JLabels inside JPanels

Invoking pack() is a critical step in using layouts. This example uses JLabel.CENTER and GridLayout to center the labels equally as the frame is resized. For simplicity, the center panel is simply a placeholder. This somewhat more complex example uses a similar approach along with java.text.MessageFormat.

Addendum: But how would I apply pack() to my code?

Simply invoke pack() as shown in the examples cited. I don't see an easy way to salvage your current approach of setting sizes extrinsically. Instead, override getPreferredSize() in a JPanel for your main content. No matter the screen size, your implementation of paintComponent() should adapt to the current size, for example.

image

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/** @see https://stackoverflow.com/a/14422016/230513 */
public class Scores {

private final JLabel[] nameLabel = new JLabel[]{
new JLabel("Team 1", JLabel.CENTER),
new JLabel("Team 2", JLabel.CENTER)};

private void display() {
JFrame f = new JFrame("Scores");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel teamPanel = new JPanel(new GridLayout(1, 0));
teamPanel.add(nameLabel[0]);
teamPanel.add(nameLabel[1]);
f.add(teamPanel, BorderLayout.NORTH);
f.add(new JPanel() {

@Override
public Dimension getPreferredSize() {
return new Dimension(320, 240);
}
}, BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
new Scores().display();
}
});
}
}


Related Topics



Leave a reply



Submit