2013-10-15 2 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() == "그래픽 ICON") 또는 뭔가 같은 경우 그.

+0

어떻게 알 수 있습니까 뿐인데 확인할 수 있습니까? – MadProgrammer

+0

캔버스의 아이콘을 클릭하면 아이콘이 캔버스에 그려지고 캔버스에 그려집니다. 그런 다음 두 개의 다른 아이콘을 선으로 연결해야한다고 생각하므로 클릭 한 번으로 시스템 검사를 클릭하면 이미지를 사용하면 라인을 시작합니다. –

+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 
} 
관련 문제