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

标签 java

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

这是我目前拥有的:

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"); 那样做。或者其他什么?

最佳答案

您可以将扭曲门图像放入 JLabel 中并添加 MouseListener:

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

关于java - 如何使用户放置的元素可点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10719603/

相关文章:

java - Jsoup 解析 html 字符串

java - org.testng.TestNGException : Cannot instantiate class

java - 使用 Apache HTTP 服务器提供错误页面

Java Mockito-如何模拟不确定数量的参数方法

java - 每次从 Ldap 连接池返回新的 Connection

java - 我的类中变量和函数的可访问性

java - Apache axis2 wsdl2java异常: unknown protocol: d

java - EJB 注入(inject) - JNDI 查找失败

java - Java 中的数学 - 不同对象的不同结果

java - InputString 中的 NumberFormatException