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