Program examples in Java KeyEvent

Senin, 19 Desember 2011

Here's an example Java program to demonstrate how the corresponding event handling button. The program will detect any keyboard key presses. Listener classes used are KeyListener which has 3 (three) keyTyped abstract method (), keyPressed () and keyReleased ().

The following looks:


contoh-program-key-event-java 

01import java.awt.*;
02import java.awt.event.*;
03import javax.swing.*;
04 
05public 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}
Semoga bermanfaat

0 komentar:

 
© Copyright 2010-2011 materials informatics All Rights Reserved.
Template Design by Moch Ramdhan | Published by Ramdhan Templates | Powered by Blogger.com.