2013-06-24 40 views
-2

我想創建一個程序,在屏幕上顯示圖像,如果變量keycode等於密鑰VK_ESCAPE,它將使用方法validate從屏幕上移除圖像。我怎樣才能關注keylistener,以便我可以運行if語句並驗證圖像。我有正確的庫導入,我沒有得到任何錯誤?!Java Keylistener如果語句

public void keyPressed(KeyEvent e){ 
    int keycode = e.getKeyCode(); 
    if(keycode == KeyEvent.VK_ESCAPE){ 
    scroll = new ImageIcon("").getImage(); 
    validate(); 
    e.consume(); 
    } 
} 
+0

是'keyPressed'叫呢?您想要觸發事件的組件必須具有鍵盤焦點。推薦的替代方案是使用[鍵綁定](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html)而不是'KeyListener'。然後該組件不需要成爲焦點所有者。 –

+0

您需要從父母中刪除圖片,例如JPanel然後調用revalidate() –

回答

3

您應該使用的Key Bindings代替Key Listeners事業key listeners主要問題是,你必須有重點,除了在按鍵綁定你只有一個動作綁定到一個鍵,在keylisteners綁定到所有。順便說一句,你不是在你的組件中刪除任何東西 你必須刪除圖像,然後致電revalidate()

教程How to use key bindings

例子:

AbstractAction escapeAction = new AbstractAction() { 
    @Override 
    public void actionPerformed(ActionEvent e) { 
     myComponent.remove(img); // if you are not using label,if yes label.setImage(null); 
     revalidate(); // im not pretty sure about this 2 lines 
     repaint(); //suggested by madProgrammer 
    }}; 
String key = "ESCAPE"; 
KeyStroke keyStroke = KeyStroke.getKeyStroke(key); 
component.getInputMap().put(keyStroke, key); 
component.getActionMap().put(key, escapeAction); 
+0

雖然我當然同意,並解釋爲什麼OP應該使用KeyListener的鍵綁定不會誤入歧途,沒有什麼比盲目的建議;) – MadProgrammer

+0

@MadProgrammer是否正確刪除img像這樣?假設他有img作爲最終變量 – nachokk

+0

我依賴於OP正在嘗試做什麼。將標籤的圖標設置爲「null」也可能起作用。您仍然需要重新驗證(並可能重繪)父容器以使其更新 – MadProgrammer