How to align JLabel-JTextField pairs vertically
What I mean by a JLabel-JTextField pai开发者_JAVA技巧r 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.
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);
or
there is possible align just text inside JTextComponents with
JLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
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);
...
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.
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.
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.
精彩评论