Reputation: 359
I'm working on a game currently using slick2d + lwjgl and I am trying to implement listeners for the gui components. I was wondering on how to do that since I am currently stumped. I was thinking I could do something like this
GuiComponent class....
public void addListener(MouseAdapter e){
// Stuck on this part
}
Than implement it into a menu like this
gComponent.addListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent e){
// listener logic
}
}
I don't know how to actually trigger the method mouseClicked inside the addListener method, because when i ran it like this nothing happened unless I am delusional. Anyway, any help does help even if you just send me to a javadoc or something like that. Thanks guys & merry christmas :)
EDIT:
GuiComponent class
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
}
}
Example in menu class
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");
}
});
}
Upvotes: 1
Views: 141
Reputation: 2561
Slick2D offers several components, I don't know if you've seen them. Maybe can you use the AbstractComponent, by inherits from it to do what you expect. It seems to provide the addListeners
method that you want to implement by yourself. It say simplify you own code.
Then to add a listener, you can use your gameContainer. Through gc.getInput().addListener()
.
With your code it would be something like :
GuiComponent guiTest = new 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");
}
});
}
Upvotes: 1