Pages

Minggu, 23 September 2012

Contoh Event Handling di Java


Event Handling merupakan konsep penanganan suatu action yang terjadi. Jadi suatu program akan berjalan saat sesuatu terjadi, misalnya saat tombol diklik, saat combo box dipilih dan sebagainya. Java memiliki beberapa jenis Event Handling, salah satunya adalah class ActionListener yang menangani aksi terhadap tombol. Berikut ini contoh programnya:
Tampilan:
contoh-program-event-handling-java

Program:
01import java.awt.*;
02import java.awt.event.*;
03import javax.swing.*;
04 
05public class ClickMe extends JFrame implements ActionListener {
06    private JButton tombol;
07 
08    public ClickMe() {
09        super ("Event Handling");  
10 
11        Container container = getContentPane();
12        container.setLayout(new FlowLayout());     
13 
14        tombol = new JButton ("Click Me!");
15        tombol.addActionListener(this);
16        container.add(tombol);     
17 
18        setSize (200,100);
19        setVisible (true);
20    }
21 
22    public static void main (String arg[]) {
23        ClickMe test = new ClickMe();
24        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
25    }
26 
27    public void actionPerformed (ActionEvent e) {
28        if (e.getSource() == tombol) {
29            JOptionPane.showMessageDialog(null, "You click me, guys !!!");
30        }
31    }
32}
Selamat mencoba

Contoh Program Event Handling di Java (2)


Contoh program berikut ini pada dasarnya sama dengan contoh program sebelumnya. Hanya saja pada contoh kali ini, ditambahkan tombol Exit yang jika diklik program akan keluar.
Berikut ini tampilannya:

Berikut ini programnya:
01import java.awt.*;
02
03import java.awt.event.*;
04
05import javax.swing.*;
06
07public class ClickMe2 extends JFrame {
08
09    private JButton tombol, btnExit;
10
11    public ClickMe2() {
12
13        super ("Event Handling");
14
15        Container container = getContentPane();
16
17        container.setLayout(new FlowLayout());
18
19        ClickListener cl = new ClickListener ();
20
21        tombol = new JButton ("Click Me!");
22
23        tombol.addActionListener(cl);
24
25        container.add(tombol);
26
27        btnExit = new JButton ("Exit");
28
29        btnExit.addActionListener(cl);
30
31        container.add(btnExit);
32
33        setSize (200,100);
34
35        setVisible (true);
36
37    }
38
39    public static void main (String arg[]) {
40
41        ClickMe2 test = new ClickMe2();
42
43        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
44
45    }
46
47    //inner class
48
49    private class ClickListener implements ActionListener {
50
51        public void actionPerformed (ActionEvent e) {
52
53            if (e.getSource() == tombol) {
54
55                JOptionPane.showMessageDialog(null, "You click me again, guys !!!");
56
57            } else if (e.getSource() == btnExit){
58
59                JOptionPane.showMessageDialog(null, "See you, guys !");
60
61                System.exit(0);
62
63            }
64
65        }
66
67    }
68
69}
Selamat mencoba, semoga bermanfaat

Contoh Program Event Handling di Java (3)

Pada contoh berikut ini ditambahkan window konfirmasi saat tombol exit ditekan.
Berikut ini tampilannya:


Contoh program:
01import java.awt.*;
02
03import java.awt.event.*;
04
05import javax.swing.*;
06
07public class ClickMe3 extends JFrame {
08
09    private JButton tombol, btnExit;
10
11    public ClickMe3() {
12
13        super ("Event Handling");
14
15        Container container = getContentPane();
16
17        container.setLayout(new FlowLayout());
18
19        ClickListener cl = new ClickListener ();
20
21        tombol = new JButton ("Click Me!");
22
23        tombol.addActionListener(cl);
24
25        container.add(tombol);
26
27        btnExit = new JButton ("Exit");
28
29        btnExit.addActionListener(cl);
30
31        container.add(btnExit);
32
33        setSize (200,100);
34
35        setVisible (true);
36
37    }
38
39    public static void main (String arg[]) {
40
41        ClickMe3 test = new ClickMe3();
42
43        test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
44
45    }
46
47    //inner class
48
49    private class ClickListener implements ActionListener {
50
51        public void actionPerformed (ActionEvent e) {
52
53            if (e.getSource() == tombol) {
54
55                JOptionPane.showMessageDialog(null, "You click me again, guys !!!");
56
57            } else if (e.getSource() == btnExit){
58
59                if ( JOptionPane.showConfirmDialog(null, "Apakah Anda yakin akan keluar ?","Konfirmasi",
60
61                        JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION) {
62
63                        System.exit(0);
64
65                    }
66
67            }
68
69        }
70
71    }
72
73}
Semoga bermanfaat

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:
contoh-program-key-event-java

Dan berikut ini program lengkapnya
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

Window Event di Java

Contoh program berikut ini memberikan contoh bagaimana penanganan event di dalam window. Event akan aktif saat window diubah ukurannnya, diclose, aktif, dan sebagainya. Listener yang digunakan dalam contoh program ini adalah WindowListener, WindowFocusListener dan WindowStateListener.
Berikut ini tampilannya:
contoh-program-window-event-java

Berikut ini program lengkapnya:
001/*
002 * WindowEventDemo.java is a 1.4 example that requires
003 * no other files.
004 */
005
006import javax.swing.*;
007import java.awt.*;
008import java.awt.event.*;
009
010public class WindowEventDemo extends JPanel
011                             implements WindowListener,
012                                        WindowFocusListener,
013                                        WindowStateListener {
014    final static String newline = "\n";
015    final static String space = "    ";
016    static JFrame frame;
017    JTextArea display;
018
019    public WindowEventDemo() {
020        super(new BorderLayout());
021        display = new JTextArea();
022        display.setEditable(false);
023        JScrollPane scrollPane = new JScrollPane(display);
024        scrollPane.setPreferredSize(new Dimension(500, 450));
025        add(scrollPane, BorderLayout.CENTER);
026
027        frame.addWindowListener(this);
028        frame.addWindowFocusListener(this);
029        frame.addWindowStateListener(this);
030
031        checkWM();
032    }
033
034    //Some window managers don't support all window states.
035    //For example, dtwm doesn't support true maximization,
036    //but mimics it by resizing the window to be the size
037    //of the screen.  In this case the window does not fire
038    //the MAXIMIZED_ constants on the window's state listener.
039    //Microsoft Windows supports MAXIMIZED_BOTH, but not
040    //MAXIMIZED_VERT or MAXIMIZED_HORIZ.
041    public void checkWM() {
042        Toolkit tk = frame.getToolkit();
043        if (!(tk.isFrameStateSupported(Frame.ICONIFIED))) {
044            displayMessage(
045               "Your window manager doesn't support ICONIFIED.");
046        }
047        if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_VERT))) {
048            displayMessage(
049               "Your window manager doesn't support MAXIMIZED_VERT.");
050        }
051        if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_HORIZ))) {
052            displayMessage(
053               "Your window manager doesn't support MAXIMIZED_HORIZ.");
054        }
055        if (!(tk.isFrameStateSupported(Frame.MAXIMIZED_BOTH))) {
056            displayMessage(
057               "Your window manager doesn't support MAXIMIZED_BOTH.");
058        } else {
059            displayMessage(
060               "Your window manager supports MAXIMIZED_BOTH.");
061        }
062    }
063
064    public void windowClosing(WindowEvent e) {
065        displayMessage("WindowListener method called: windowClosing.");
066
067        //A pause so user can see the message before
068        //the window actually closes.
069        ActionListener task = new ActionListener() {
070            boolean alreadyDisposed = false;
071            public void actionPerformed(ActionEvent e) {
072                if (!alreadyDisposed) {
073                    alreadyDisposed = true;
074                    frame.dispose();
075                } else { //make sure the program exits
076                    System.exit(0);
077                }
078            }
079        };
080        Timer timer = new Timer(500, task); //fire every half second
081        timer.setInitialDelay(2000);        //first delay 2 seconds
082        timer.start();
083    }
084
085    public void windowClosed(WindowEvent e) {
086        //This will only be seen on standard output.
087        displayMessage("WindowListener method called: windowClosed.");
088    }
089
090    public void windowOpened(WindowEvent e) {
091        displayMessage("WindowListener method called: windowOpened.");
092    }
093
094    public void windowIconified(WindowEvent e) {
095        displayMessage("WindowListener method called: windowIconified.");
096    }
097
098    public void windowDeiconified(WindowEvent e) {
099        displayMessage("WindowListener method called: windowDeiconified.");
100    }
101
102    public void windowActivated(WindowEvent e) {
103        displayMessage("WindowListener method called: windowActivated.");
104    }
105
106    public void windowDeactivated(WindowEvent e) {
107        displayMessage("WindowListener method called: windowDeactivated.");
108    }
109
110    public void windowGainedFocus(WindowEvent e) {
111        displayMessage("WindowFocusListener method called: windowGainedFocus.");
112    }
113
114    public void windowLostFocus(WindowEvent e) {
115        displayMessage("WindowFocusListener method called: windowLostFocus.");
116    }
117
118    public void windowStateChanged(WindowEvent e) {
119        displayStateMessage(
120          "WindowStateListener method called: windowStateChanged.", e);
121    }
122
123    void displayMessage(String msg) {
124        display.append(msg + newline);
125        System.out.println(msg);
126    }
127
128    void displayStateMessage(String prefix, WindowEvent e) {
129        int state = e.getNewState();
130        int oldState = e.getOldState();
131        String msg = prefix
132                   + newline + space
133                   + "New state: "
134                   + convertStateToString(state)
135                   + newline + space
136                   + "Old state: "
137                   + convertStateToString(oldState);
138        display.append(msg + newline);
139        System.out.println(msg);
140    }
141
142    String convertStateToString(int state) {
143        if (state == Frame.NORMAL) {
144            return "NORMAL";
145        }
146        if ((state & Frame.ICONIFIED) != 0) {
147            return "ICONIFIED";
148        }
149        //MAXIMIZED_BOTH is a concatenation of two bits, so
150        //we need to test for an exact match.
151        if ((state & Frame.MAXIMIZED_BOTH) == Frame.MAXIMIZED_BOTH) {
152            return "MAXIMIZED_BOTH";
153        }
154        if ((state & Frame.MAXIMIZED_VERT) != 0) {
155            return "MAXIMIZED_VERT";
156        }
157        if ((state & Frame.MAXIMIZED_HORIZ) != 0) {
158            return "MAXIMIZED_HORIZ";
159        }
160        return "UNKNOWN";
161    }
162
163    /**
164     * Create the GUI and show it.  For thread safety,
165     * this method should be invoked from the
166     * event-dispatching thread.
167     */
168    private static void createAndShowGUI() {
169        //Make sure we have nice window decorations.
170        JFrame.setDefaultLookAndFeelDecorated(true);
171
172        //Create and set up the window.
173        frame = new JFrame("WindowEventDemo");
174        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
175
176        //Create and set up the content pane.
177        JComponent newContentPane = new WindowEventDemo();
178        newContentPane.setOpaque(true); //content panes must be opaque
179        frame.setContentPane(newContentPane);
180
181        //Display the window.
182        frame.pack();
183        frame.setVisible(true);
184    }
185
186    public static void main(String[] args) {
187        //Schedule a job for the event-dispatching thread:
188        //creating and showing this application's GUI.
189        javax.swing.SwingUtilities.invokeLater(new Runnable() {
190            public void run() {
191                createAndShowGUI();
192            }
193        });
194    }
195}
Semoga bermanfaat