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

残念ながら、あなたのコードは実際には SSCCE ではありませんが、このコードはある種のコンポーネント (おそらく JLabel?) にあると思います。そこにはすでに MouseListener を実装しています。ここで、配置したワープゲートの位置を保存し、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;
}

そこで、ワープゲートの位置を含むベクターを作成しました。

編集: もちろん、ワープゲートの位置 (および鉱物の数、ワープゲートのサイズなど) は、理想的にはこのクラスに保存されるべきではありません。コンパクトになるように並べてみました。

于 2012-05-23T13:10:46.100 に答える
1

ワープゲート画像を JLabel 内に配置して、次を追加できますMouseListener

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