setMinimumSize() not working for JButton

六眼飞鱼酱① 提交于 2019-12-06 16:41:21

JButtons (and a few other components) can be a bit goofy in layout managers. The layout manager is noticing that your button has a preferred size that needs to be respected, so it's adjusting your pane to accommodate. But your JButton is happy doing it's thing (what it thinks is right) unless you really force it to consider the size it's supposed to be.

If you're manually sizing your button (which isn't necessarily recommended), I'd say you should set all three properties (Minimum, maximum, and preferred). Maximum is the key - it forces the button to consider the other two sizes.

Here's a simple example that should work.

import java.awt.Dimension;
import javax.swing.*;

public class ButtonSizes {

    private static class AddInputSetButton extends JButton {
        Dimension d;
        public AddInputSetButton(int width, int height) {
            super("+");
            d = new Dimension(width, height);
            setMinimumSize(d);
            setMaximumSize(d);
            setPreferredSize(d);
        }

    }

    public static void main(String[] args) {
        Box buttons = Box.createVerticalBox();
        buttons.add(new AddInputSetButton(100,100));
        buttons.add(new AddInputSetButton(200,200));
        buttons.add(new AddInputSetButton(300,300));

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(buttons);
        frame.pack();
        frame.setVisible(true);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!