Perdorimi i KeyListener
Shembull i menaxhimit te ngjarjeve: KeyListener
• Nderfaqja KeyListener
– Per ngjarjet qe ndodhin kur perdoruesi shtyp tastieren
• KeyListener permban tre metoda:
– keyPressed()
– keyTyped()
• percakton cili karakter eshte shtypur
• Mos ekzekutoni thirrjet nga butonat e veprimit
– keyReleased()
• ngjarja ndodh kur leshohet butoni.
– Klasa KeyEvent
– Permabn virtual key codes
• Perfaqeson butonat e tastieres qe jane shtypur
• Konstantet e butonave virtuale kane emra si VK_SHIFT dhe VK_ALT
Shembull:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class JDemoKeyFrame extends JFrame
implements KeyListener
{
private JLabel prompt = new JLabel("Type keys below:");
private JLabel outputLabel = new JLabel();
private JTextField textField = new JTextField(10);
public JDemoKeyFrame()
{
setTitle("JKey Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(prompt, BorderLayout.NORTH);
add(textField, BorderLayout.CENTER);
add(outputLabel, BorderLayout.SOUTH);
addKeyListener(this);
textField.addKeyListener(this);
}
public void keyTyped(KeyEvent e)
{
char c = e.getKeyChar();
outputLabel.setText("Last key typed: " + c);
}
public void keyPressed(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
public static void main(String[] args)
{
JDemoKeyFrame keyFrame = new JDemoKeyFrame();
final int WIDTH = 250;
final int HEIGHT = 100;
keyFrame.setSize(WIDTH, HEIGHT);
keyFrame.setVisible(true);
}
}