我是编程的初学者所以请耐心等待我,我尝试使用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 ;
}
}
我希望它能够执行操作,但是当我运行它时,它似乎只是在进行添加。我想它可能在我的编程逻辑中。另外,如何删除文本字段中的操作符号,因为它还会转换符号,以便抛出异常。
答案 0 :(得分:0)
尝试使用keyReleased()而不是keyPressed():
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
//Do something
}
Java中的一些听众非常容易受到攻击,如果你不质疑它背后的推理,有时会为你节省很多麻烦^^