2013-01-06 46 views
2

我需要在標籤中顯示的圖像,當用戶點擊button.I已經寫了一些代碼的ActionListener,但它不工作需要顯示圖像時,用戶點擊按鈕clickme

 btnNewButton.addActionListener(new ActionListener() { 

     public void actionPerformed(ActionEvent e) { 

      ImageIcon one = new ImageIcon("E:\\image1.jpg"); 
      panel_1.setLocation(20, 100); 
      panel_1.setSize(115, 115); 
      mbutton.setIcon(one); 
      panel_1.add(mbutton); 
      // mbutton.setText("You changed me"); 
     } 
    }); 
+0

希望這[示例](http://stackoverflow.com/a/9866659/1057230)也許能夠幫助你一點。 –

回答

4

林有點困惑,你說的代碼是將圖像添加到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/nullLayoutManager這不是推薦,並可能導致很多問題的感覺。而是使用適當的LayoutManager在這裏看到更多: