我正在尝试从(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);
}
}
答案 0 :(得分:2)
有几种方法。最简单的是这些:
ComponentListener
更新尺寸,并在触发componentShown
或componentResized
时更新尺寸。JPanel
。