如何将actionlistener制作成自定义类?

时间:2014-11-02 04:38:28

标签: java opengl actionlistener lwjgl

我正在使用LWJGL和SlickUtil来制作游戏,我创建了自己的GLButton类,您可以单击它。它工作正常,但我想添加动作监听器实现,所以我不必为每个按钮创建一个新的类,当它被点击时具有不同的动作。我想要它,所以我可以做到

GLButton.addActionListener((ActionEvent e) -> {
    //do method here
}); 

这是类的代码

public class GLButton {
private boolean alive = false;
private float x1;
private float y1;
private float x2;
private float y2;
private String text;
private final Texture tex;
private final Texture texOver;
private final Texture texPressed;
private Texture currentTexture;
private boolean pressed=false;

public GLButton(float x, float y, float width, float height, String text) {
    this.x1=x;
    this.y1=y;
    this.x2=width;
    this.y2=height;
    this.text=text;

    tex=loadTexture("btn");
    texOver=loadTexture("btnOver");
    texPressed=loadTexture("btnPressed");

    currentTexture = tex;

    alive=true;
}

public void draw() {
    if(!alive) return;
    pollInput();

    currentTexture.bind();

    glColor3f(1,1,1);
        glBegin(GL_QUADS);
            glTexCoord2f(0,0);glVertex2f(x1,y1);
            glTexCoord2f(0,1);glVertex2f(x1,y1+y2);
            glTexCoord2f(1,1);glVertex2f(x1+x2,y1+y2);
            glTexCoord2f(1,0);glVertex2f(x1+x2,y1);
        glEnd();
}

public void setText(String text) {
    this.text=text;
}

public void setLocation(float x, float y) {
    this.x1=x;
    this.y1=y;
}

public void setSize(float width, float height) {
    this.x2=width;
    this.y2=height;
}

private Texture loadTexture(String key) {
    try {
        return TextureLoader.getTexture("PNG", new FileInputStream(
                Start.main_dir+"\\res\\textures\\"+key+".png"));
    } catch (IOException ex) {
        Logger.getLogger(GLButton.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

private void pollInput() {
    if(GameWindow.grabbed==true) return;

    int mouseY = Math.abs(Mouse.getY()-Display.getHeight());

    currentTexture = tex;

    if(Mouse.getX()>=(int)x1 && Mouse.getX()<=(int)x1+(int)x2 && mouseY >= (int)y1 && mouseY <= (int)y1+(int)y2) {
        currentTexture = texOver;

        if(Mouse.isButtonDown(0)&&pressed==false) {
            pressed=true;
            currentTexture = texPressed;
        } else if(!Mouse.isButtonDown(0)) {
            pressed=false;
        }
    }
}

public boolean isAlive() {
    return alive;
}

public void destroy() {
    alive=false;
}



public float getX() {
    return x1;
}

public float getY() {
    return y1;
}

public float getWidth() {
    return x2;
}

public float getHeight() {
    return y2;
}

}

0 个答案:

没有答案