2015-01-09 6 views
0

버튼을 클릭하여 작동하는 계산기 프로그램이 있습니다. 텍스트를 문자열에 추가 한 다음 나중에 계산을 수행하기 위해 double로 변환하고 변환합니다.키 트리거 액션 리스너

but1.addActionListener(this); 
if (source==but1) // Number buttons shows the text to display 
     { 
      text.append("1"); 
} 

public double number_convert() // Converts the string back to double 
    { 

     double num1; 
     String s; 
     s = text.getText(); 
     num1 = Double.parseDouble(s); // creating a double from the string value. 
     return num1; //returns value 
    } 

키보드 키로 ActionListener을 실행해야합니다. 어떤 아이디어가 이것을 어떻게?

모든 것이 계산기에서 작동합니다. 키보드 키를 눌렀을 때 버튼을 실행하는 방법 만 있으면됩니다.

답변

2

가장 간단한 해결책은 Action과 Key Bindings API의 조합을 사용하는 것입니다. 그들이 매우 유연하고,

public class NumberAction extends AbstractAction { 

    private int number; 

    public NumberAction(int number) { 
     this.number = number; 
     putValue(NAME, Integer.toString(number)); 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     // Deal with the number... 
    } 
} 

Action

버튼 및 키 바인딩을 모두 사용할 수 있습니다 ... 자세한 내용

NumberAction action = new NumberAction(1); 
JButton btn = new JButton(action); 
InputMap im = btn.getInputMap(WHEN_IN_FOCUSED_WINDOW); 
ActionMap am = btn.getActionMap(); 

im.put(KeyStroke.getKeyStroke(KeyEvent.VK_1, 0), "Number1"); 
am.put("Number1", action); 

그리고 일반적인 예를 Action에 대한 How to Use ActionsHow to Use Key Bindings보기 ...