如何使用户放置元素可点击?

时间:2012-05-23 12:09:05

标签: java

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

这是我目前所拥有的:

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时,你可以放置一个warpgate。我怎样才能做到这一点,你以后放在哪里只需点击它就会像system.out.print("hey");或其他什么一样做?

2 个答案:

答案 0 :(得分:1)

您可以将您的warpgate图片放入JLabel并添加MouseListener

label.addMouseListener(new MouseAdapter() {
 public void mouseClicked(MouseEvent e) {
   System.out.print("hey");
 }
});

答案 1 :(得分: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位置的Vector。

编辑:当然,你的warpgates的位置(以及矿物数量,warpgate大小等)理想情况下不应该保存在这个类中。我把它们放在那里使其紧凑。