키 바인더가 어떻게 작동하는지 배우려고하고 있습니다. 자바 튜토리얼에서 오해 한 것 같습니다. 이 코드입니다 : 내가 이해에서키 바인드가 작동하지 않고, 액션이 수행되지 않았습니다.
public class KeyBinder {
public static void main(String[] args) {
//making frame and label to update when "g" key is pressed.
JLabel keybinderTestLabel;
JFrame mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(300,75);
mainFrame.setLocationRelativeTo(null);
mainFrame.setVisible(true);
keybinderTestLabel = new JLabel("Press the 'g' key to test the key binder.");
mainFrame.add(keybinderTestLabel);
Action gPressed = new AbstractAction(){
@Override
public void actionPerformed(ActionEvent e) {
keybinderTestLabel.setText("Key Binding Successful.");
System.out.println("Key Binding Successful.");
//Testing to see if the key binding was successful.
}
};
keybinderTestLabel.getInputMap().put(KeyStroke.getKeyStroke("g"), "gPressed");
keybinderTestLabel.getActionMap().put("gPressed", gPressed);
/*
* from my understanding, these two lines map the KeyStroke event of the g key
* to the action name "gpressed", then map the action name "gpressed" to the action
* gpressed.
*
*/
}
}
, 내가 작업 이름 "gPressed"에 g 키 입력을 매핑 한 다음 매핑하는 작업 gPressed
에. 그러나 어떤 이유로 프로그램을 실행할 때 g 키를 누르면 텍스트 레이블이 업데이트되지 않습니다. 여기에 무슨 문제가 있니? 키보드의 g 키에 실제로 매핑되지 않은 "g"키 입력입니까?
은 (1+)'KeyStroke.getKeyStroke ("g")는'
KeyStroke.getKeyStroke(KeyEvent.VK_G, 0)
를 사용해보십시오. String를 사용하려면, 다음을 사용할 수 있습니다 :'KeyStroke.getKeyStroke ("G")'. 키보드의 "g"를 누르기위한 바인딩을 등록 할 경우. 문자열을 사용하면 기본적으로 KeyEvent.VK _ 뒤에 텍스트를 가져옵니다. 따라서'KeyStroke.getKeyStroke ("ENTER")'를 사용하여 "Enter"키를 청취 할 수도 있습니다. 또는 이해하기 쉽도록 문자 매개 변수를 사용하는 것입니다 :'KeyStroke.getKeyStroke ('g')', – camickr아, 고마워! 그러나 getKeyStroke (KeyEvent.VK_G, 0)를 사용하면 0 매개 변수는 무엇을 수행합니까? – Psear
@Psear 수정 자 (예 : 이동/변경/제어) – MadProgrammer