Kovalainen Kovalainen - 1 month ago 8
Java Question

Java Swing - Get the size of the element some other element is enclosed in

As the title says - say I have a jPanel enclosed in a jScrollPane. How do I find the size, from inside the jPanel, of the jScrollPane it is enclosed in?

Fairly simple question that I get the feeling I should be able to google easily but I haven't found an answer.

Answer Source

You can call Component's getParent() which will give you the direct parent of this component and then you can query its dimensions.

Here is an example, although to be fair, it's the preferred size what I'm checking here. If you run it you will see that "200.0" is printed to the console, as you would expect.

Presumably using getWidth() will get you the actual width too, although that requires a little more knowledge of Swing's internal workings to ensure, since the user is not in direct control of the actual size of the rendered panel.

public class SomeJFrame extends JFrame {
   public SomeJFrame() {
      setLayout(new BorderLayout());

      JPanel parent = new JPanel(new BorderLayout());
      parent.setPreferredSize(new Dimension(200, 201));
      JPanel child = new JPanel(new BorderLayout());
      parent.add(child);
      System.out.println(child.getParent().getPreferredSize().getWidth());

      add(parent, BorderLayout.CENTER);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      pack();
      setVisible(true);
   }

   public static void main(String[] args) {
      javax.swing.SwingUtilities.invokeLater(new Runnable() {
         @Override
         public void run() {
            new SomeJFrame();
         }
      });
   }

}