2013-03-22 2 views
0

저는 매우 간단한 계산기를 가지고 있으며 키를 JButton에 바인딩하려고합니다. 나는 Java에 익숙하지 않고 많이 알지 못합니다. 나는 그것이 ActionListener를 포함하고 있다는 것을 알고 있지만, 현재 갖고있는 것에 들어가기 위해 머리를 감쌀 수는 없다.JButton에 대한 키 바인딩

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 

@SuppressWarnings("serial") 
public class Calculator2 extends JFrame implements ActionListener { 

    // Declare the GUI objects and variables HERE 
    JTextField ansText; 
    JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b0, plus, minus, multi, div, 
      equal, clear; 
    JPanel p1, p2, p3; 
    Double val1 = 0.0, val2 = 0.0, answer = 0.0; 
    int operator = 0; 

    public static void main(String[] args) { 
     new Calculator2(); 
    } 

    public Calculator2() { 

     // GUI Creation Code goes HERE 

     ansText = new JTextField("", 7); 
     ansText.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); 


     ansText.addKeyListener(new KeyAdapter() { //Allow only numbers in ansText 
      public void keyTyped(KeyEvent e) { 
       char c = e.getKeyChar(); 
       if (((c < '0') || (c > '9')) && (c != KeyEvent.VK_BACK_SPACE)) { 
        e.consume(); 
       } 
      } 
     }); 

     b1 = new JButton("1"); 
     b1.addActionListener(this); 
     b2 = new JButton("2"); 
     b2.addActionListener(this); 
     b3 = new JButton("3"); 
     b3.addActionListener(this); 
     b4 = new JButton("4"); 
     b4.addActionListener(this); 
     b5 = new JButton("5"); 
     b5.addActionListener(this); 
     b6 = new JButton("6"); 
     b6.addActionListener(this); 
     b7 = new JButton("7"); 
     b7.addActionListener(this); 
     b8 = new JButton("8"); 
     b8.addActionListener(this); 
     b9 = new JButton("9"); 
     b9.addActionListener(this); 
     b0 = new JButton("0"); 
     b0.addActionListener(this); 
     plus = new JButton("+"); 
     plus.addActionListener(this); 
     minus = new JButton("-"); 
     minus.addActionListener(this); 
     multi = new JButton("*"); 
     multi.addActionListener(this); 
     div = new JButton("/"); 
     div.addActionListener(this); 
     equal = new JButton("="); 
     equal.addActionListener(this); 
     clear = new JButton("C"); 
     clear.addActionListener(this); 

     this.setLayout(new BorderLayout()); 

     p1 = new JPanel(); 
     this.add(p1, BorderLayout.NORTH); 
     p1.setLayout(new GridLayout(0, 1, 2, 2)); 
     p1.add(ansText); 

     p2 = new JPanel(); 
     this.add(p2, BorderLayout.CENTER); 
     p2.setLayout(new GridLayout(4, 3, 2, 2)); 
     p2.add(b1); 
     p2.add(b2); 
     p2.add(b3); 
     p2.add(plus); 

     p2.add(b4); 
     p2.add(b5); 
     p2.add(b6); 
     p2.add(minus); 

     p2.add(b7); 
     p2.add(b8); 
     p2.add(b9); 
     p2.add(multi); 

     p2.add(clear); 
     p2.add(b0); 
     p2.add(equal); 
     p2.add(div); 

     this.setSize(200, 250); 
     this.setVisible(true); 
    } 

    public void actionPerformed(ActionEvent e) { 

     //Number input 
     if (e.getSource() == b1) { 
      ansText.setText(ansText.getText() + b1.getText()); 
     } 
     else if (e.getSource() == b2) { 
      ansText.setText(ansText.getText() + b2.getText()); 
     } 
     else if (e.getSource() == b3) { 
      ansText.setText(ansText.getText() + b3.getText()); 
     } 
     else if (e.getSource() == b4) { 
      ansText.setText(ansText.getText() + b4.getText()); 
     } 
     else if (e.getSource() == b5) { 
      ansText.setText(ansText.getText() + b5.getText()); 
     } 
     else if (e.getSource() == b6) { 
      ansText.setText(ansText.getText() + b6.getText()); 
     } 
     else if (e.getSource() == b7) { 
      ansText.setText(ansText.getText() + b7.getText()); 
     } 
     else if (e.getSource() == b8) { 
      ansText.setText(ansText.getText() + b8.getText()); 
     } 
     else if (e.getSource() == b9) { 
      ansText.setText(ansText.getText() + b9.getText()); 
     } 
     else if (e.getSource() == b0) { 
      ansText.setText(ansText.getText() + b0.getText()); 
     } 

     //Operator input 
     else if (e.getSource() == plus) { 
      operator = 1; 
      val1 = Double.parseDouble(ansText.getText()); 
      ansText.setText(""); 
     } 
     else if (e.getSource() == minus) { 
      operator = 2; 
      val1 = Double.parseDouble(ansText.getText()); 
      ansText.setText(""); 
     } 
     else if (e.getSource() == multi) { 
      operator = 3; 
      val1 = Double.parseDouble(ansText.getText()); 
      ansText.setText(""); 
     } 
     else if (e.getSource() == div) { 
      operator = 4; 
      val1 = Double.parseDouble(ansText.getText()); 
      ansText.setText(""); 
     } 
     //Misc 
     else if (e.getSource() == equal) { 
      val2 = Double.parseDouble(ansText.getText()); 
      if (operator == 1) { 
       answer = val1 + val2; 
       ansText.setText("" + answer); 
      } else if (operator == 2) { 
       answer = val1 - val2; 
       ansText.setText("" + answer); 
      } else if (operator == 3) { 
       answer = val1 * val2; 
       ansText.setText("" + answer); 
      } else if (operator == 4) { 
       answer = val1/val2; 
       ansText.setText("" + answer); 
      } 
     } 
     else if (e.getSource() == clear) { 
      ansText.setText(""); 
      val1 = 0.0; 
      val2 = 0.0; 
      answer = 0.0; 
      operator = 0; 
     } 
    } 
} 
+0

어떤 오류가 발생합니까? 문제가 무엇입니까? – theJollySin

+0

키를 버튼에 바인딩하려는 경우, 즉 키보드의 "+"를 누르면 GUI의 "+"를 클릭하는 것과 동일합니다. http://docs.oracle.com/javase/tutorial/uiswing/misc/ keybinding.html – jedyobidan

답변

0

모든 작업을 수행하는 내부 클래스가 하나 인 단일 클래스를 갖고 싶지는 않습니다. Java Swing은 다른 GUI 시스템과 마찬가지로 MVC, Model-View-Controller를 기반으로합니다.

여기 모델은 누적 기의 현재 값과 값이 디스플레이에 저장되는 개체입니다. RPN 계산기를 쓰고 있었습니까? 모델 객체는 RPN 스택을 포함합니다.

보기는 스윙 클래스입니다 (JTextFieldJButtons).

컨트롤러는 실제 작업을 수행하는 새로운 객체 인 CalculatorController입니다. ActionListener 숫자를 더하거나 빼거나 곱하거나 나누는 대신 CalculatorController에서 메서드를 호출하면 해당 개체가 JTextField를 업데이트합니다.

오메가의 설명서를 보는 jedyobidan의 제안은 매우 좋습니다. 키 스트로크는 JPanel 입력 맵에 넣으려고 할 것입니다. 사용자가 집중 한 패널의 어느 위치에 상관없이 적용해야하기 때문입니다. 그런 다음 액션 맵은 CalculatorController에서 메서드를 호출하는 AbstractActions을 보유합니다.

저는 Mac이나 이전의 NeXT에서 Interface Builder 프로그램으로 GUI를 개발 한 스타일이 Java Swing에서 사용되는 스타일보다 초보자에게 훨씬 유리하다고 생각했습니다.

2

How to Use Key Bindings 자습서에서는 키 바인딩에 대해 자세히 설명합니다. 다음은 키패드와 기본 키보드에서 액션을 플러스 키에 바인딩하는 간단한 예입니다.

JPanel panel = new JPanel(); 
JPanel panel = new JPanel(); 
    panel.getInputMap(JPanel.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
      KeyStroke.getKeyStroke(KeyEvent.VK_ADD, 0), "plus"); 
panel.getInputMap(JPanel.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
     KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, 
       InputEvent.SHIFT_MASK), "plus"); 

panel.getActionMap().put("plus", plusAction); 
panel.add(button); 
+2

추상화에 대해 언급하는 것을 잊어 버렸습니다. Xxx.getInputMap (JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT/*. WHEN_FOCUSED * /) .put (KeyStroke.getKeyStroke ("0"), "zero"); – mKorbel

+0

@mKorbel은 그것을 놓쳤습니다, 감사합니다! – tenorsax