Reputation: 1105
I have a JPanel
and inside it are two JLabel
components: headerLabel
and timeLabel
The problem is that I'm having trouble making headerLabel
sit in the center of the panel and timeLabel
sit to the far right. I have tried several different Layout Managers (GridBagLayout
, BorderLayout
etc.) and techniques (Box.createHorizontalStrut(X)
, adding Insets
) and they all either end up pushing headerLabel
to the far left and timeLabel
to the far right or placing them both in the center.
Below is a graphical representation of how I want it to look:
Is there a particular Layout Manager I should be using to get this result?
Upvotes: 1
Views: 1340
Reputation: 324118
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.
Upvotes: 4
Reputation: 13858
You should be able to get there with GridBagLayout.
headerPanel will sit at 0,0 with FILL_BOTH, centered and fillx = 1.0
timePanel will sit at 0,1 and no further fill options.
Now the display for those will largely depend on big your original panel is rendered. If it is inside a JDialog or any other container that's pack()
ed, all they will still appear "side by side" as this is the best way to layout those elements.
If this still bugs you, you could assign minimum & preferred size to headerPanel so that packing will not shrink it below that size.
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{1.0, 0.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, Double.MIN_VALUE};
setLayout(gridBagLayout);
JLabel lblHeader = new JLabel("HEADER");
GridBagConstraints gbc_lblHeader = new GridBagConstraints();
gbc_lblHeader.weightx = 1.0;
gbc_lblHeader.insets = new Insets(0, 0, 0, 5);
gbc_lblHeader.gridx = 0;
gbc_lblHeader.gridy = 0;
add(lblHeader, gbc_lblHeader);
JLabel lblTime = new JLabel("TIME");
GridBagConstraints gbc_lblTime = new GridBagConstraints();
gbc_lblTime.gridx = 1;
gbc_lblTime.gridy = 0;
add(lblTime, gbc_lblTime);
Upvotes: 1