What is key event? How it is handled in Java? Explain with suitable Java source cod
Handling Key Events
The class KeyEvent is defined in java.awt.event package. Key events occur when a key is pressed on the keyboard. Any component can generate these events, and a class must implement KeyListener interface to support them. The object that implements the KeyListener interface gets this KeyEvent when the event occurs and hence must handle the event by overriding keyTyped(), keyPressed(), and keyReleased) methods of KeyListener interface. Pressing and releasing a key on the keyboard results in the generating the following key events (in order):
KEY PRESSED
KEY TYPED (is only generated if a valid Unicode character could be generated.)
KEY RELEASED
Example
import javax.swing.";
import java.awt.";
import java.awt.event.";
public class EventTest extends JFrame implements KeyListener
{
private JTextField t1, 12, 13;
JLabel 11,12,13;
JButton b;
public EventTest()
{
super("Handling Key Event");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
11= new JLabel("First Value:");
12= new JLabel("Second Value:");
13= new t1 = new JLabel("Result:"); JTextField(10);
12= new JTextField(10); 13=new JTextField(10);
bnew JButton("Calculate"); b.addKeyListener(this);
setLayout(new FlowLayout (FlowLayout.LEFT,150,10));
add(11); add(t1);
add(12);
add(12);
add(13);
add(t3);
add(b);
setSize (400,300);
setVisible(true);
}
public void keyPressed (KeyEvent ke)
{
int x, y, z;
x = Integer.parseInt(t1.getText());
y = Integer.parseInt(t2.getText()); if(ke.getKeyChar() == 'a')
z = x+y;
else if(ke.getKeyChar() == 's')
z=x-y;
else
{
t3.setText("Press a or s");
return;
}
t3.setText(String.valueOf(z));
}
public void keyTyped(KeyEvent ke)
{}
public void key Released(KeyEvent ke)
{}
public static void main(String a [])
{
new EventTest();
}
}
Comments
Post a Comment