Home > database >  How to get a panel's size in Java?
How to get a panel's size in Java?

Time:05-28

I tried to get with the panel.getSize() but it said java.awt.Dimension[width=0,height=0]

I tried panel.getHeight() but it said it is 0

CodePudding user response:

The Reason why your getting 0x0 as dimension is:

You did declaration to find size earlier than JFrame and JPanel to render

I assume you Did This:

JPanel panel = new JPanel();
System.out.println(panel.getSize()); // <-- This Line Triggers Earlier
panel.setVisible(true); // <-- Then This Line Renders the Panel, but late to recognize

To Fix this, Just Make Sure to Render All Objects First before getting the Info for size:

JPanel panel = new JPanel();
panel.setVisible(true); // <-- Then This Line Renders the Panel first before recognizing
System.out.println(panel.getSize()); // <-- This Line Triggers Output Size

Bonus(in order to get info infinitely by using Listener of your choice, My Instance is MouseListener):

 import java.awt.Event.*;

        panel.addMouseListener(new MouseAdapter() {
        
        @Override
        public void mousePressed(MouseEvent me) {
          System.out.println("Size: "   panel.getSize());
            panel.repaint(); //This refreshes when user tries to resize
        }
    });

for sample:

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.*;

class Main {
  public static void main(String[] args) {
    JFrame frame = new JFrame("Hello world");
    frame.setSize(300, 300);
    frame.setLocation(5, 5);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //JPanel Created
    JPanel panel = new JPanel();
    //You are getting 0x0 because you did first
    //System.out.println("Size: "   panel.getSize());
    panel.setVisible(true);
    frame.add(panel);
    frame.setVisible(true);
    
    //Solution: Get Value by event of your choice
    //My instance is to use mouseListener mousePressed
    panel.addMouseListener(new MouseAdapter() {
    
    @Override
    public void mousePressed(MouseEvent me) {
      System.out.println("Size: "   panel.getSize());
        panel.repaint();
    }
});
  }
}

Give a thumbs up if it helps. Gladge

  • Related