How to align JLabel-JTextField pairs vertically

前端 未结 7 1119
独厮守ぢ
独厮守ぢ 2020-12-11 02:33

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.

相关标签:
7条回答
  • 2020-12-11 03:13

    or

    there is possible align just text inside JTextComponents with

    JLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
    
    0 讨论(0)
  • 2020-12-11 03:22

    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.

    0 讨论(0)
  • 2020-12-11 03:23

    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.

    0 讨论(0)
  • 2020-12-11 03:26

    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.

    0 讨论(0)
  • 2020-12-11 03:29

    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);
    
    0 讨论(0)
  • 2020-12-11 03:29

    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.

    0 讨论(0)
提交回复
热议问题