Posted by zonefreeze
On
- -
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
02 | import java.awt.event.*; |
05 | public class KeyEventTest extends JFrame implements KeyListener { |
06 | private String baris1= "" , baris2= "" , baris3= "" ; |
07 | private JTextArea textArea; |
09 | public KeyEventTest() { |
10 | super ( "Mencoba Key Event" ); |
12 | textArea = new JTextArea ( 10 , 15 ); |
13 | textArea.setText( "Tekan sembarang tombol di keyboard..." ); |
14 | textArea.setEnabled( false ); |
15 | textArea.setDisabledTextColor(Color.BLACK); |
16 | getContentPane().add(textArea); |
18 | addKeyListener ( this ); |
21 | setLocationRelativeTo( null ); |
25 | public void keyPressed (KeyEvent e) { |
26 | baris1 = "Tombol yang ditekan : " + e.getKeyText(e.getKeyCode()); |
30 | public void keyReleased (KeyEvent e) { |
31 | baris1 = "Tombol yang dilepas : " + e.getKeyText(e.getKeyCode()); |
35 | public void keyTyped (KeyEvent e) { |
36 | baris1 = "Tombol yang ditulis : " + e.getKeyChar(); |
40 | private void setLines2and3 (KeyEvent e) { |
41 | baris2 = "This key is " + (e.isActionKey() ? "" : "not " ) + "an action key" ; |
42 | String temp = e.getKeyModifiersText(e.getModifiers()); |
43 | baris3 = "Modifier key pressed : " + (temp.equals( "" ) ? "none" : temp); |
44 | textArea.setText(baris1 + "\n" + baris2 + "\n" + baris3 + "\n" ); |
47 | public static void main (String args[]) { |
48 | KeyEventTest test = new KeyEventTest(); |
49 | test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); |
Semoga bermanfaat