【问题标题】:How can I get a JPanel's width and height from within the constructor?如何从构造函数中获取 JPanel 的宽度和高度?
【发布时间】: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,因此在构造函数中它不知道任何宽度。

标签: java polygons


【解决方案1】:

swing 组件在构建时还没有宽度。它首先必须添加到容器中,之后布局管理器将为组件分配位置和尺寸。

至于为什么不是 600 而是 594 - 每个摆动组件都有被边框占据的“插图”。它们具有默认宽度,具体取决于您的 PLAF。在这种情况下,JFrame 内容窗格左侧和右侧的插图可能是 3 和 3 像素,加起来是 6,并且 600 - 6 = 594。

【讨论】:

    【解决方案2】:

    JPanel默认的LayoutManager为BorderLayout,组件的大小在BorderLayout.layoutContainer中计算,在调用构造函数时,BorderLayout.layoutContainer没有被调用;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-30
      • 2011-08-20
      • 1970-01-01
      • 2019-12-26
      • 2023-04-09
      • 2011-07-12
      • 2014-05-01
      • 2017-05-28
      相关资源
      最近更新 更多