如何检查鼠标是否在定义的对象上单击

时间:2017-06-28 15:12:15

标签: java menu

我正在用java制作游戏,我试图为我的gui按钮创建一个类,但我不知道如何检查按钮被点击的时间!我知道如何使用MouseListener但有更简单的方法吗?

代码: Button.java

package galaxyblast.gui;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;

public class Button {

protected int x;
protected int y;
protected int width;
protected int height;

public Button(String label, int x, int y, int width, int height, Graphics2D g2d, Graphics g){
    Rectangle btn = new Rectangle(x, y, width, height);

    g.setColor(Color.DARK_GRAY);
    g.fillRect(x, y, width, height);
    g.setColor(Color.BLUE);
    Font font2 = new Font("arial", Font.BOLD, 30);
    g.setFont(font2);
    g.drawString(label, x + width / 20, y + height-height/3);
    g2d.draw(btn);

    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
}

public Bounds getBounds(){
    Bounds bounds = new Bounds(x, y, width, height);
    return bounds;
}
final class Bounds{
    private final int x;
    private final int y;
    private final int width;
    private final int height;

    public Bounds(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }


    }
}

使用示例:

package galaxyblast.gui.debug;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;

import galaxyblast.gui.Button;
import galaxyblast.gui.Gui;

public class DebugMenu extends Gui{

boolean toggled = false;

public Button debugBtn;
public Button testBtn;

String menuName;

public DebugMenu(String menuName) {
    super(menuName);
    this.menuName = menuName;
}


@Override
public void render(Graphics g) {        
    Graphics2D g2d = (Graphics2D) g;

    debugBtn = new Button("Debug", 60, 130, 100, 50, g2d, g);

    Font font0 = new Font("arial", Font.BOLD, 50);
    g.setFont(font0);
    g.setColor(Color.BLUE);
    g.drawString(menuName, 60,  60);
}

public boolean isToggled() {
    return toggled;
}

@Override
public String getName() {
    return menuName;
}

}

有没有办法检查按钮或gui类中的点击? 编辑:这是在Java画布上

0 个答案:

没有答案