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.
Just use the setBounds attribute. Jtextfield. setBounds(x,x,x,x);
a) JTextField cannot be used as an alternative to 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.
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.
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:
Use the label alignment that pushes the text to the RHS.
See also this answer for an MCVE.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With