2015-05-01 145 views
1

的內部區域的大小我有一個簡單的函數,生成一個包含圖像的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

那麼你可以嘗試在JLabel中插入圖像,這可能不會導致此問題。 –

+0

@ParamvirSinghKarwal我從那開始的。我不知道爲什麼我不再使用該解決方案,但是我猜想有一個原因。 –

+1

顯示使用JLabel的圖像的最簡單方法。只有在操作圖像時才進行自定義繪畫。 – camickr

回答

2

通過重寫的JPanelgetPreferredSize方法和使其可見

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()); 
    } 
}; 

查看其回答Use of overriding getPreferredSize() instead of using setPreferredSize() for fixed size Components之前呼籲JFramepack()指定面板的優選大小關於這種技術的使用和效果,或者方法的使用和效果

+0

太棒了!它的工作原理,比我希望的更簡單:) –

+0

@TomášZato,更簡單的是使用JLabel,因爲它爲你做到了這一點。 – camickr