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