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

Posted by Jonas on Stack Overflow See other posts from Stack Overflow or by Jonas
Published on 2010-05-24T13:59:15Z Indexed on 2010/05/24 14:01 UTC
Read the original article Hit count: 337

Filed under:
|
|
|
|

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? I want that they together take up 100% of the total width, so it would be good if I could use some kind of weigthing.

I have tried with .setColumns() but it doesn't make sense.

Here is my code:

class Row extends JComponent {
        public Row() {
            this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

            JTextField fld1 = new JTextField("First field");
            JTextField fld2 = new JTextField("Second field, should be longer");
            JTextField fld3 = new JTextField("Short field");
            JTextField fld4 = new JTextField("Another field");

            fld1.setBorder(null);
            fld2.setBorder(null);
            fld3.setBorder(null);
            fld4.setBorder(null);

            fld1.setFocusable(false);
            fld2.setFocusable(false);
            fld3.setFocusable(false);
            fld4.setFocusable(false);

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

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

        this.setLayout(new GridLayout(20,0));

        this.add(new Row());
        this.add(new Row());
        this.add(new Row());

© Stack Overflow or respective owner

Related posts about java

Related posts about swing