2011-04-30 105 views
0

我將圖像插入JPanel。我寫這個代碼。將動作偵聽器添加到圖像

public void paint(Graphics g) 
{ 

    img1=getToolkit().getImage("/Users/Boaz/Desktop/Piece.png"); 
    g.drawImage(img1, 200, 200,null); 

} 

我想一個動作偵聽器添加到圖片,但它不具有addActionListener()方法。如何在不將圖像放入按鈕或標籤中的情況下做到這一點?

+3

1)對於繪製圖像,只需要一個「JComponent」。 2)對於'JComponent'或'JPanel',重寫'paintComponent(Graphics)'而不是'paint(Graphics)'3)不要嘗試在paint方法中加載圖像。將它加載到'init()'或構造過程中並將其作爲類級屬性存儲。 4)'Toolkit'圖像加載方法需要一個'MediaTracker'。使用'ImageIO.read(文件)'來保證圖像被加載。 5)在'drawImage()'方法中爲'this'交換'null'。 – 2011-04-30 06:13:16

回答

4

有幾個選項。

使用在JPanel

一個MouseListener直接一個簡單而骯髒的方式將是直接添加MouseListener到您推翻了paintComponent方法JPanel,並實現了一個mouseClicked方法,檢查該區域圖像存在的位置已被點擊。

一個例子是沿着線的東西:

class ImageShowingPanel extends JPanel { 

    // The image to display 
    private Image img; 

    // The MouseListener that handles the click, etc. 
    private MouseListener listener = new MouseAdapter() { 
    public void mouseClicked(MouseEvent e) { 
     // Do what should be done when the image is clicked. 
     // You'll need to implement some checks to see that the region where 
     // the click occurred is within the bounds of the `img` 
    } 
    } 

    // Instantiate the panel and perform initialization 
    ImageShowingPanel() { 
    addMouseListener(listener); 
    img = ... // Load the image. 
    } 

    public void paintComponent(Graphics g) { 
    g.drawImage(img, 0, 0, null); 
    } 
} 

註釋:ActionListener不能添加到JPanel,作爲JPanel本身不借給自己的作品被認爲是「行動」。

創建JComponent顯示圖像,並添加MouseListener

一個更好的辦法是使JComponent一個新的子類,其唯一目的是要顯示的圖像。 JComponent應根據圖像的大小自行調整,以便點擊任何部分的JComponent都可以被視爲圖像上的點擊。再次,在JComponent中創建一個MouseListener以捕獲點擊。

class ImageShowingComponent extends JComponent { 

    // The image to display 
    private Image img; 

    // The MouseListener that handles the click, etc. 
    private MouseListener listener = new MouseAdapter() { 
    public void mouseClicked(MouseEvent e) { 
     // Do what should be done when the image is clicked. 
    } 
    } 

    // Instantiate the panel and perform initialization 
    ImageShowingComponent() { 
    addMouseListener(listener); 
    img = ... // Load the image. 
    } 

    public void paintComponent(Graphics g) { 
    g.drawImage(img, 0, 0, null); 
    } 

    // This method override will tell the LayoutManager how large this component 
    // should be. We'll want to make this component the same size as the `img`. 
    public Dimension getPreferredSize() { 
    return new Dimension(img.getWidth(), img.getHeight()); 
    } 
} 
+2

按照@ user650679的歷史記錄看來,您的答案在近期內不會被承認/接受:)。雖然我的投票是+1。 – Favonius 2011-04-30 06:11:05

+0

@Favonius:希望這個答案也能在將來幫助其他人。謝謝你的贊成:) – coobird 2011-04-30 06:15:33

+1

你的代碼不遵循你的描述(幸運的是:-) a)它正確地覆蓋了_paintComponent_(與第一個例子中描述的paint相比)b)它正確地使用了MouseListener(相對於已實現的規定) – kleopatra 2011-04-30 09:30:41

2

最簡單的方法是將圖像放入JLabel中。當你使用該程序時,它看起來只是圖像,你不能在JLabel中告訴它。然後,只需將一個MouseListener添加到JLabel。

+2

這個問題具體問到如何做到這一點,而不會將其放入標籤中,因此您的回覆最好作爲評論,而不是回答。 – 2012-11-08 15:25:29

相關問題