将JComponent的宽度和高度设置为实例变量

时间:2014-07-10 13:38:32

标签: java swing awt

我将组件的宽度和高度设置为实例变量(在组件的子类中)时遇到问题。如果我在构造函数中调用getWidth()getHeight()(始终为零),则值与调用paintComponent(Graphics g)中的相同方法不同。有人可以解释为什么会发生这种情况,我怎样才能将组件的宽度和高度设置为实例变量。非常感谢。

以下是代码段:

import java.awt.Graphics;
import javax.swing.JComponent;

public class MyComponent extends JComponent
{
    // Instance variables.
    private int width;
    private int height;

    public MyComponent()
    {
        width = getWidth();
        height = getHeight();
        System.out.println(width+","+height);
    }

    public void paintComponent(Graphics g)
    {
        // Local variables.
        int width = this.getWidth();
        int height = this.getHeight();
        System.out.println(width+","+height);
    }

}

import javax.swing.JFrame;

public class ComponentTester
{
    public static void main(String args[])
    {
        JFrame frame = new JFrame();
        MyComponent component = new MyComponent();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setSize(350, 400);
        frame.setVisible(true);

        frame.add(component);
    }

}

1 个答案:

答案 0 :(得分:3)

设置组件大小取决于组件。因此在构造函数中,默认大小为0.如果将组件添加到布局管理器中(就像将组件添加到具有默认布局管理器的框架时所做的那样),它将根据首选/最小/最大值设置大小这 - 默认为0到max-int。因此布局管理器会将组件的大小调整为框架的大小。

无需将大小存储在本地副本中,因为getWidth()/ Height()将从组件类中的本地副本读取大小。