Contoh Program KeyEvent di Java
Berikut ini contoh program Java untuk mendemonstrasikan bagaimana penanganan event terkait tombol. Program akan mendeteksi penekanan setiap tombol keyboard. Class Listener yang digunakan adalah KeyListener yang memiliki 3 (tiga) buah method abstract keyTyped(), keyPressed() dan keyReleased().
Berikut ini tampilannya:

Dan berikut ini program lengkapnya
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyEventTest extends JFrame implements KeyListener {
private String baris1="", baris2="", baris3="";
private JTextArea textArea;
public KeyEventTest() {
super ("Mencoba Key Event");
textArea = new JTextArea (10,15);
textArea.setText("Tekan sembarang tombol di keyboard...");
textArea.setEnabled(false);
textArea.setDisabledTextColor(Color.BLACK);
getContentPane().add(textArea);
addKeyListener (this);
setSize (300,150);
setLocationRelativeTo(null);
setVisible(true);
}
public void keyPressed (KeyEvent e) {
baris1 = "Tombol yang ditekan : " + e.getKeyText(e.getKeyCode());
setLines2and3 (e);
}
public void keyReleased (KeyEvent e) {
baris1 = "Tombol yang dilepas : " + e.getKeyText(e.getKeyCode());
setLines2and3 (e);
}
public void keyTyped (KeyEvent e) {
baris1 = "Tombol yang ditulis : " + e.getKeyChar();
setLines2and3 (e);
}
private void setLines2and3 (KeyEvent e) {
baris2 = "This key is "+ (e.isActionKey() ? "" : "not ") + "an action key";
String temp = e.getKeyModifiersText(e.getModifiers());
baris3 = "Modifier key pressed : " + (temp.equals("") ? "none" : temp);
textArea.setText(baris1 + "\n" + baris2 + "\n" + baris3 + "\n");
}
public static void main (String args[]) {
KeyEventTest test = new KeyEventTest();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Semoga bermanfaat
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.



Terima kasih, Pak.