How to control the width of jtextfields in Java swing?

I try to have several jtextfields on a single line, but I don't want them to have the same width How do I control the width and make some of them wider than others? I want them to occupy 100% of the total width together, so it would be good if I could use some way

I've tried Setcolumns(), but it doesn't make any sense

Here is an example. I use three rows, which should be displayed as columns:

import java.awt.GridLayout;
import javax.swing.@R_448_2419@Layout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class RowTest extends JPanel {

    class Row extends JComponent {
        public Row(String str1,String str2,String str3) {
            this.setLayout(new @R_448_2419@Layout(this,@R_448_2419@Layout.X_AXIS));

            JTextField fld1 = new JTextField(str1);
            JTextField fld2 = new JTextField(str2);
            JTextField fld3 = new JTextField(str3);

            fld1.setColumns(5); // makes no sense

            this.add(fld1);
            this.add(fld2);
            this.add(fld3);
        }
    }

    public Rowtest() {
    this.setLayout(new GridLayout(5,0));

    this.add(new Row("Short","A long text that takes up more space","Short again"));
    this.add(new Row("Longer but short","Another long string","Short"));
    this.add(new Row("Hello","The long field again","Some info"));
    }

    public static void main(String[] args) {
        new JFrame() {{ this.getContentPane().add(new Rowtest());
                            this.pack(); this.setVisible(true); }};
    }

}

Solution

All swing components have a preferred size The preferred size of a text component is based on the text of the component Therefore, the assembly is usually painted in its preferred size

So I can't see the problem with your code segment Each text field should have a different preferred size In addition, when the frame is resized, the width will be adjusted because @ r_ 448_ 2419@Layout Will try to resize each component to the maximum / minimum size

If you need more help, you can publish your sscce to actually demonstrate the size problems you encounter

Edit:

According to the latest requirements, you can use relative layout

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>