Slick2d | TextField字符传递

时间:2013-04-21 18:08:30

标签: java keylistener slick2d

问题:

我为我的游戏写了一些GUI东西(一个按钮)。但我坚持创建TextField,因为KeyListener无法正常工作。我试图实现KeyListener但没有工作。
我该怎么办?

链接:

  

The game (finished)

代码:

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

1 个答案:

答案 0 :(得分:1)

参考JavaDoc,KeyListener方法具有以下语法:

void keyPressed(KeyEvent e)
 void keyReleased(KeyEvent e)
 void keyTyped(KeyEvent e)

查看代码,您的语法是:
public void keyPressed(int i, char c)
public void keyReleased(int i, char c)

这将在编译时标记为错误。

此外,您应该理想为您的活动创建一个单独的处理程序类 TextField生成事件的对象,必须有人监听它。您需要通过调用addKeyListener()方法并将处理程序类'对象作为参数传递来指定谁将监听。

PS:切换到Swing。请改用JTextField

参考:http://docs.oracle.com/javase/6/docs/api/java/awt/event/KeyListener.html
教程:http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
事件委托模型:http://wiki.answers.com/Q/What_is_delegation_event_model_in_java
摆动的优点:https://softwareengineering.stackexchange.com/questions/112482/advantage-of-using-swing-over-awt