2013-10-15 93 views
1

我想知道是否有可能知道當我離開時單擊我的畫布下面有一個圖像圖標,這是必須能夠的代碼手的話:如何知道鼠標點擊是否在圖形圖像java

public void mousePressed(MouseEvent evt) { 
    if (!labelSelected){ 

    // This is called by the system when the user presses the mouse button. 
    // Record the location at which the mouse was pressed. This location 
    // is one endpoint of the line that will be drawn when the mouse is 
    // released. This method is part of the MouseLister interface. 
    startX = evt.getX(); 
    startY = evt.getY(); 
    prevX = startX; 
    prevY = startY; 
    dragging = true; 
    Random ran = new Random(); 
    int x = ran.nextInt(10); 
    currentColorIndex = x; 
    gc = getGraphics(); // Get a graphics context for use while drawing. 
    gc.setColor(colorList[currentColorIndex]); 
    gc.setXORMode(getBackground()); 
    gc.drawLine(startX, startY, prevX, prevY); 
    } 
} 

但我的畫前行我想確保鼠標按下了一個圖形圖像,像如果(evt.getsource()==「圖形選項」)或類似的東西那。

+0

你怎麼知道其中的圖標繪製? – MadProgrammer

+0

我選擇一個圖標點擊畫布上的某個地方,然後它被畫在畫布上,之後我必須加入讓我們說2個不同的圖標與一條線,所以我想到了,當我點擊系統檢查點擊結束圖像,讓它讓你開始行 –

+0

因此,你知道圖標圖像的位置?這是如何維護的? – MadProgrammer

回答

1

嘗試檢查圖像的位置,例如。如果圖像位置是(X = 100,Y = 100),寬度和高度是100.那麼您可以檢查光標的當前位置。從ImageIcon對象中獲取X位置,Y位置,寬度和高度。像 -

// imgX has the position of Image in X direction 
// imgY has the position of Image in Y direction 
// imgW has the width of image 
// imgH has the height of image 

所以,現在我可以檢查與 -

if((startX <= imgX+imgW && startX >= imgX) && (startY <= imgY+imgH && startY >= imgH)) 
{ 
    //On the image 
} 
else 
{ 
    //Out side of the image 
} 
相關問題