Q:

Swing layout problem

Hello I'd like to get this swing layout inside a JPanel:
JLabel - JTextField - JComboBox
as the panel resizes I'd like the textField to expand but not the other two. Everything must remain in line. I tried grid bag layout but doesn't work... or I can't. Ideas?

A:

If you have three components and want the one in the middle to expand, you can for example use a BorderLayout, put your JLabel at BorderLayout.WEST, your JComboBox at BorderLayout.EAST and the one you want to expand (JTextField) at BorderLayout.CENTER.
The following is ugly, but the intent is to be minimal yet show the behavior you want:
public class Gotch {
    public static void main( String[] args ) {
        JFrame main = new JFrame();
        JPanel p = new JPanel();
        p.setLayout( new BorderLayout() );
        p.add( new JLabel( "test" ), BorderLayout.WEST );
        p.add( new JTextField( "growable" ), BorderLayout.CENTER );
        p.add( new JComboBox(), BorderLayout.EAST );
        main.add( p );
        main.pack();
        main.setVisible( true );
    }
}

A:

Thought I'd post some code how to do it with GridBagLayout as well. Could be useful for when you have something that does not fit so perfectly with BorderLayout, which will be often when making GUIs.
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        JFrame frame = new JFrame("GridBagLayout Demo");
        frame.setLayout(new GridBagLayout());

        JLabel label = new JLabel("Demo Label");
        JTextField textField = new JTextField("Demo Text");
        JComboBox comboBox = new JComboBox(new String[] {"hello", "goodbye", "foo"});

        GridBagConstraints cons = new GridBagConstraints();
        cons.insets = new Insets(10, 10, 10, 10);
        frame.add(label, cons);

        cons.gridx = 1;
        cons.weightx = 1;
        cons.weighty = 1;
        cons.insets = new Insets(10, 0, 10, 10);
        cons.fill = GridBagConstraints.HORIZONTAL;

        frame.add(textField, cons);

        cons.gridx = 2;
        cons.weightx = 0;
        cons.weighty = 0;
        cons.insets = new Insets(10, 0, 10, 10);
        cons.fill = GridBagConstraints.NONE;

        frame.add(comboBox, cons);

        frame.pack();
        frame.setVisible(true);
    }
}

