10

For instance, the size of the window changed (user resized it), how to get current window size?

2
  • "how to get current window size?" Why do you think you need it? I've written 100s of GUIs and rarely needed to get the size of the parent container (especially not on resize). Nov 30, 2011 at 21:38
  • 2
    How you handle resizing of frame then?
    – Giannis
    Mar 27, 2012 at 13:37

3 Answers 3

23
Rectangle r = frame.getBounds();
h = r.height;
w = r.width;
8

Assuming you have a JFrame in which you are drawing your interface:

Dimension size = frame.getBounds().getSize()

Returns the dimensions of the frame. Additionally, you can give the frame a resize handler to catch whenever the user adjusts the frame's size:

    class ResizeListener implements ComponentListener {

        public void componentHidden(ComponentEvent e) {}
        public void componentMoved(ComponentEvent e) {}
        public void componentShown(ComponentEvent e) {}

        public void componentResized(ComponentEvent e) {
            Dimension newSize = e.getComponent().getBounds().getSize();          
        }   
    }

    frame.addComponentListener(new ResizeListener());
1
  • 3
    if you don't override most of the methods, I'd consider using ComponentAdaper instead
    – Jan Vorcak
    Dec 1, 2011 at 17:08
3

Simply use the getSize()method: javadoc

2
  • 3
    I'm getting 404 on that link. Please update it and complement your answer, so this doesn't invalidate it in the future. getSize() method from which class? Jul 19, 2018 at 11:38
  • 1
    @VictorMoraes since OP was afk for a while, I have updated broken link.
    – pavjel
    Apr 23, 2019 at 14:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.