Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java (Swing): finding a component's *screen* size when the window is resized

Tags:

java

swing

resize

I need to find a component's exact screen size in pixels when the main JFrame is resized.

I've tried several things and couldn't find an easy way to do it: it probably have missed something obvious.

BBBBB JFRAME BORDER BBB
BZZZZZZZZZZZZZZZZZZZZZB
BAAAAAAAAAAAAAAAAAAAAAB
BCC1................DDB
BCCC................DDB
BCCC................DDB
BCCC................DDB
BCCC................2DB
BEEEEEEEEEEEEEEEEEEEEEB
BBBBBBBBBBBBBBBBBBBBBBB

Resized, it could become this if, say, the user made the main JFrame shorter (vertically) and wider (horizontally):

 BBBBBB JFRAME BORDER BBBBBB
 BZZZZZZZZZZZZZZZZZZZZZZZZZB
 BAAAAAAAAAAAAAAAAAAAAAAAAAB
 BCC1....................DDB
 BCCC....................2DB
 BEEEEEEEEEEEEEEEEEEEEEEEEEB
 BBBBBBBBBBBBBBBBBBBBBBBBBBB

What I want is to find the exact size in pixels, on screen, of the rectangle area indicated by dots.

I'm adding a ComponentListener to get the resizing events, which works fine.

The issue I'm having is that calling getWidth()/getHeight() on a Component does apparently not return the component's screen size but the component's actual size (and you can have, for example, a JPanel wider than the component it is into).

Any hint most welcome.

like image 270
SyntaxT3rr0r Avatar asked May 18 '10 18:05

SyntaxT3rr0r


2 Answers

You're looking for JComponent.getVisibleRect().

like image 62
Nate Avatar answered Sep 26 '22 03:09

Nate


getWidth() and getHeight() returns the width and height of the component. I've never heard of any difference between "actual" width/height and "screen" width/height.

Some layout managers however, does not fill the panel with a component it contains, and some space between the component and the panels edge may not be occupied by the component. In that case I usually setBackground(Color.BLUE) on the underlying panel to see what's going on.

like image 25
aioobe Avatar answered Sep 26 '22 03:09

aioobe