我正在开发当前使用slick2d + lwjgl的游戏,并且正在尝试为gui组件实现侦听器。由于我目前很困惑,我一直在想该怎么做。我以为我可以做这样的事情

GuiComponent类...

public void addListener(MouseAdapter e){
   // Stuck on this part
}


比将其实现为这样的菜单

gComponent.addListener(new MouseAdapter(){

   @Override
        public void mouseClicked(MouseEvent e){
            // listener logic

        }
}


我不知道如何在addListener方法中实际触发方法mouseClicked,因为当我像这样运行它时,除非我有妄想,否则什么都不会发生。无论如何,即使您只是将我发送到Javadoc之类,任何帮助也确实会有所帮助。谢谢你们和圣诞快乐:)

编辑:

GuiComponent类

package com.connorbrezinsky.turbulent.gui;

import java.awt.event.MouseAdapter;

import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;

public class GuiComponent {

int x, y, width, height;

Color color;
Image i;

public GuiComponent(Gui gui, int _x, int _y, int w, int h, Color c) {
    gui.components.add(this);
    x = _x;
    y = _y;
    width = w;
    height = h;
    color = c;
}

public GuiComponent(int _x, int _y, int w, int h, Color c) {
    x = _x;
    y = _y;
    width = w;
    height = h;
    color = c;
}

public GuiComponent(Gui gui, int _x, int _y, int w, int h) {
    gui.components.add(this);
    x = _x;
    y = _y;
    width = w;
    height = h;
    color = Color.white;
}

public GuiComponent(int _x, int _y, int w, int h) {
    x = _x;
    y = _y;
    width = w;
    height = h;
    color = Color.white;
}

public void addText(String s){

}

public void addSprite(Image s){
    i = s;
}

public void render(Graphics g){
    if(i == null) {
        g.setColor(color);
        g.fillRect(x, y, width, height);
    }else{
        i.draw(x,y,width,height);
    }
}

public void addListener(MouseAdapter e){
    // stuck here
}


}

菜单类中的示例

GuiComponent guiTest = new GuiComponent(20, 20, 50, 10);

public void update(GameContainer arg0, StateBasedGame arg1, int arg2)    throws SlickException{
  guiTest.addListener(new MouseAdapter(){
        @Override
        public void mouseClicked(MouseEvent e){
            System.out.println("click");
        }
    });
 }

最佳答案

Slick2D提供several components,我不知道您是否看过它们。也许您可以使用AbstractComponent,通过继承它来做您期望的事情。似乎提供了您要自己实现的addListeners方法。它说简化您自己的代码。

然后,要添加侦听器,您可以使用gameContainer。通过gc.getInput().addListener()

使用您的代码,它将类似于:

GuiComponent guiTest =新的GuiComponent(20,20,50,10);

public void update(GameContainer arg0, StateBasedGame arg1, int arg2)    throws SlickException{
  arg0.getInput().addListener(new MouseAdapter(){
        @Override
        public void mouseClicked(MouseEvent e){
            System.out.println("click");
        }
    });
 }

07-27 23:39