0

My program is just a simple calculator and for some reason, the keyPressed() method isn't being called whenever I press a key on my keyboard. I've done System.out.println() so as to test if it was being called, and it wasn't. Please help

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

public class FullCalculator extends Frame implements ActionListener,KeyListener{
private Button btn0, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, 
btnAdd, btnSub, btnMul, btnDiv, btnEquals, btnDot, btnC, btnCE, btnRand, 
btnBack;
private Label lbl1, lbl2, black;
private float temp, temp2;
private String operator, tempS;

public FullCalculator (String s){
    super (s);
    init();
    this.addKeyListener(this);
    this.setFocusable(true);
    this.requestFocus(true);
    setLayout(null);
}

public void init(){
    Font f = new Font ("Courier", Font.BOLD, 13);

    btn0 = new Button ("0");
    btn0.setBounds(6, 285, 70, 70);
    btn0.addActionListener(this);
    btn0.setFont (f);

    btn1 = new Button ("1");
    btn1.setBounds(6, 215, 70, 70);
    btn1.addActionListener(this);
    btn1.setFont (f);

    btn2 = new Button ("2");
    btn2.setBounds(76, 215, 70, 70);
    btn2.addActionListener(this);
    btn2.setFont (f);

    btn3 = new Button ("3");
    btn3.setBounds(146, 215, 70, 70);
    btn3.addActionListener(this);
    btn3.setFont (f);

    btn4 = new Button ("4");
    btn4.setBounds(6, 145, 70, 70);
    btn4.addActionListener(this);
    btn4.setFont (f);

    btn5 = new Button ("5");
    btn5.setBounds(76, 145, 70, 70);
    btn5.addActionListener(this);
    btn5.setFont (f);

    btn6 = new Button ("6");
    btn6.setBounds(146, 145, 70, 70);
    btn6.addActionListener(this);
    btn6.setFont (f);

    btn7 = new Button ("7");
    btn7.setBounds(6, 75, 70, 70);
    btn7.addActionListener(this);
    btn7.setFont (f);

    btn8 = new Button ("8");
    btn8.setBounds(76, 75, 70, 70);
    btn8.addActionListener(this);
    btn8.setFont (f);

    btn9 = new Button ("9");
    btn9.setBounds(146, 75, 70, 70);
    btn9.addActionListener(this);
    btn9.setFont (f);

    btnAdd = new Button ("+");
    btnAdd.setBounds(216, 75, 70, 70);
    btnAdd.addActionListener(this);
    btnAdd.setFont (f);

    btnSub = new Button ("-");
    btnSub.setBounds(216, 145, 70, 70);
    btnSub.addActionListener(this);
    btnSub.setFont (f);

    btnMul = new Button ("*");
    btnMul.setBounds(216, 215, 70, 70);
    btnMul.addActionListener(this);
    btnMul.setFont (f);

    btnDiv = new Button ("/");
    btnDiv.setBounds(146, 285, 70, 70);
    btnDiv.addActionListener(this);
    btnDiv.setFont (f);

    btnEquals = new Button ("=");
    btnEquals.setBounds(216, 285, 70, 70);
    btnEquals.addActionListener(this);
    btnEquals.setFont (f);

    btnDot = new Button (".");
    btnDot.setBounds (76, 285, 70, 70);
    btnDot.addActionListener(this);
    btnDot.setFont (f);

    btnC = new Button ("C");
    btnC.setBounds (76, 355, 70, 70);
    btnC.addActionListener(this);
    btnC.setFont (f);

    btnCE = new Button ("CE");
    btnCE.setBounds (146, 355, 70, 70);
    btnCE.addActionListener(this);
    btnCE.setFont (f);

    btnRand = new Button ("RandNum");
    btnRand.setBounds (6, 355, 70, 70);
    btnRand.addActionListener(this);
    btnRand.setFont (f);

    btnBack = new Button ("<==");
    btnBack.setBounds (216, 355, 70, 70);
    btnBack.addActionListener (this);
    btnBack.setFont (f);

    lbl1 = new Label ("", Label.RIGHT);
    lbl1.setBounds (9, 52, 274, 22);
    lbl1.setBackground (Color.WHITE);
    lbl1.setFont (new Font ("Courier", Font.BOLD, 20));

    lbl2 = new Label ("", Label.RIGHT);
    lbl2.setBounds (9, 32, 274, 20);
    lbl2.setBackground (Color.WHITE);
    lbl2.setFont (new Font ("Monospaced", Font.PLAIN, 12));

    black = new Label ("");
    black.setBounds (6, 30, 280, 50);
    black.setBackground (Color.BLACK);

    add(btn0);
    add(btn1);
    add(btn2);
    add(btn3);
    add(btn4);
    add(btn5);
    add(btn6);
    add(btn7);
    add(btn8);
    add(btn9);
    add(btnAdd);
    add(btnSub);
    add(btnMul);
    add(btnDiv);
    add(btnEquals);
    add(btnDot);
    add(btnC);
    add(btnCE);
    add(btnRand);
    add(btnBack);

    add(lbl1);
    add(lbl2);
    add(black);

    addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent we){
                System.exit(0);
            }
        });
}

@Override
public void actionPerformed(ActionEvent e){
    try{
        if (e.getSource()==btn0){
            setLabel("0");
        }
        else if (e.getSource()==btn1){
            setLabel("1");
        }
        else if (e.getSource()==btn2){
            setLabel("2");
        }
        else if (e.getSource()==btn3){
            setLabel("3");
        }
        else if (e.getSource()==btn4){
            setLabel("4");
        }
        else if (e.getSource()==btn5){
            setLabel("5");
        }
        else if (e.getSource()==btn6){
            setLabel("6");
        }
        else if (e.getSource()==btn7){
            setLabel("7");
        }
        else if (e.getSource()==btn8){
            setLabel("8");
        }
        else if (e.getSource()==btn9){
            setLabel("9");
        }
        else if (e.getSource()==btnAdd){
            temp = Float.parseFloat(lbl1.getText());
            operator = "+";
            lbl2.setText(lbl1.getText()+"+");
            lbl1.setText("");
        }
        else if (e.getSource()==btnSub){
            temp = Float.parseFloat(lbl1.getText());
            operator = "-";
            lbl2.setText(lbl1.getText()+"-");
            lbl1.setText("");
        }
        else if (e.getSource()==btnMul){
            temp = Float.parseFloat(lbl1.getText());
            operator = "*";
            lbl2.setText(lbl1.getText()+"*");
            lbl1.setText("");
        }
        else if (e.getSource()==btnDiv){
            temp = Float.parseFloat(lbl1.getText());
            operator = "/";
            lbl2.setText(lbl1.getText()+"/");
            lbl1.setText("");
        }
        else if (e.getSource()==btnEquals){
            temp2 = Float.parseFloat(lbl1.getText());
            switch (operator){
                case "+": lbl1.setText("" + (temp+temp2)); break;
                case "-": lbl1.setText("" + (temp-temp2)); break;
                case "*": lbl1.setText("" + (temp*temp2)); break;
                case "/": lbl1.setText("" + (temp/temp2)); break;
            }
        }
        else if (e.getSource()==btnDot){
            setLabel(".");
        }
        else if (e.getSource()==btnC){
            lbl1.setText("");
            lbl2.setText("");
        }
        else if (e.getSource()==btnCE){
            lbl1.setText("");
        }
        else if (e.getSource()==btnRand){
            lbl1.setText(""+(int)(Math.random()*100)+1);
        }
        else if (e.getSource()==btnBack){
            tempS = lbl1.getText();
            lbl1.setText((lbl1.getText().substring(0, tempS.length() - 1)));
        }
    }catch (Exception ex){
        JOptionPane.showMessageDialog (null, "Error " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
}

@Override
public void keyPressed(KeyEvent e){
    if (e.getKeyCode()==(KeyEvent.VK_0|KeyEvent.VK_NUMPAD0)){
        setLabel("0");
    }
    else if (e.getKeyCode()==(KeyEvent.VK_1|KeyEvent.VK_NUMPAD1)){
        setLabel("1");
    }
    else if (e.getKeyCode()==(KeyEvent.VK_2|KeyEvent.VK_NUMPAD2)){
        setLabel("2");
    }
    else if (e.getKeyCode()==(KeyEvent.VK_3|KeyEvent.VK_NUMPAD3)){
        setLabel("3");
    }
    else if (e.getKeyCode()==(KeyEvent.VK_4|KeyEvent.VK_NUMPAD4)){
        setLabel("4");
    }
    else if (e.getKeyCode()==(KeyEvent.VK_5|KeyEvent.VK_NUMPAD5)){
        setLabel("5");
    }
    else if (e.getKeyCode()==(KeyEvent.VK_6|KeyEvent.VK_NUMPAD6)){
        setLabel("6");
    }
    else if (e.getKeyCode()==(KeyEvent.VK_7|KeyEvent.VK_NUMPAD7)){
        setLabel("7");
    }
    else if (e.getKeyCode()==(KeyEvent.VK_8|KeyEvent.VK_NUMPAD8)){
        setLabel("8");
    }
    else if (e.getKeyCode()==(KeyEvent.VK_9|KeyEvent.VK_NUMPAD9)){
        setLabel("9");
    }
    else if (e.getKeyCode()==KeyEvent.VK_PLUS){
        temp = Float.parseFloat(lbl1.getText());
        operator = "+";
        lbl2.setText(lbl1.getText()+"+");
        lbl1.setText("");
    }
    else if (e.getKeyCode()==KeyEvent.VK_MINUS){
        temp = Float.parseFloat(lbl1.getText());
        operator = "-";
        lbl2.setText(lbl1.getText()+"-");
        lbl1.setText("");
    }
    else if (e.getKeyCode()==KeyEvent.VK_ASTERISK){
        temp = Float.parseFloat(lbl1.getText());
        operator = "*";
        lbl2.setText(lbl1.getText()+"*");
        lbl1.setText("");
    }
    else if (e.getKeyCode()==KeyEvent.VK_SLASH){
        temp = Float.parseFloat(lbl1.getText());
        operator = "/";
        lbl2.setText(lbl1.getText()+"/");
        lbl1.setText("");
    }
    else if (e.getKeyCode()==KeyEvent.VK_PERIOD){
        setLabel(".");
    }
}

@Override
public void keyReleased(KeyEvent e){

}

@Override
public void keyTyped(KeyEvent e){

}

public void setLabel(String key){
    lbl1.setText(lbl1.getText()+key);
}

}

I've also tried without the setFocus(true) and requestFocus(true)

  • 1
    Why do you have a Frame which is also a KeyListener? You should avoid creating "all in one" classes. – Tom Feb 06 '18 at 14:25
  • Possible duplicate of [Pipe (|) operator in Java](https://stackoverflow.com/questions/3312611/pipe-operator-in-java) – Tom Feb 06 '18 at 14:25
  • Please read the dupe question to understand that this `e.getKeyCode()==(KeyEvent.VK_6|KeyEvent.VK_NUMPAD6)` doesn't mean "either VK_6 or VK_NUMPAD0". – Tom Feb 06 '18 at 14:31
  • Please format code as code and only give minimal example. (MCVE) – user202729 Feb 06 '18 at 14:32
  • Also, your KeyListener is assigned to the Frame, not the Labels. – Tom Feb 06 '18 at 14:33
  • A button will have the keyboard focus, not the frame, so keypress events will never go to the frame. – AJNeufeld Feb 06 '18 at 14:34
  • 1) Why use AWT? See [this answer](http://stackoverflow.com/questions/6255106/java-gui-listeners-without-awt/6255978#6255978) for many good reasons to abandon AWT components in favor of Swing. 2) For Swing, we typically use [key bindings](https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) rather than the lower level `KeyListener`. 3) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). .. – Andrew Thompson Feb 07 '18 at 05:22
  • .. 4) See [Detection/fix for the hanging close bracket of a code block](http://meta.stackexchange.com/q/251795/155831) for a problem I could no longer be bothered fixing. 5) See also this [calculator example](http://stackoverflow.com/a/7441804/418556). It uses `ScriptEngine` to evaluate the expression in the text field. – Andrew Thompson Feb 07 '18 at 05:22

1 Answers1

0

The first problem you have is an Unresponsive KeyListener for JFrame.

Consider registering the keylistener to the relevant components.

Then, as @Tom also pointed out, KeyEvent.VK_0|KeyEvent.VK_NUMPAD0 for instance, performs a bitwise OR operation between the integer values KeyEvent.VK_0and KeyEvent.VK_NUMPAD0.

And

 if (e.getKeyCode()==(KeyEvent.VK_0|KeyEvent.VK_NUMPAD0))

becomes

if (e.getKeyCode()==<result of the above bitwise OR operation>)

Replace your conditions with e.g

if ((e.getKeyCode()==KeyEvent.VK_0) || (e.getKeyCode()==KeyEvent.VK_NUMPAD0))

to get the expected behavior.

Also note the double-pipe ||, this prevents the right-hand part to be evaluated if the left-hand part is true.

Cf. Pipe (|) operator in Java

Arnaud
  • 17,229
  • 3
  • 31
  • 44
  • Note that in this case, `VK_0=48` and `VK_NUMPAD0=96`, and `48|96=112`, and `VK_F1=112`. So while attempting to check for 0s, it's actually matching F1. _While interesting to see, do not use the numbers in code, use the `KeyEvent.VK_` constants_ – phflack Feb 06 '18 at 14:38
  • I appreciate the response, but with the || it did not work giving the following error; – Jokniserous Feb 06 '18 at 14:52
  • bad operand types for binary operator '||' first type: int; second type: int; – Jokniserous Feb 06 '18 at 14:53
  • It did work though, when I removed the OR altogether, so thks anyways ;) – Jokniserous Feb 06 '18 at 14:53
  • Now, for some reason another problem is occuring.... Whenever I type any digit it sets the calculator display to '00' instead of just '0' ... please help ;/ – Jokniserous Feb 06 '18 at 15:00
  • nvm, solved it too... discovered another KeyListener in the main method... all's good THANKS – Jokniserous Feb 06 '18 at 15:04