我想創建一個程序,在屏幕上顯示圖像,如果變量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();
}
}
是'keyPressed'叫呢?您想要觸發事件的組件必須具有鍵盤焦點。推薦的替代方案是使用[鍵綁定](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html)而不是'KeyListener'。然後該組件不需要成爲焦點所有者。 –
您需要從父母中刪除圖片,例如JPanel然後調用revalidate() –