2011-09-29 85 views
0

我想在圖像上添加事件。也就是說,當我點擊圖片時,它應該被替換爲另一張圖片。如何爲圖像添加事件

import java.awt.Canvas; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.IOException; 

import javax.imageio.ImageIO; 

public class RadioButtonLoader extends Canvas{ 

    private static final long serialVersionUID = 1L; 
    BufferedImage image = null; 
    public RadioButtonLoader(){ 
     try { 
      this.image = ImageIO.read(new File("res/rb1.gif")); 

     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 
    public RadioButtonLoader(String checked){ 
     try { 
      this.image = ImageIO.read(new File("res/rb2.gif")); 

     } catch (IOException ex) { 
      ex.printStackTrace(); 
     } 
    } 
    @Override 
    public void setSize(Dimension d) { 
     super.setSize(new Dimension(15,22)); 
    } 

    @Override 
    public void paint(Graphics g) { 
     setSize(new Dimension(15,22)); 
     g.drawImage(image, 0, 0, null); 


    } 

} 

我該怎麼辦?

+2

怎麼樣'MouseListener'? –

+0

您現在正在設置'paint()'中的大小嗎?!?仍然使用'null'作爲'ImageObserver'?你需要多少次被告知? –

回答

1

只要你在你的圖像中mouselister的onclick方法中添加mouselistner添加代碼...............

http://www.anyexample.com/programming/java/java_full_screen_image_viewer.xml

+0

['java.awt.MouseListener'](http://download.oracle.com/javase/7/docs/api/java/awt/event/MouseListener.html)(與'mouselistner ** **或* *'mouselister')沒有'onclick'方法,雖然它有一個[MouseListener.mouseClicked(MouseEvent)](http://download.oracle.com/javase/7/docs/api/java/awt/ event/MouseListener.html#mouseClicked%28java.awt.event.MouseEvent%29)方法。順便說一句 - 鏈接的源代碼混合了Swing和AWT,但是未能使用JFrame.setDefaultOperationOnClose(int),並且它使用Swing頂級容器(ick)中的paint(Graphics)來定製繪畫。 –