[Solved] JDialog doesn’t respect dimensions of child components


If I don’t define dimensions, how do I ensure the whole background I’m painting is displayed?

You could use a JLabel to display the ImageIcon. The size of the label will be the size of the image. You then set the layout manager of the label so you can add components to it.

Edit:

do you know why it’s commonly-recommended to subclass JPanel when painting backgrounds in Java

When you use a JPanel the size of the panel is based on the components added to the panel and the layout manager you are using. Your custom painting code then needs to paint the image the way your want. That is you can paint the image from (0, 0), or you can center the image on the panel, you can scale the image to make it fit the pane, but the image in no way controls the size of the panel, unless you override the getPreferredSize() method of the panel to use custom code to base the size of the larger of the components or the image. So you are in full control.

When you use the JLabel approach suggested here, the size of the label is always the size of the image. Then components will be positioned based on the layout manager but can be truncated if the image is smaller than the space required by the components.

So based on your requirement that you want to make sure the entire image is displayed, I suggested the JLabel approach, since you don’t need to write any custom code. I find this a simple approach when using popup non-resizable dialogs to display a background image and a few components and buttons to close the dialog.

You can also check out Background Panel which provides these common painting features in a reusable class.

1

solved JDialog doesn’t respect dimensions of child components