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:
contoh-program-key-event-java Dan berikut ini program lengkapnya
contoh-program-key-event-java Dan berikut ini program lengkapnya
01 | import java.awt.*; |
02 | import java.awt.event.*; |
03 | import javax.swing.*; |
04 |
05 | public class KeyEventTest extends JFrame implements KeyListener { |
06 | private String baris1= "" , baris2= "" , baris3= "" ; |
07 | private JTextArea textArea; |
08 | |
09 | public KeyEventTest() { |
10 | super ( "Mencoba Key Event" ); |
11 | |
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); |
17 | |
18 | addKeyListener ( this ); |
19 | |
20 | setSize ( 300 , 150 ); |
21 | setLocationRelativeTo( null ); |
22 | setVisible( true ); |
23 | } |
24 | |
25 | public void keyPressed (KeyEvent e) { |
26 | baris1 = "Tombol yang ditekan : " + e.getKeyText(e.getKeyCode()); |
27 | setLines2and3 (e); |
28 | } |
29 | |
30 | public void keyReleased (KeyEvent e) { |
31 | baris1 = "Tombol yang dilepas : " + e.getKeyText(e.getKeyCode()); |
32 | setLines2and3 (e); |
33 | } |
34 | |
35 | public void keyTyped (KeyEvent e) { |
36 | baris1 = "Tombol yang ditulis : " + e.getKeyChar(); |
37 | setLines2and3 (e); |
38 | } |
39 | |
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" ); |
45 | } |
46 | |
47 | public static void main (String args[]) { |
48 | KeyEventTest test = new KeyEventTest(); |
49 | test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); |
50 | } |
51 | } |
No comments:
Post a Comment