如何在 Java 中获取面板的大小?

How to get a panel's size in Java?

我试图与 panel.getSize() 取得联系,但它说 java.awt.Dimension[width=0,height=0]

我试过了panel.getHeight()但是它说是0

你得到 0x0 作为维度的原因是:

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

我假设你这样做了:

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

要解决此问题,只需确保在获取大小信息之前先渲染所有对象:

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

奖金(为了通过使用您选择的监听器无限获取信息,我的实例是 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
        }
    });

示例:

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