I wrote some GUI stuff (a button) for my game. But Im stuck at creating the TextField, becouse the KeyListener is not working. I tried to implement the KeyListener but did not work.
What should I do?
Links:
The code:
public class TextField extends GUI implements KeyListener {
private boolean focused = false;
private String text = "";
public TextField(int x, int y, int width, int height) {
super(x, y, width, height);
}
public boolean isFocused() {
return focused;
}
public void setFocused(boolean focused) {
this.focused = focused;
}
public void append(String text) {
this.text = this.text + text;
}
public void delete() {
if (text.length() > 0) {
text = text.substring(0, text.length() - 1);
}
}
@Override
public void render(GameContainer gc, Graphics g) {
if (!focused) {
g.setColor(Color.gray);
} else {
g.setColor(Color.orange);
}
g.fillRect(x - width / 2, y - height / 2, width, height);
g.setColor(Color.darkGray);
g.fillRect(x - width / 2 + 5, y - height / 2 + 5, width - 10, height - 10);
g.setColor(Color.white);
g.drawString(text, x - g.getFont().getWidth(text) / 2, y - g.getFont().getHeight(text) / 2);
}
@Override
public void setInput(Input input) {
}
@Override
public boolean isAcceptingInput() {
return false;
}
@Override
public void inputEnded() {
}
@Override
public void inputStarted() {
}
@Override
public void keyPressed(int i, char c) {
System.out.println("This is not working");
}
@Override
public void keyReleased(int i, char c) {
}
}
This is how I create a TextField:
ipField = new TextField(width / 2, height / 2 - 60, 200, 50);
ipField.add(new ActionHandler() {
@Override
public void pressed() {
ipField.setFocused(true);
}
@Override
public void hover() {
}
@Override
public void notHover() {
if (input.isMousePressed(0)) {
ipField.setFocused(false);
}
}
});
guiManager.add(ipField);
**I found out, I can use a built in TextField for this:*
org.newdawn.slick.gui.TextField
Referring to JavaDoc, KeyListener
methods have the following syntax:
void keyPressed(KeyEvent e)
void keyReleased(KeyEvent e)
void keyTyped(KeyEvent e)
Going over your code, your syntax are:
public void keyPressed(int i, char c)
public void keyReleased(int i, char c)
This will be flagged as an error at compilation time.
Also, you should, ideally, create a separate handler class for your events.
TextField
is the object that will generate the event and there must be someone to listen to it. You need to specify who will listen by calling the addKeyListener()
method and passing the handler class' object as an argument.
PS: Switch to Swing. Use JTextField instead
Refer: http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyListener.html
Tutorial: http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
Event delegation model: http://wiki.answers.com/Q/What_is_delegation_event_model_in_java
Advantages of swing: https://softwareengineering.stackexchange.com/questions/112482/advantage-of-using-swing-over-awt