我注意到运行我在下面列出的程序有时会产生不良影响。
编辑:我简化了代码以使事情看起来清晰。我正在绘制一个打印出当前组件大小的字符串。我已经覆盖了 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);
}
}