tomas
tomas

Reputation: 739

Swing GridBagLayout - auto-resize fields

This is a piece of code generated from netbeans Swing gui designer. I'm trying to do the following: jLabel1 and jLabel2 will contain only image icon with dimension 52x46 px without text, they should be fixed in the left and right side of the line, jTextField2 is expected to fill the gap between jlabels and autoresize to full screen/view width.

Problem is, that jTextField2 remains with same width no matter what size of window/view is... The initial width is dependent on the length of hard-coded text inside the field...

Do you have any idea, how to do this?

private void initComponents() {
    javax.swing.JLabel jLabel1;
    javax.swing.JLabel jLabel2;
    javax.swing.JTextField jTextField2;

    java.awt.GridBagConstraints gridBagConstraints;

    jLabel1 = new javax.swing.JLabel();
    jTextField2 = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().setLayout(new java.awt.GridBagLayout());

    jLabel1.setText("ABC");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
    getContentPane().add(jLabel1, gridBagConstraints);

    jTextField2.setText("some text field content");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridwidth = java.awt.GridBagConstraints.RELATIVE;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    getContentPane().add(jTextField2, gridBagConstraints);

    jLabel2.setText("ABC");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
    getContentPane().add(jLabel2, gridBagConstraints);

    pack();
}

Upvotes: 3

Views: 14248

Answers (1)

Aubin
Aubin

Reputation: 14853

See documentation of GridBagLayout

GridBagConstraints.weightx, GridBagConstraints.weighty

Used to determine how to distribute space, which is important for specifying resizing behavior. Unless you specify a weight for at least one component in a row (weightx) and column (weighty), all the components clump together in the center of their container. This is because when the weight is zero (the default), the GridBagLayout object puts any extra space between its grid of cells and the edges of the container.

jTextField2.setText("some text field content");
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridwidth = java.awt.GridBagConstraints.RELATIVE;
gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;

gridBagConstraints.weightx = 1.0; //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

getContentPane().add(jTextField2, gridBagConstraints);

Upvotes: 12

Related Questions