我将组件的宽度和高度设置为实例变量(在组件的子类中)时遇到问题。如果我在构造函数中调用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);
}
}
答案 0 :(得分:3)
设置组件大小取决于组件。因此在构造函数中,默认大小为0.如果将组件添加到布局管理器中(就像将组件添加到具有默认布局管理器的框架时所做的那样),它将根据首选/最小/最大值设置大小这 - 默认为0到max-int。因此布局管理器会将组件的大小调整为框架的大小。
无需将大小存储在本地副本中,因为getWidth()/ Height()将从组件类中的本地副本读取大小。