Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 558
skyork Avatar asked May 14 '11 22:05

skyork


People also ask

How do I center text in JTextField?

Just use the setBounds attribute. Jtextfield. setBounds(x,x,x,x);

Can JTextField be used as an alternative to JLabel?

a) JTextField cannot be used as an alternative to JLabel.

How is JTextField different from JLabel?

JLabel is a component used for displaying a label for some components. It is commonly partnered with a text field or a password field. JTextField is an input component allowing users to add some text.

What is JTextField in Java Swing?

JTextField is a lightweight component that allows the editing of a single line of text. For information on and examples of using text fields, see How to Use Text Fields in The Java Tutorial. JTextField is intended to be source-compatible with java. awt. TextField where it is reasonable to do so.


2 Answers

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.

like image 65
Andrew Thompson Avatar answered Oct 06 '22 01:10

Andrew Thompson


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);
like image 35
MByD Avatar answered Oct 06 '22 01:10

MByD