2

我有一个程序,一个人可以在屏幕上放置一个代表扭曲门的元素。我想知道之后如何找到元素的位置,以便程序可以捕获该区域的点击。

这是我目前拥有的:

int xCoord22[];
int yCoord22[];
int numSquare22;

int warpGate = 0;

public void init()
{

    warpgate = getImage(getDocumentBase(),"image/warpgate.png");

    xCoord22 = new int[100];
    yCoord22 = new int[100];
    numSquare22 = 0;
}

public void paint(Graphics g)
{

    warpGate(g);
}

public void warpGate(Graphics g)
{
    //Checks if warpgate == 1 then will make the warp gate where the user chooses
    if(warpGate == 1)
    {

        g.drawImage(warpgate,510,820,100,100,this);
        //Use the custom cursor  
        setCursor(cursor2);  

    }

    //Building the pylons
    if(Minerals >= 150)
    {

        for (int k = 0; k < numSquare22; k++)
        {

            g.drawImage(warpgate,xCoord22[k],yCoord22[k],120,120,this);
        //Makes cursor normal.
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        }
    }
}

public boolean mouseDown(Event e, int x, int y) 
{
    if(warpGate == 1)
    {
        if(Minerals >= 150)
        {
            xCoord22[numSquare22] = x;
            yCoord22[numSquare22] = y;
        numSquare22++;
        handleWarpGatePlacement();
        repaint();
        }
    }

    //Checks to see if the person clicks on the warpGate icon so you can build it
    if(x > 1123 && x < 1175 && y > 782 && y < 826 && onNexus == 1 && Minerals >= 250)
    {
        warpGate = 1;

    }

所以,基本上,当你点击时,x > 1123 && x < 1175 && y > 782 && y < 826你可以放置一个传送门。我怎样才能做到这一点,以便您以后将它放在任何地方,您只需单击它,它就会像一个system.out.print("hey");或其他东西一样?

4

2 回答 2

1

您可以将您的 warpgate 图像放在 JLabel 中并添加MouseListener

label.addMouseListener(new MouseAdapter() {
 public void mouseClicked(MouseEvent e) {
   System.out.print("hey");
 }
});
于 2012-05-23T12:24:58.893 回答
1

不幸的是,您的代码并不是真正的 SSCCE,但我猜这段代码在某种组件中(也许是 JLabel?)。您已经在那里实现了一个 MouseListener。现在您只需要保存放置的 warpgate 的位置,然后检查该位置而不是 MouseListener 中的常量值:

int minerals = 300;
Vector<int[]> warpgatePosition = new Vector<int[]>();
private final int warpgateDimX = 52, warpgateDimY = 44;

public boolean mouseDown(Event e, int x, int y) {
  boolean clickedOnAWarpgate = false;
  for (int[] p : warpgatePosition) {
    if (x > p[0] && x < p[0] + warpgateDimX && y > p[1] && y < p[1] + warpgateDimY) {
      clickedOnAWarpgate = true;
      break;
    }
  }
  if (clickedOnAWarpgate) {
    // we can not build one as there is already one there
    System.out.print("hey");
  } else {
    if (minerals >= 150) {
      warpgatePosition.add(new int[] {x - warpgateDimX / 2, y - warpgateDimY / 2});
      repaint();
    }
  }
  return false;
}

所以我刚刚建立了一个带有 Warpgate 位置的向量。

编辑:当然,你的曲门的位置(以及矿物数量、曲门大小等)最好不要保存在这个类中。我只是把它们放在那里以使其紧凑。

于 2012-05-23T13:10:46.100 回答