JButton size larger than specified

You’re not using a LayoutManager of any kind. The JButton will try to inherit the size of the parent container, as the default for a JFrame is BorderLayout (specifically, BorderLayout.CENTER). You could try using

button.setPreferredSize(x, y);

However I don’t think this would be enough by itself. Call getContentPane on the Jframe, and set a layout on that contentPane container (I use FlowLayout a lot, as it respects setPreferredSize). Put your JButton inside that.

This is always a good starting point:

https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

As the methods that you can call on a UI element vary depending on what LayoutManager you’re assigning them to (be the child of). Sometimes it’s setMinimumSize, sometimes it’s setPreferredSize, and sometimes it’s a combination.

Leave a Comment