林有點困惑,你說的代碼是將圖像添加到JLabel
,但是代碼顯示你添加了一個變量mButton
並設置了它的圖標,這讓我想到了它的JButton
?
無論哪種方式是JLabel
/JButton
已經添加到容器或它是否動態添加?
1)如果JLabel
/JButton
已不存在於可見容器:
添加/刪除或上一個可見的容器交換部件的尺寸/佈局之後,你應該調用revalidate()
和repaint()
上的容器例如作爲以反映變化:
//code which adds component to visible panel_1
//so changes can be reflected
panel_1.revalidate();
panel_1.repaint();
2)如果JLabel
/JButton
可見所見setIcon
應該工作,因爲它要求revalidate()
和repaint()
她自己從JLabel#setIcon
E(JButton
是相同的):
* 108: getfield #294 // Field defaultIcon:Ljavax/swing/Icon;
* 111: invokeinterface #346, 1 // InterfaceMethod javax/swing/Icon.getIconHeight:()I
* 116: aload_2
* 117: invokeinterface #346, 1 // InterfaceMethod javax/swing/Icon.getIconHeight:()I
* 122: if_icmpeq 129
* 125: aload_0
* 126: invokevirtual #319 // Method revalidate:()V
* 129: aload_0
* 130: invokevirtual #318 // Method repaint:()V
從而別的東西是喜歡你的佈局管理不能正確支持添加新的組件的故障,因此它不得到安置在一個可見的空間,請張貼SSCCE 。
我也看到你正在使用setSize(..)
和setLocation(..)
,所以我得到了你所使用的Absolute
/null
LayoutManager
這不是推薦,並可能導致很多問題的感覺。而是使用適當的LayoutManager
在這裏看到更多:
希望這[示例](http://stackoverflow.com/a/9866659/1057230)也許能夠幫助你一點。 –