Phil Freihofner
Phil Freihofner

Reputation: 7910

Obtain a JPanel's display area dimensions, Windows vs Mac

I have code that generates a JPanel that needs to run on both Mac OSX and Windows environments. I would like to draw a series of rectangles that frame the JPanel's display area. However the display area of the JPanels differs in the two environments. In the diagram below, the Mac JPanel is on the left and a Windows JPanel is on the right.

Mac vs Windows JPanels

Is there a property that makes reference to the display area of a JPanel as opposed to its size?

The two JPanels in the diagram were made with the same code. In both cases I have the following command:

setSize(400, 400);

And in the override of paintComponent, the outermost rectangle (cut off in both in the vertical but only for Windows in the horizontal) is drawn as follows:

g2.drawRect(0, 0, 399, 399);

(The inner rectangles are displaced by an increment of 4 pixels and alternate in color. This isn't exactly what I hope to draw, but it illustrates the problem.)

I could manually determing the adjustments needed, and create separate constants for the two environments, but I'm wondering if there is something I've missed in Swing where it is possible to obtain the display size of a given JPanel. If such a function or property exists, making use of it would be cleaner and more flexible, as well as hedging against JPanels being given different title-bar sizes or padding settings.

Upvotes: 0

Views: 67

Answers (1)

camickr
camickr

Reputation: 324128

In the paintComponent() method of your panel you use:

int width = getWidth();
int height = getHeight();

This will give you the current size of the panel whenever the component is repainted.

Upvotes: 2

Related Questions