获取 JPanel 的大小

Get size of JPanel

我正在尝试从 (0,0) 到面板中心画一条线。没有绘制线条,因为 DrawingPanel 构造函数中的 getWidth() 和 getHeight() return 0。我猜这是因为框架还不可见。那么如何获取面板的大小呢?

import java.awt.*;
import javax.swing.*;


public class DrawingApplication extends JFrame {
    static int CenterX;
    static int CenterY;

    public DrawingApplication(){
        setTitle("Drawing Application");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setExtendedState(JFrame.MAXIMIZED_BOTH);
        DrawingPanel pnlDraw = new DrawingPanel();
        add(pnlDraw);
    }

    public static void main(String[] args) {
        DrawingApplication drawingApp = new DrawingApplication();
        drawingApp.setVisible(true);
    }
}


class DrawingPanel extends JPanel {
    int CenterX, CenterY;

    public DrawingPanel(){
        CenterX = getWidth()/2;
        CenterY = getHeight()/2;
    }

    public void paintComponent(Graphics g){
        Graphics2D g2 = (Graphics2D) g;
        super.paintComponent(g);
        g2.drawLine(0, 0, CenterX, CenterY);
    }
}

有几种方法。最简单的是这些:

  1. 使用 ComponentListener 更新大小并在触发 componentShowncomponentResized 时更新大小。
  2. 只需在每次绘制 JPanel 时获取尺寸即可。