获取JPanel的大小

时间:2015-10-12 17:28:46

标签: java jframe jpanel size

我正在尝试从(0,0)到面板中心绘制一条线。没有绘制线,因为DrawingPanel构造函数中的getWidth()和getHeight()返回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 个答案:

答案 0 :(得分:2)

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

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