【问题标题】:Java KeyPressed for all keysJava KeyPressed 用于所有键
【发布时间】:2014-02-12 20:25:30
【问题描述】:

在java中我正在制作一个应用程序,当它被激活时(如果wantCommand = true),它会读取你按下的任何键读取并将其添加到字符串中,然后使用Java.awt.Graphics,它绘制字符串到屏幕...有人可以帮助我使用代码来获取您输入的字符串(如果您弄乱了您输入的内容,也可能删除) 这是我目前所拥有的:

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;

public class slashCommand {
    public static boolean wantCommand = false;
    public static String commandLine = "kill";
    public static String getText () {
        //get the string in a for loop or something maybe
        return commandLine;
    }
    public static void render(Graphics g) {
        if (wantCommand) {
            g.setColor(new Color(0, 0, 0, 130));
            g.fillRect(Inventory.inv_bag[0].x - 100, Inventory.inv_bag[0].y + 116, Component.size.width, 10);
            g.setColor(new Color(255, 255, 255));
            g.setFont(new Font("Arial", Font.PLAIN, 10));
            g.drawString("/ " + commandLine, Inventory.inv_bag[0].x - 69, Inventory.inv_bag[0].y + 125);
        }
    }
}

【问题讨论】:

    标签: java input awt keypress stringreader


    【解决方案1】:

    看来你还有很长的路要走。你需要:

    • 最重要的是一个 GUI,最好是 Swing 而不是 AWT,这样您的按键和字符串绘图就有一个应用程序来与之交互并显示数据。
    • 附加到具有焦点的组件的 KeyListener。请注意,我不认为 Key Bindings 可以很好地解决这个问题。
    • 具有被覆盖的paintComponent(Graphics g) 方法的JPanel。

    【讨论】:

    • 我已经有了第一个和最后一个选项,它们属于不同的类别。这只是我已经拥有的游戏的附加课程。
    • @BryceHahn:没有更多上下文和代码,很难找出问题所在。如果您的代码库很大,大多数人都没有时间查看它,但您可能需要考虑创建并发布一个minimal, compilable, runnable example program,我们可以运行、测试和修改它,这向我们展示了您的问题。
    【解决方案2】:

    尝试向 GUI 注册一个 keyPressed 事件监听器;该事件告诉您可以传递哪个键被按下

    private void formKeyPressed(java.awt.event.KeyEvent evt)                                
    {                                    
       System.out.println(evt.getKeyChar());
    }         
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-26
      • 1970-01-01
      • 2018-10-06
      • 2016-04-15
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 2014-09-19
      相关资源
      最近更新 更多