[英]Can I change the location of the ImageIcon that I put on a JLabel in my code?
[英]If I already have a JLabel with an ImageIcon, If I change the ImageIcon and then pack the frame, it doesn't pack
這是我的代碼:
/**
* Opens file and gives a warning if non image.
*/
private void openFile() {
final int returnVal = myFileChooser.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
myFile = myFileChooser.getSelectedFile();
try {
myImage = PixelImage.load(myFile);
myImageIcon = new ImageIcon(myImage);
myImageLabel.setIcon(myImageIcon);
this.pack();
this.setMinimumSize(this.getSize());
enableButtons();
} catch (final IOException exception) {
JOptionPane.showMessageDialog(null,
"The selected file did not contain an image!");
}
} else {
System.out.println("ERROR FILE"); //PLACEHOLDER
}
}
所以我想做的是:
除嘗試加載新圖像外,這四個步驟正常工作。 我遇到的問題是,當我在現有圖像之上加載新圖像時,它會擦除舊圖像(按預期),然后在新圖像周圍打包框架時(例如,較小的圖像),它將保持會根據舊圖像來設置最小尺寸要求,而不設置最小尺寸(this.setMinimumSize(this.getSize()))。 如果加載較小的圖像,則希望調整框架的大小以適應較小圖像的高度和寬度,而不是基於舊圖像。
也許嘗試類似:
this.setMinimumSize(null);
this.pack();
this.setMinimumSize(this.getSize());
所以pack()方法不限於先前的最小值嗎? 如果null不起作用,則使用Dimension(0,0)。
盡管有代表Windows的Java類,但Window是系統資源,而Java在很大程度上是無法控制的。 (當然,所有框架和JFrame都是Windows。)
當您調用pack()
,系統會響應調整窗口大小的請求,但可能不會立即生效。 因此,不能保證在對pack()
的調用完成時Window的大小會發生變化。
…頂級窗口(包括
Window
,Frame
和Dialog
)的位置和大小受桌面窗口管理系統的控制。 對setLocation
,setSize
和setBounds
調用是轉發到窗口管理系統的請求(不是偽指令)。 將盡一切努力滿足這些要求。 但是,在某些情況下,窗口管理系統可能會忽略此類請求,或修改請求的幾何形狀,以便以與桌面設置更匹配的方式放置和調整Window
大小。由於本機事件處理的異步特性,在處理完最后一個請求之前,由
getBounds
,getLocation
,getLocationOnScreen
和getSize
返回的結果可能無法反映屏幕上Window的實際幾何形狀。 在后續請求的處理期間,窗口管理系統滿足請求時,這些值可能會相應更改。
通常,這可以通過使用invokeLater來容納:
this.pack();
EventQueue.invokeLater(() -> {
this.setMinimumSize(this.getSize());
enableButtons();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.