[英]Changing JRadioButton Icon on Windows 7
我創建了一個更改按鈕組中所有jradiobuttons圖標的方法:
public void setRadioButtonIcons(final ButtonGroup gruppe){
Enumeration<AbstractButton> gruppeEnum = gruppe.getElements();
while (gruppeEnum.hasMoreElements()){
AbstractButton radio = gruppeEnum.nextElement();
Icon unselIcon = new ImageIcon( Thread.currentThread().getContextClassLoader().getResource("checkbox0.jpg").getPath());
Icon selIcon = new ImageIcon( Thread.currentThread().getContextClassLoader().getResource("checkbox1.jpg").getPath());
radio.setIcon(unselIcon);
radio.setSelectedIcon(selIcon);
}
}
在帶有Java 1.6.0_16的Ubuntu下可以正常工作。
當我在帶有Java 1.6.0_18的Windows 7下使用methode時,圖標不出現。 他們只是失蹤了。 程序不會拋出Nullpointer ...它會找到圖標,但不會顯示它們。 有任何想法嗎? 似乎很難相信我不能在Windows下使用這種簡單的功能。
我嘗試了gif和jpg。 我還將圖像放入罐子中,並嘗試從文件系統中加載它們->相同結果。
編輯:在此配置中,文件從jar中加載。
Icon unselIcon = new ImageIcon( Thread.currentThread().getContextClassLoader().getResource("checkbox0.jpg").getPath());
Icon selIcon = new ImageIcon( Thread.currentThread().getContextClassLoader().getResource("checkbox1.jpg").getPath());
您不應該在那里調用getPath(),而應該是:
Icon unselIcon = new ImageIcon( Thread.currentThread().getContextClassLoader().getResource("checkbox0.jpg"));
Icon selIcon = new ImageIcon( Thread.currentThread().getContextClassLoader().getResource("checkbox1.jpg"));
它無法按路徑訪問jar中的資源,ImageIcon可以使用URL加載圖像。
如果仍然看不到圖標,則可能是您使用的L&F沒有使用這些圖標,而是使用了自己的圖標。 也許嘗試使用其他L&F測試代碼。
嘗試刪除對getPath()
的調用,如下所示:
public void setRadioButtonIcons(final ButtonGroup gruppe) {
Enumeration<AbstractButton> gruppeEnum = gruppe.getElements();
while (gruppeEnum.hasMoreElements()){
AbstractButton radio = gruppeEnum.nextElement();
Icon unselIcon = new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("checkbox0.jpg"));
Icon selIcon = new ImageIcon(Thread.currentThread().getContextClassLoader().getResource("checkbox1.jpg"));
radio.setIcon(unselIcon);
radio.setSelectedIcon(selIcon);
}
}
問題在於URL.getPath()
為您提供了一個字符串URL,它不一定是ImageIcon
字符串構造函數期望的有效字符串文件名。 幸運的是, ImageIcon
還有另一個可以理解URL
對象的構造函數,因此不需要調用getPath()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.