我有一个生成包含图像的JFrame的简单函数:
//The window
JFrame frame = new JFrame();
//Topmost component of the window
Container main = frame.getContentPane();
//Turns out this is probably the simplest way to render image on screen
//with guaranteed 1:1 aspect ratio
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
};
//Put the image drawer in the topmost window component
main.add(panel);
//Set window size to the image size plus some padding dimensions
frame.setSize(image.getWidth(null)+1, image.getHeight(null)+15);
frame.setVisible(true);
结果:
我认为这是因为窗口尺寸包括顶部栏的大小和窗口边框。
我还尝试设置JPanel
的尺寸并在JFrame上调用pack()
:
//Set the size to the panel and let JFrame size itself properly
panel.setSize(image.getWidth(null), image.getHeight(null));
frame.pack();
结果更糟:
那么如何精确指定内部窗口尺寸(以像素为单位)?
答案 0 :(得分:2)
通过覆盖getPreferredSize
的{{1}}方法并在JPanel
上调用pack()
,然后再将其显示为
JFrame
请参阅Use of overriding getPreferredSize() instead of using setPreferredSize() for fixed size Components中有关此技术的使用和效果的答案,或JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
@Override
public Dimension getPreferredSize(){
return new Dimension(image.getWidth(), image.getHeight());
}
};
方法