skyork
skyork

Reputation: 7381

How to align JLabel-JTextField pairs vertically

What I mean by a JLabel-JTextField pair is a JLabel component followed by a JTextField one, for example, "Parameter 1: -----" where "-----" denotes a blank JTextField.

The problem is, the width of JLabels varies due to the varying lengths of parameter names, so that the starts of JTextFields are not aligned vertically.

Is there any way to align the JLabels vertically to their right, so that the starts of JTextFields that follow would be aligned? Thanks.

Upvotes: 10

Views: 35712

Answers (7)

Andrew Thompson
Andrew Thompson

Reputation: 168815

Is there any way to align the JLabels vertically to their right, so that the starts of JTextFields that follow would be aligned?

1.6+, GroupLayout. E.G. from the JavaDocs:

enter image description here

Use the label alignment that pushes the text to the RHS.


See also this answer for an MCVE.

Upvotes: 7

MByD
MByD

Reputation: 137282

You didn't specify which layout do you use, so a good layout to implement that would be GridBagLayout. The demo in oracle site is great to start with.

And a short example:

JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
panel.add(new JLabel("Label 1:"), c);
c.gridx = 1;
c.gridy = 0;
panel.add(new JTextField("TextField 1"), c);
c.gridx = 0;
c.gridy = 1;
panel.add(new JLabel("Label 2:"), c);
c.gridx = 1;
c.gridy = 1;
panel.add(new JTextField("TextField 2"), c);

Upvotes: 6

jfpoilpret
jfpoilpret

Reputation: 10519

This is a perfect use case for DesignGridLayout:

DesignGridLayout layout = new DesignGridLayout(contentPane);
layout.labelAlignment(LabelAlignment.RIGHT);
layout.row().grid(label1).add(field1);
layout.row().grid(label2).add(field2);
...

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Good solutions for this that I've seen include use of the GridBagLayout (as noted above) or the MiGLayout, though since the latter isn't part of standard Java, it must be downloaded and placed on the classpath prior to use. MiGLayout is not as difficult to use.

Upvotes: 1

mKorbel
mKorbel

Reputation: 109815

or

there is possible align just text inside JTextComponents with

JLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);

Upvotes: 3

Osiris76
Osiris76

Reputation: 1244

I would suggest the GridLayout layout manager. It presents the easiest solution to show pair-wise visualization of label and textbox controls. Thereby you simply define the number of rows and columns at time of instantiation and the added controls will be handled by the manager.

Upvotes: 1

SJuan76
SJuan76

Reputation: 24780

The LayoutManager of the parent component has the responsability of positioning the elements contained. Maybe you need to set an XYLayout.

See the setLayoutManager() for your parent class.

Upvotes: 0

Related Questions