Search code examples
javaswingheightlayout-managerpack

java swing can't expand JFrame's height?


I created a JFrame and set a JPanel as its content panel, I added about 30 buttons into that container but the JFrame shows me one line of buttons and it won't allow me expand the height.

public class UIDemo{
    private JPanel contentPanel = new JPanel();
    private JButton buttons[] = new JButton[30];
    public UIDemo(JFrame frame){
        for(int i = 0; i < buttons.length; i++){
           buttons[i] = new JButton("Button"+Integer.toString(i));
           contentPanel.add(buttons[i]);
        }//Add all buttons into content panel.

        frame.setContentPane(contentPanel);
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
             public void run(){
                 new UIDemo(new JFrame());
             }
        });
    }
}

Solution

    • JPanel has implemented FlowLayout in API

    • FlowLayout accepting only PreferredSize, then JComponents in JPanel isn't resizable

    • have look at GridLayout,

    • another options are GridBagLayout or todays custom MigLayout