我是编程的初学者,所以请耐心等待,我正在尝试使用KeyListener制作计算器,这是我所拥有的(剪切的代码)

    public void keyPressed(KeyEvent e){
    int code = e.getKeyCode();
    System.out.println("   Code: " + KeyEvent.getKeyText(code));

    if(KeyEvent.VK_ADD == e.getKeyCode()){
        tmp = Double.parseDouble(txtDisplay.getText());
        txtDisplay.setText(display);
        add = true;

    }
    if(KeyEvent.VK_DIVIDE == e.getKeyCode()){
        tmp = Double.parseDouble(txtDisplay.getText());
        txtDisplay.setText(display);
        div = true;
    }
    if(KeyEvent.VK_SUBTRACT == e.getKeyCode()){
        tmp = Double.parseDouble(txtDisplay.getText());
        txtDisplay.setText(display);
        sub = true;
    }
    if(KeyEvent.VK_MULTIPLY == e.getKeyCode()){
        tmp = Double.parseDouble(txtDisplay.getText());
        txtDisplay.setText(display);
        mul = true;
    }
    if(e.getKeyCode()==KeyEvent.VK_BACK_SPACE){
        txtDisplay.setText("");
        tmp = 0;
        toSolve = 0;
    }
    if(e.getKeyCode() == KeyEvent.VK_ENTER){
        toSolve = Double.parseDouble(txtDisplay.getText());
        if( add == true ){
            toSolve = tmp + toSolve;}

        else if ( sub == true  ){

            toSolve = tmp - toSolve;}

        else if ( mul == true  ){

            toSolve = tmp * toSolve;}

        else if ( div == true  ){

            toSolve = tmp / toSolve;}

    txtDisplay.setText(Double.toString( toSolve ));

    add = false ;
    sub = false ;
    mul = false ;
    div = false ;

    }


}


我希望它执行操作,但是当我运行它时,似乎只是在做附加操作。我认为这可能在我的编程逻辑中。另外,如何删除文本字段中的操作符号,因为它还会转换符号,因此会引发异常。

最佳答案

尝试使用keyReleased()而不是keyPressed():

public void keyReleased(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_ENTER) {
        //Do something
}


Java中的某些侦听器非常容易出错,如果您不质疑其背后的原因,有时它可以使您省去很多麻烦^^

07-24 15:36