Home > Enterprise >  Resizeable JButton in BoxLayout
Resizeable JButton in BoxLayout

Time:09-14

I have the following code:

  public void showFrame() {
    var frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    var panel = frame.getContentPane();
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

    panel.add(new Button("Button 1"));
    panel.add(new Button("Button 2"));
    panel.add(new Button("Button 3"));
    panel.add(new Button("Button 4"));
    panel.add(new JButton("Button 5"));

    frame.setSize(200, 300);
    frame.setVisible(true);
  }

Which generates the following form:

rendered form

Buttons 1 to 4 (AWT buttons) resize together with the window. But button 5 (Swing button) behaves differently.

I would like button 5 to also be resizeable. I believe I'm missing something. Is there a simple way to make button 5 resizeable?

CodePudding user response:

I would like button 5 to also be resizeable. I believe I'm missing something. Is there a simple way to make button 5 resizeable?

BoxLayout respects the minimum/maximum sizes of components.

By default for a JButton those sizes are set to the preferred size.

If you want the button to grow you need to override the getMaximumSize() method of the button to return a dimension for the maximum that you want.

As suggested in the comments, an easier solution is to use a GridLayout.

  • Related