How can I control the width of JTextFields in Java Swing?

后端 未结 4 1237
醉酒成梦
醉酒成梦 2021-01-03 20:06

I am trying to have several JTextFields on a single row, but I don\'t want them to have the same width. How can I control the width and make some of them wider than others?

相关标签:
4条回答
  • 2021-01-03 20:32

    Try this:

    textfield.setPreferredSize(new Dimension(int width, int height));
    
    0 讨论(0)
  • 2021-01-03 20:40

    All Swing components have a preferred size. The preferred size of a text component is based on the text of the component. So generally the component is painted at its preferred size.

    So I don't see the problem with your code snippet. Each text field should have a different preferred size. Also, as the frame is resized the width will be adjusted since the BoxLayout will try to resize each component up to its maximum/minimum size.

    If you need more help post your SSCCE that actually demonstrates the sizing problem you are experiencing.

    Edit:

    Based on the latest requirement you can use the Relative Layout.

    0 讨论(0)
  • 2021-01-03 20:43
    yourTextField = new JTextField("", 20);
    

    if you start it like this it sets the textfield to be empty and to have 20 collumns

    0 讨论(0)
  • 2021-01-03 20:50
    // 1. create JTextField
    yourTextField = new JTextField();
    // 2. store default height
    int defaultHeight = yourTextField.getSize().getHeight();
    // 3. set custom width and default height
    yourTextField.setSize(new Dimension(yourWidth, defaultHeight));
    
    0 讨论(0)
提交回复
热议问题