设置窗口

时间:2015-05-01 17:25:18

标签: java swing

我有一个生成包含图像的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);

结果:

image description

我认为这是因为窗口尺寸包括顶部栏的大小和窗口边框。

我还尝试设置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();

结果更糟:

image description

那么如何精确指定内部窗口尺寸(以像素为单位)?

image description

Here's the full function code.

1 个答案:

答案 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()); } }; 方法