的内部区域的大小我有一个简单的函数,生成一个包含图像的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();
结果更糟糕:
所以,我怎么能准确地指定内部窗口尺寸像素?
Here's the full function code.
那么你可以尝试在JLabel中插入图像,这可能不会导致此问题。 –
@ParamvirSinghKarwal我从那开始的。我不知道为什么我不再使用该解决方案,但是我猜想有一个原因。 –
显示使用JLabel的图像的最简单方法。只有在操作图像时才进行自定义绘画。 – camickr