Implementing the keyTyped() method
The keyTyped() method executes. When a key on the keyboard interface is pressed and is followed by key release event. The keyTyped() method calls the calculate() method, if the key typed label is +,-, and pow. The keyTyped() method also appends the key typed label in the text field of the calculator. The label of the label need to be between 0 - 9. The keyTyped method is a keyListener method that is implemented by the calculator_app for trapping keyboard events.Declaration of the method keyTyped()
public void keyTyped(KeyEvent e)//Denotes a key press followed by a key release.
{
char ch;
ch=e.getKeyChar();
if ((ch=='1')||(ch=='2') || (ch=='3') ||(ch=='4')|| (ch=='5')||(ch=='6')||(ch=='7')||(ch=='8')||(ch=='9') ||(ch=='0')) //To check the source label of the pressed key.
{
if(pressed)
{
str="0";
pressed=false;
}
if(str=="0")//Check whether string is empty or not.
str=""+ch;
else
str=str+ch;
}//End if.
else if(ch=='.'&& cond5)
{
if(pressed)
{
str="0";
pressed=false;
}
str=str+ch;
cond5=false;
}
else if((ch=='+')||(ch=='-')||(ch=='*') ||(ch=='/'))
{
op=""+ch;
str1=str;
str="0";
}
else if(ch=='=')
calculate();
textf.setText(str);
}//End of method declaration KeyTyped().
The above listing shows the declaration of the keyTyped() method. The keyTyped() method is executed when a key is presed and is followed by key release event on the calculator interface.
Implementing the keyPressed() method
The keyPressed() method is called, when the key on the keyboard is pressed. Teh keyPressed() method is a built-in listener method of keyListener class that is implemented by Calculator_app class for ttrapping the keyboard event. The method checks the American Starndard Code for Information Interchange(ASCII) value of the key pressed. The Java built-in event handling method, getKeyCode() gives the ASCII value of the key, which is perssd.
public void keyPressed(KeyEvent e)//Indicates a key is pushed down.
{
double ac=e.getKeyCode();
if((ac==13)||(ac==10))
calculate();
else if(ac==8)
{
if(str.compareTo("")==0)
textf.setText("Error");
else
{
str = str.substring(0,str.length()-1);
textf.setText(str);
}
}
}//End of method KeyPressed.
The above listing shows the declaration of the keyPressed() method. The keyPressed() method invokes a built-in method named getCodeKey(). The calculate() method is invoked if the ASCII value of the key pressed is 13 or 10.
More To Be Added ...
0 Comments:
Post a Comment