【发布时间】:2016-09-14 02:18:52
【问题描述】:
所以我有一个将东西绘制到 JPanel 的类,但要做到这一点,我需要在构造函数中实例化多边形。但是我对此有点困惑;我创建了 JFrame 并将 JPanel 扩展类“Field”添加到它,就像这样,
public class mainSetup {
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setSize(600,600);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(new Field());
frame.pack();
}
}
这是 JPanel 的代码:
public class Field extends JPanel implements ActionListener{
public Field(){
System.out.println(getWidth());
}
@Override
public void paintComponent(Graphics g){
System.out.println(getWidth());
}
@Override
public void actionPerformed(ActionEvent arg0) {
repaint();
}
}
为什么构造函数中的getWidth()调用打印0,而paintComponent方法中的getWidth()调用返回594?事实上——为什么这两个数字都不是我期望的 600?为什么它们会有所不同?
【问题讨论】:
-
在这段代码
frame.add(new Field());中,首先调用构造函数,然后将其添加到frame,因此在构造函数中它不知道任何宽度。