admrply
admrply

Reputation: 169

Listening for a keystroke OR a button press

I am building a calculator app to get my head around building GUIs with Swing. I want to be able to click on the calculator buttons, but also to type them in on the keyboard.

I've been looking at KeyStroke but I'm not entirely sure how to implement it in my current JButton ActionListener.

Here's a sample of a button press:

public void actionPerformed(ActionEvent e) {
    if(e.getSource()==btn1){
        if(calcOperatorActive){display.setText("1");calcOperatorActive=false;}
        else if(calcOperator=="equals"){display.setText("1");calcTempMem=0;calcOperator="none";}
        else{display.setText(display.getText()+"1");}
    }

I want to be able to add a key listener on the if statement, something along the lines of:

if((e.getSource()==btn1)|(KeyStroke.getKeyStroke("1")){
    //the code
}

But I get an error saying can't compare boolean and KeyStroke.

Upvotes: 0

Views: 134

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

This is not valid Java:

if((e.getSource()==btn1)|(KeyStroke.getKeyStroke("1")){
    //the code
}

since the first part of the boolean expression, here

(e.getSource()==btn1)

is a boolean expression, very good, but not so the 2nd part:

(KeyStroke.getKeyStroke("1")

For an if expression to work with a compound boolean test, the boolean test must be an actual boolean expression. So in your situation for valid java you would need

if (booleanExpression1 || booleanExpression2) {
  //...
}

or both statements would have to be boolean expressions that evaluate to true or false, and again, your 2nd statement, (KeyStroke.getKeyStroke("1")


OK, but that's just the first problem with your code/question. The other problem is that there is no boolean expression you can use for the keystroke portion since that is not how Java handles KeyStrokes. Instead you will want to use Key Bindings for this (not a KeyListener).

For example, please have a look at camickr's answer to a similar question here.

Upvotes: 2

Related Questions