问题:
我为我的游戏写了一些 GUI 东西(一个按钮)。但我坚持创建 TextField,因为 KeyListener 不起作用。我试图实现 KeyListener 但没有奏效。
我应该怎么办?
链接:
编码:
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) {
}
}
这就是我创建 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);
**我发现,我可以为此使用内置的 TextField:*
org.newdawn.slick.gui.TextField