【发布时间】:2012-07-19 12:52:31
【问题描述】:
我注意到运行下面列出的程序有时会产生不良影响。
编辑:我已经简化了代码以使事情看起来更清晰。我正在绘制一个打印出当前组件大小的字符串。我已经覆盖了 Component 类中的 getPreferedSize() 方法,并将宽度和高度分别设置为 640 x 512。但是,运行程序后我仍然得到不同的结果:640 x 512 和 650 x 522。奇怪的是删除 frame.setResizable(false) 行修复了问题。但我希望窗口可以调整大小
import java.awt.*;
import javax.swing.*;
public class DrawTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
DrawFrame frame = new DrawFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
});
}
}
class DrawFrame extends JFrame
{
private static final long serialVersionUID = 1L;
public DrawFrame()
{
setTitle("DrawTest");
setLocationByPlatform(true);
Container contentPane = getContentPane();
DrawComponent component = new DrawComponent();
contentPane.add(component);
}
}
class DrawComponent extends JComponent
{
private static final long serialVersionUID = 1L;
public Dimension getPreferredSize() {
return new Dimension(640, 512);
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
String msg = getWidth() + " x " + getHeight();
g2.setPaint(Color.BLUE);
g2.drawString(msg, getWidth()/2, getHeight()/2);
}
}
【问题讨论】:
-
对我能想到的行为的最佳猜测是,您使用
setPreferredSize()作为Content Pane。相反,您可以做的是覆盖getPreferredSize(),并使其返回您想要设置为JComponent的首选大小的值。一个例子是here、another here、and one More here -
为什么这种方法是有益的,看看@trashgod的wonderful answer
-
感谢您的提示。正如您所指出的,我已经覆盖了该方法,并简化了代码。但是问题仍然出现,我不知道为什么。检查 OP 中的编辑。
-
你很受欢迎并保持微笑:-) 我确实注意到,多次运行该程序确实会给你
650 X 522,这是意料之外的。似乎frame.setResizable(...)有问题,虽然我在Windoes 7 32 位平台上使用Java(TM) SE Runtime Environment (build 1.7.0_03-b05),但希望这不是1.7 的另一个错误:( -
为sscce+1。