2014-02-12 57 views
-1

在java中,我創建了一個應用程序,當它被激活時(如果wantCommand = true),它將讀取你按下它讀取的關鍵字並將其添加到字符串中,然後使用Java.awt .Graphics,它將字符串繪製到屏幕上...有人可以幫助我獲取字符串到您輸入的字符(也可能刪除,以防萬一您將輸入內容搞亂) 這是我所擁有的到目前爲止:Java KeyPressed for all keys

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); 
     } 
    } 
} 

回答

2

你似乎還有很長的路要走。你需要:

  • 最重要的是一個GUI,最好是Swing而不是AWT,這樣你的按鍵和字符串繪圖就有一個應用程序來與數據交互和顯示。
  • 連接到具有焦點的組件的KeyListener。請注意,我不認爲Key Bindings對此會有效。
  • 一個覆蓋paintComponent(Graphics g)方法的JPanel。
+0

我已經有了第一個和最後一個選項,它們在不同的類中。這只是我已經擁有的一款遊戲的附加課程。 –

+0

@BryceHahn:沒有更多的上下文和代碼,很難弄清楚什麼是錯的。如果你有一個龐大的代碼庫,大多數人都沒有時間去查看它,但是你可能想考慮創建併發佈一個[最小的,可編譯的,可運行的示例程序](http://stackoverflow.com/help/mcve )我們可以運行,測試和修改,並向我們展示您的問題。 –

0

嘗試向GUI註冊keyPressed事件偵聽器;該事件告訴哪個鍵被按下,您可以通過哪些鍵

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