291_diktat kuliah oopl
TRANSCRIPT
Pengajar:
Niko Ibrahim, S.Kom, MIT
ii
Daftar Isi
Daftar Isi ........................................................................................................................................................ ii
Daftar Program ........................................................................................................................................... vii
Daftar Gambar ........................................................................................................................................... viii
Pendahuluan ................................................................................................................................................. 1
Tujuan Perkuliahan ................................................................................................................................... 1
Peraturan Perkuliahan .............................................................................................................................. 1
Pedoman Penilaian ................................................................................................................................... 1
Materi Keseluruhan .................................................................................................................................. 1
Point-point penilaian ................................................................................................................................ 2
Reading Materials ..................................................................................................................................... 2
Softwares and Tools .................................................................................................................................. 2
Tentang Praktikum .................................................................................................................................... 3
Cara menghubungi dosen ......................................................................................................................... 3
Teknik Belajar ............................................................................................................................................ 3
Pengertian 4 SKS untuk Pemrograman Berorientasi Objek ...................................................................... 3
Bab 1 Pengenalan Aplikasi Dekstop Berbasis Java ........................................................................................ 5
1.1. Komponen ..................................................................................................................................... 5
1.2. Layout ............................................................................................................................................ 5
1.3. Event Handling .............................................................................................................................. 6
Bab 2 Pengenalan JavaSwing ........................................................................................................................ 7
Bab 3 Komponen-komponen Swing .............................................................................................................. 8
3.1. JLabel ............................................................................................................................................. 8
3.2. JButton .......................................................................................................................................... 9
3.2.1. Memberikan Gambar pada Button & Label .......................................................................... 9
iii
3.2.2. Memberikan Teks HTML pada Label & Button ..................................................................... 9
3.3. JFrame ........................................................................................................................................... 9
3.4. JPanel .......................................................................................................................................... 11
3.5. JCheckbox & JRadioButton ......................................................................................................... 11
3.6. JList .............................................................................................................................................. 14
3.7. JComboBox .................................................................................................................................. 14
3.8. JSpinner ....................................................................................................................................... 16
3.9. Border ......................................................................................................................................... 18
3.10. JMenu ...................................................................................................................................... 21
Menggunakan Keyboard Access ( Alt & Ctrl) pada Menu ................................................................... 22
3.11. JPopupMenu ........................................................................................................................... 25
3.12. JScrollPane .............................................................................................................................. 27
3.13. JSplitPane ................................................................................................................................ 29
3.14. JTabbedPane ........................................................................................................................... 30
3.15. JOptionPane (Message Dialog) ............................................................................................... 32
3.16. JScrollbar & JSlider .................................................................................................................. 34
3.17. JDesktopPane & JInternalFrame ............................................................................................. 36
Bab 4 Layout Manager ................................................................................................................................ 38
4.1. FlowLayout .................................................................................................................................. 39
4.2. GridLayout ................................................................................................................................... 41
4.3. BorderLayout .............................................................................................................................. 43
4.4. BoxLayout .................................................................................................................................... 45
4.5. CardLayout .................................................................................................................................. 47
4.6. GridBagLayout ............................................................................................................................. 49
4.7. GroupLayout ............................................................................................................................... 51
Bab 5 Event-driven Programming ............................................................................................................... 55
iv
Event Handling and Listener ................................................................................................................... 55
Teknik 1: Menjadikan JFrame utama sebagai implementasi dari Listener ............................................. 58
Teknik 2: Menggunakan Inner Class ....................................................................................................... 60
Teknik 3: Penggunaan Anonymous Inner Class untuk menangani Event ............................................... 62
Teknik Penanganan Komponen Input ..................................................................................................... 64
Komponen Input 1: JTextField ............................................................................................................ 64
Komponen Input 2: RadioButton & CheckBox .................................................................................... 65
Komponen Input 3: JScrollBar & JSlider .................................................................................................. 66
Bab 6 Integrated Development Environment (IDE) .................................................................................... 68
Pengenalan NetBeans IDE ....................................................................................................................... 68
Tutorial 1: Pengembangan aplikasi GUI Dasar ........................................................................................ 69
Bab 7 Pengembangan GUI Lanjutan Menggunakan NetBeans ................................................................... 85
Bab 8 Java Database Connectivity (JDBC) ................................................................................................. 102
1. Memanggil Driver JDBC ................................................................................................................. 103
2. Mendefinisikan URL dan Melakukan Koneksi ............................................................................... 104
3. Membuat Objek Statement .......................................................................................................... 104
4. Mengeksekusi Query Untuk Statement Select ............................................................................. 105
5. Memproses Hasil........................................................................................................................... 106
6. Memproses Query Untuk Statement Update/Insert/Delete ........................................................ 107
7. Menutup Koneksi .......................................................................................................................... 107
Peringatan Untuk Pengguna JDBC ........................................................................................................ 111
Bab 9 Java Persistence API (JPA) ............................................................................................................... 112
JDBC ...................................................................................................................................................... 113
Enterprise JavaBeans (EJB)........................................................................................................................ 113
Java Data Objects (JDO) ........................................................................................................................ 113
Java Persistence API .............................................................................................................................. 113
v
Annotations (@) .................................................................................................................................... 114
Mapping Java class menjadi Entity class ............................................................................................... 115
Anotating Employee Class ..................................................................................................................... 116
Entity Manager...................................................................................................................................... 117
How does Entity Manager works? ........................................................................................................ 117
Obtaining an Entity Manager ................................................................................................................ 117
Operation on Entity ............................................................................................................................... 118
Persisting an Entity (INSERT) ................................................................................................................. 118
Finding an Entity ................................................................................................................................... 118
Removing an Entity ............................................................................................................................... 119
Updating an Entity ................................................................................................................................ 119
Transactions .......................................................................................................................................... 120
Queries .................................................................................................................................................. 120
Referensi Bahasa Pemrograman Java ....................................................................................................... 125
Tipe Data Primitif .................................................................................................................................. 125
Operator Aritmatika .............................................................................................................................. 125
Karakter Khusus .................................................................................................................................... 125
Assignment Operators .......................................................................................................................... 126
Ekspresi Boolean ................................................................................................................................... 126
Operator AND dan OR ........................................................................................................................... 126
String ..................................................................................................................................................... 126
Variabel & Assignment .......................................................................................................................... 127
Method print, println,dan printf ........................................................................................................... 127
Using Console for Input & Output ........................................................................................................ 127
Struktur Kontrol Selection..................................................................................................................... 128
Struktur Kontrol Loop ........................................................................................................................... 129
vi
Array ...................................................................................................................................................... 129
Exception Handling ............................................................................................................................... 132
Handling Exception: Try-Catch .............................................................................................................. 132
Catching All Exceptions ......................................................................................................................... 133
Finally .................................................................................................................................................... 134
Konsep Dasar Pemrograman Berorientasi Objek ..................................................................................... 135
CLASS & OBJECT .................................................................................................................................... 135
Membuat CLASS REKENING .................................................................................................................. 135
Membuat OBJECT myRekening: new .................................................................................................... 135
Method ................................................................................................................................................. 136
CONSTRUCTOR ...................................................................................................................................... 136
SET dan GET methods ........................................................................................................................... 136
Access Modifier ..................................................................................................................................... 137
Konsep Inheritance ............................................................................................................................... 137
Abstract Class ........................................................................................................................................ 138
Konsep Polymorphism .......................................................................................................................... 139
Interface ................................................................................................................................................ 140
vii
Daftar Program
Program 1: Implementasi JFrame - HelloFrame.java .................................................................................. 10
Program 2: Implementasi JCheckbox & JRadioButton - PesanMakanan.java ............................................ 13
Program 3: Implementasi JList & JComboBox - DayLister.java ................................................................... 15
Program 4: Implementasi JSpinner – SpinnerList.java ................................................................................ 17
Program 5: Implementasi Border - BorderTest.java ................................................................................... 20
Program 6: Implementasi JMenu & JMenuBar – DinnerMenu.java ........................................................... 24
Program 7: Impelementasi JPopupMenu – ContextMenu.java .................................................................. 26
Program 8: Implementasi JScrollPane – ScrollPaneFrame.java .................................................................. 28
Program 9: Implementasi JSplitPane – SplitPaneFrame.java ..................................................................... 29
Program 10: Implementasi JTabbedPane – TabbedPaneFrame.java ......................................................... 31
Program 11 – Implementasi JOptionPane – ExerciseOptions.java ............................................................. 33
Program 12: Implementasi JScrollbar & JSlider – Slippery.java .................................................................. 35
Program 13 – Implementasi JDesktopPane & JInternalFrame – Desktop.java ........................................... 36
Program 14: Implementasi FlowLayout – Flow.java ................................................................................... 40
Program 15: Implementasi GridLayout – Grid.java .................................................................................... 42
Program 16: Implementasi BorderLayout – BorderLayoutApp1.java ......................................................... 43
Program 17: Implementasi BorderLayout dengan menggunakan Panel – BorderLayoutApp2.java .......... 45
Program 18: Implementasi BoxLayout – Boxer.java ................................................................................... 47
Program 19: Implementasi CardLayout – Card.java ................................................................................... 48
Program 20: Implementasi GridBagLayout dengan constraint gridx dan gridy – GridBag1.java ............... 50
Program 21: Implementasi GroupLayout – Group.java .............................................................................. 53
Program 22: Implementasi Event-Handling Cara 1: ClickMe.java .............................................................. 59
Program 23: Implementasi Event-Handling Cara 2: ClickMe2.java ............................................................ 61
Program 24: Implementasi Event handling cara 3: ClickMe3.java ............................................................. 63
Program 25: Pengaksesan database menggunakan JDBC – ListMovies.java ............................................ 110
Program 26: POJO Class Employee – Employee.java ................................................................................ 115
Program 27: Entity Class Employee – Employee.java ............................................................................... 116
Program 28: Method-method Pengelolaan Employee menggunakan JPA - EmployeeService.java ........ 122
Program 29: Aplikasi Utama Pengelolaan Employee - EmployeeTest.java .............................................. 123
viii
Daftar Gambar
Gambar 1: Contoh Komponen GUI ............................................................................................................... 5
Gambar 2: Penggunaan Layout Manager ..................................................................................................... 6
Gambar 3: Swing dibangun di atas AWT ....................................................................................................... 7
Gambar 4: Hubungan komponen Swing dan AWT ....................................................................................... 7
Gambar 5: Hello World Frame .................................................................................................................... 10
Gambar 6: Hello World Frame berisi Label, Button, & ImageIcon ............................................................. 10
Gambar 7: JFrame berisi JButton dengan teks HTML ................................................................................. 11
Gambar 8: Tampilan PesanMakanan.java .................................................................................................. 14
Gambar 9: Tampilan dari DayLister.java ..................................................................................................... 16
Gambar 10: Tampilan dari SpinnerList.java ................................................................................................ 17
Gambar 11: Tampilan BorderTest.java ....................................................................................................... 21
Gambar 12: MenuBar, Menu, & MenuItem ............................................................................................... 22
Gambar 13: Tampilan DinnerMenu.java ..................................................................................................... 25
Gambar 14: Tampilan ContextMenu.java ................................................................................................... 27
Gambar 15: Tampilan ScrollPaneFrame.java .............................................................................................. 28
Gambar 16: Tampilan SplitPaneFrame.java ................................................................................................ 30
Gambar 17: Tampilan TabbedPaneFrame.java ........................................................................................... 32
Gambar 18: Tampilan ExerciseOptions.java ............................................................................................... 34
Gambar 19: Tampilan Slippery.java ............................................................................................................ 36
Gambar 20: Tampilan Dektop.java ............................................................................................................. 37
Gambar 21: Class LayoutManager .............................................................................................................. 38
Gambar 22: Tampilan Flow.java ................................................................................................................. 40
Gambar 23: Tampilan Grid.java .................................................................................................................. 42
Gambar 24: Tampilan BorderLayoutApp1.java........................................................................................... 44
Gambar 25: Tampilan BorderLayoutApp2.java........................................................................................... 45
Gambar 26: Tampilan Boxer.java ................................................................................................................ 47
Gambar 27: Tampilan Card.java .................................................................................................................. 48
Gambar 28: Tampilan GridBag1.java .......................................................................................................... 50
Gambar 29: Implementasi sequential group secara horisonal dan paralel group secara vertikal ............. 51
ix
Gambar 30: Implementasi paralel group sepanjang horisonal dan sequential group sepanjang vertikal . 51
Gambar 31: Implementasi sequential group untuk pada kedua sumbu horisonal dan vertikal ................ 52
Gambar 32: Tampilan Group.java ............................................................................................................... 54
Gambar 33: Tampilan ClickMe.java ............................................................................................................ 60
Gambar 34: Tampilan ClickMe2.java .......................................................................................................... 61
Gambar 35: Tampilan ClickMe3.java .......................................................................................................... 63
Gambar 36: Contoh mengambil input dari JTextField dan menampilkannya di JOptionPane ................... 64
Gambar 37: Mengambil input dari RadioButton/CheckBox dan menampilkannya di JOptionPane .......... 65
Gambar 37: Mengambil input dari JScrollBar dan JSlider ........................................................................... 66
Gambar 38: Tampilan Texter.java ............................................................................................................... 67
Pendahuluan Page | 1
Pendahuluan
Tujuan Perkuliahan
1. Mahasiswa mampu membuat program aplikasi Java berdasarkan konsep berorientasi objek
2. Mahasiwa mampu membuat program aplikasi yang berhubungan dengan database.
3. Mahasiswa memahami konsep-konsep lanjutan dalam pemrograman berorientasi objek.
Peraturan Perkuliahan
a) Pedoman Perkuliahan
1. Titip absen E
2. Handphone wajib di-nonaktifkan/silent
3. Menggunakan pakaian rapi & bersepatu
b) Kewajiban hadir
1. Kehadiran > 15 menit, tidak boleh masuk kelas
2. 75% kehadiran dosen (Tidak hadir > 25% berarti cekal)
3. Bila kena cekal, tidak diijinkan ikut UAS E
Pedoman Penilaian
a) Nilai Akhir = 30% UTS + 30% UAS + 10% Quiz + 30% Praktikum & Project
b) Pedoman Penghitungan nilai:
1. A: 80 <= NA <= 100
2. B+: 73 <= NA < 80
3. B: 67 <= NA < 73
4. C+: 61 <= NA < 67
5. C: 55 <= NA < 61
6. D: 41 <= NA < 55
7. E: NA <41
Materi Keseluruhan
a) Java Swing
1. Komponen-komponen Swing
Pendahuluan Page | 2
2. Layout Manager
b) Event-driven programming
c) Thread & Concurrent programming
d) Database access and processing
Point-point penilaian
No Details about each form of
assessable work in the topic Amount
Proportion
of total mark
Penalties to be applied
for plagiarism / late
works
1 Bi-weekly lab exercises
programming tasks
10 20% Mark = 0, for all practical
works
2 Group Project 1 10% Mark = 0
3 Quizzes 5 10% Mark = 0, for all quizzes
4 Mid-semester Exam 1 25% Mark = 0, for all exams
5 Final-semester Exam 1 25% Mark = 0, for all exams
Reading Materials
a) JFC Swing Tutorial, A Guide to Constructing GUIs, 2nd Ed., Kathy Walrath, Mary Campione,
Alison Huml, Sharon Zakhour
b) Learning Java, Jonathan Knudsen & Patrick Niemeyer, O’Reilly, 2005.
c) Java Swing, Matthew Robinson & Pavel Vorobiev, Manning, 2005.
d) Java 6 API Documentation, Sun Microsystems
e) NetBeans 6 Tutorials and Documentations
Softwares and Tools
a) OS: Windows 98, XP, 2000, 2003, Vista, Linux, Mac OS, Unix, Solaris
b) JDK 1.6 + Java API Documentation
c) Editors:
1. JGrasp (Simple Java editor, free download)
2. NetBeans 6.0 (Java IDE, Open Source, free download)
3. Others:
Notepad, EditPlus, TextPad, UltraEdit, dll
Pendahuluan Page | 3
BlueJ, JCreator, DrJava
IntelliJ IDEA 6, IBM Eclipse 3, Borland Jbuilder 2007, Oracle JDeveloper, dll
( Available in almost all IT Labs )
Tentang Praktikum
a) Total Praktikum 10 problem sets
b) Pelajari dan ikuti petunjuk yang disediakan dalam setiap problem sets tersebut
c) Setiap problem sets harus diselesaikan dalam waktu maksimal 14 hari dan tidak ada waktu
perpanjangan
d) Untuk penyelesaian tugas praktikum sebaiknya dikerjakan di rumah
e) Pertemuan praktikum di lab sebaiknya digunakan sebagai help session (tanya jawab), bukan
untuk mengerjakan tugas karena tidak akan ada cukup waktu
Cara menghubungi dosen
a) Ask directly after the class! (preferable)
b) Email me at: [email protected]
c) Walk in to: Ruang Kajur SI
d) Phone/sms is not recommended
Teknik Belajar
a) Baca dan pelajari materi kuliah pada diktat minimal sehari sebelum perkuliahan dimulai
b) Pada setiap slide, tertera nomor bab/referensi pada textbook yang digunakan. Baca bab
tersebut agar lebih paham
c) Diskusi berpasangan dalam menganalisa soal praktikum. Lalu, kerjakan soal praktikum sebisa
mungkin sendiri-sendiri.
d) Jangan ragu untuk bertanya pada asisten atau dosen
e) NO DUMB QUESTIONS!
Pengertian 4 SKS untuk Pemrograman Berorientasi Objek
4 SKS dibagi menjadi 2 bagian, yaitu
a) 3 SKS Teori, berarti untuk setiap minggu, mahasiswa wajib melaksanakan:
1. 3 jam perkuliahan di kelas sesuai jadwal
Pendahuluan Page | 4
2. 3 jam kegiatan berstruktur di bawah bimbingan dosen, misal: diskusi, pekerjaan rumah, &
membuat makalah
3. 3 jam kegiatan mandiri mahasiswa, misal: membaca buku, latihan programming, &
diskusi/belajar kelompok
b) 1 SKS Praktikum, berarti untuk setiap minggu, mahasiswa wajib melaksanakan:
2-4 jam mengerjakan praktikum termasuk membuat laporan apabila diperlukan
Bab 1 Pengenalan Aplikasi Desktop Berbasis Java Page | 5
Bab 1 Pengenalan Aplikasi Dekstop Berbasis Java
Ada 3 hal penting dalam pemrograman GUI berbasis Java dalam membuat aplikasi dekstop:
1. Elemen-elemen (components) apa yang bisa ditampilkan di layar?
2. Bagaimana cara kira menyusun dan menempatkan elemen-elemen tersebut?
3. Bagaimana kita berinteraksi dengan elemen-elemen tersebut?
1.1. Komponen
Components merupakan bagian dari GUI, seperti buttons, menus, checkboxes, sliders, text fields, labels,
dll. Java API menyediakan banyak sekali komponen-komponen ini (lihat javadocs API 1.6). Selain
komponen built-in yang telah disediakan, kita juga dapat membuat komponen sendiri.
Berikut contoh penggunaan komponen di dalam sebuah aplikasi desktop sederhana:
Gambar 1: Contoh Komponen GUI
1.2. Layout
Layout merupakan cara penyusunan komponen di dalam sebuah container. Pada dasarnya ada 2
teknik layout:
1. Absolut: berdasarkan koordinat x,y (jarang digunakan karena tidak fleksibel)
2. Relatif terhadap komponen lain (dalam hal posisi, ukuran, resolusi layar, font yang digunakan, dll).
Untuk menentukan layout, kita harus menggunakan objek Layout Manager yang berfungsi mengatur
posisi dan ukuran setiap komponen yang digunakan, seperti yang ditunjukkan gambar berikut:
Bab 1 Pengenalan Aplikasi Desktop Berbasis Java Page | 6
Gambar 2: Penggunaan Layout Manager
1.3. Event Handling
Event handling merupakan teknik penanganan input dari user yang diberikan kepada komponen GUI.
Berikut ini adalah cara kerja dari event-handling dengan contoh penekanan sebuah komponen tombol:
Bab 2 Pengenalan Java Swing Page | 7
Bab 2 Pengenalan JavaSwing
Untuk membuat aplikasi desktop, Java 1.6 menyediakan 2 libraries:
1. AWT (Abstract Window Toolkit), dan
2. Swing
Tabel berikut ini memperlihatkan perbedaan antara AWT dan Swing
AWT Swing
heavyweight: bergantung pada platform (sistem operasi)
lightweight: tidak bergantung pada sistem operasi
difficult to port, platform-dependant look pluggable look and feel, programmer designed look
library generasi pertama untuk GUI berbasis Java, masih menggunakan libary dari sistem operasi
murni berbasis Java, generasi kedua, komponen diawali dengan huruf ‘J’
Java Swing sebenarnya dibangun di atas library AWT seperti digambarkan sebagai berikut:
Gambar 3: Swing dibangun di atas AWT
Setiap komponen Swing dibangun berdasarkan komponen AWT yang bersesuaian seperti gambar
berikut:
Gambar 4: Hubungan komponen Swing dan AWT
Pada prakteknya, gunakanlah library Swing dalam membuat aplikasi desktop dan hindarilah
penggunakan library Swing bersamaan dengan AWT.
Bab 3 Komponen-komponen Swing Page | 8
Bab 3 Komponen-komponen Swing
Berikut ini adalah komponen-komponen Swing yang dapat digunakan untuk membangun tampilan GUI:
1. JLabel
2. JButton
3. JFrame
4. JPanel
5. JCheckbox
6. JRadioButton
7. JList
8. JComboBox
9. JSpinner
10. JBorder
11. JMenu
12. JPopupMenu
13. JScrollPane & JSplitPane
14. JTabbedPane
15. JOptionPane
16. JScrollbar & JSlider
17. JdesktopPane & JInternalFrame
3.1. JLabel
Label biasa digunakan untuk:
Menampilkan judul (caption) dari komponen lagin seperti textfield atau combo box
Menampilkan pesan/informasi
Menampilkan hasil penghitungan atau pencarian basis data
Menampilkan gambar
Kita dapat menentukan jenis huruf, ukuran, style (bold, italic, underline) dan warna dari label tersebut.
Contoh membuat label:
JLabel judul = new JLabel();
judul.setText("Hello, World!");
atau
JLabel judul = new JLabel("Hello, World!");
Bab 3 Komponen-komponen Swing Page | 9
3.2. JButton
Button merupakan komponen yang dapat di-klik untuk melakukan konfirmasi sesuatu.
Contoh membuat button:
JButton tombolOK = new JButton();
tombolOK.setText("Click me!");
atau
JButton tombolOK = new JButton("Click me!");
3.2.1. Memberikan Gambar pada Button & Label
Kita dapat menambahkan sebuah gambar kepada JLabel dan JButton dengan cara membuat dan
men-set objek ImageIcon pada label dan button tsb.
Contoh membuat label bergambar:
ImageIcon gambarUang = new ImageIcon("uang.png");
JLabel labelJudul = new JLabel(gambarUang);
labelJudul.setText("Sistem Administrasi Keuangan");
Contoh membuat button bergambar:
JButton okButton = new JButton("OK DECH");
okButton.setIcon(new ImageIcon("ok.png"));
3.2.2. Memberikan Teks HTML pada Label & Button
Salah satu feature Swing adalah dapat menginterpretasi teks HTML di dalam JLabel dan JButton
Contoh:
JButton htmlButton = new JButton(
"<html>S<font size=-2>MALL<font size=+0> "
+"C<font size=-2>APITALS");
String htmlTable= "<html><table border=1>"
+"<tr><td>One</td><td>Two</td></tr>"
+"<tr><td>Three</td><td>Four</td></tr>"
+"</table>";
JButton htmlButton2 = new JButton(htmlTable);
3.3. JFrame
JFrame merupakan komponen top-level bagi aplikasi desktop. Frame berfungsi sebagai penampung
komponen-komponen lainnya.
Contoh:
JFrame frameUtama = new JFrame();
frameUtama.setTitle("Menu Utama");
Kita dapat membuat sebuah class baru yang memiliki sifat-sifat JFrame dengan cara melakukan proses
Bab 3 Komponen-komponen Swing Page | 10
inheritance (extends).
Berikut ini contoh program yang menampilkan sebuah frame dengan tulisan “Hello, World!”
Contoh Program 1: HelloFrame.java
Program 1: Implementasi JFrame - HelloFrame.java
Berikut hasil dari program HelloFrame.java:
Gambar 5: Hello World Frame
Latihan 1:
Modifikasi program HelloFrame.java tersebut sedemikian rupa sehingga Label dan Button memiliki
Image seperti ditunjukkan gambar berikut:
Gambar 6: Hello World Frame berisi Label, Button, & ImageIcon
import javax.swing.*;
public class HelloFrame extends JFrame {
public HelloFrame() {
this.setSize(200,100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Hello World!");
this.setVisible(true);
}
public static void main(String[] args) {
/* Creates a new instance of HelloFrame */
new HelloFrame();
}
}
Bab 3 Komponen-komponen Swing Page | 11
Latihan 2:
Buatlah sebuah JFrame yang mengandung 2 buah objek JButton yang berisi teks HTML sbb:
Gambar 7: JFrame berisi JButton dengan teks HTML
3.4. JPanel
Panel adalah suatu container yang dirancang untuk menampung sekumpulan komponen sedemikian
rupa sehingga kumpulan tersebut dapat ditampilkan bersama-sama di dalam sebuah frame.
Cara yang lazim dilakukan dalam menampilkan sekumpulan komponen kontrol seperti text field, label,
dan button adalah dengan menambahkan komponen-komponen tersebut ke dalam sebuah panel,
kemudian panel tersebut ditambahkan ke dalam sebuah frame.
Contoh membuat panel:
class HelloPanel extends JPanel{
public HelloPanel(){
// buat dan tambahkan beberapa komponen:
JTextField input = new JTextField();
JButton tombol = new JButton();
this.add(input);
this.add(tombol);
}
}
Kemudian, di dalam constructor class frame, kita buat objek panel tersebut dan tambahkan ke dalam
frame tersebut:
this.add(new HelloPanel());
3.5. JCheckbox & JRadioButton
Checkbox adalah toggle switch yang diberi label. Setiap kali kita menekan checkbox, maka statusnya
akan berganti antara checked dan unchecked. Swing mengimplementasikan checkbox sebagai jenis
khusus dari button.
Contoh membuat checkbox:
JCheckBox cbox1 = new JCheckBox("Sambal");
JCheckBox cbox2 = new JCheckBox("Saus Tomat");
JCheckBox cbox3 = new JCheckBox("Salad");
Bab 3 Komponen-komponen Swing Page | 12
Radiobutton hampir menyerupai checkbox, tetapi penggunaannya haruslah secara berkompok.
Apabila kita menekan salah satu radio button di dalam suatu kelompok, maka secara otomatis akan
menonaktifkan radio button yang lain.
Radio button dapat dikelompokkan bersama dengan menggunakan objek dari class ButtonGroup.
Contoh membuat dan mengelompokkan radio button:
ButtonGroup makananGroup = new ButtonGroup( );
JRadioButton rb1 = new JRadioButton("Sapi");
JRadioButton rb2 = new JRadioButton("Ayam");
JRadioButton rb3 = new JRadioButton("Sayuran", true);
makananGroup.add(rb1);
makananGroup.add(rb2);
makananGroup.add(rb3);
Bab 3 Komponen-komponen Swing Page | 13
Contoh Program 2: PesanMakanan.java
Program 2: Implementasi JCheckbox & JRadioButton - PesanMakanan.java
import java.awt.*; // library yang mencakup FlowLayout
import javax.swing.*;
public class PesanMakanan extends JFrame{
public PesanMakanan() {
this.setSize(300,200);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setTitle("Pesan Makanan!");
this.setVisible(true);
this.setLocationRelativeTo(null); // set location to the center
// PANEL 1: berisi 3 buah checkboxes
JCheckBox cbox1 = new JCheckBox("Sambal");
JCheckBox cbox2 = new JCheckBox("Saus Tomat");
JCheckBox cbox3 = new JCheckBox("Black Peper");
JPanel panelBumbu = new JPanel();
panelBumbu.add(cbox1);
panelBumbu.add(cbox2);
panelBumbu.add(cbox3);
this.add(panelBumbu);
// PANEL 2: berisi 3 buah Radio Button
JRadioButton rb1 = new JRadioButton("Sapi");
JRadioButton rb2 = new JRadioButton("Ayam");
JRadioButton rb3 = new JRadioButton("Sayuran", true);
ButtonGroup entreeGroup = new ButtonGroup( );
entreeGroup.add(rb1);
entreeGroup.add(rb2);
entreeGroup.add(rb3);
JPanel panelMakanan = new JPanel();
panelMakanan.add(rb1);
panelMakanan.add(rb2);
panelMakanan.add(rb3);
this.add(panelMakanan);
// PANEL 3: berisi 1 buah Button
JButton orderButton = new JButton("Place Order");
JPanel panelButton = new JPanel();
panelButton.add(orderButton);
this.add(panelButton);
this.setLayout(new FlowLayout());
this.setVisible(true);
}
public static void main (String[] args){
new PesanMakanan();
}
}
Bab 3 Komponen-komponen Swing Page | 14
Berikut hasil dari PesanMakan.java:
Gambar 8: Tampilan PesanMakanan.java
3.6. JList
Dengan menggunakan List kita dapat memilih dari sekumpulan pilihan. List dapat dikonfigurasi
sedemikian rupa sehingga kita hanya dapat memilih satu pilihan atau dapat memilih beberapa pilihan
sekaligus. Untuk memilih item di dalam List, kita dapat menggunakan kombinasi tombol mouse
dengan tombol Control atau Shift pada keyboard.
Contoh membuat List:
String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
JList list = new JList(days);
3.7. JComboBox
Combo box merupakan campuran antara text field dengan list. Combo box hanya menampilkan satu
baris teks yang disertai tombol bertanda panah.
Apabila kita menekan tombol panah tersebut, combo box akan membuka dan menampilkan daftar
pilihan. Kita dapat memilih satu pilihan dengan cara menekan pilihan yang diinginkan.
Setelah pilihan dibuat, combo box akan kembali menutup, daftar pilihan akan menghilang, dan pilihan
yang baru akan ditampilkan di dalam text field.
List dan Combo box memiliki kemiripan yaitu memiliki data model yang sama. Keduanya dapat
menampung data model berupa sebuah array.
Contoh membuat Combo box:
String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
JComboBox jcb = new JComboBox(days);
Bab 3 Komponen-komponen Swing Page | 15
Contoh Program 3: DayLister.java
Program 3: Implementasi JList & JComboBox - DayLister.java
import java.awt.*;
import javax.swing.*;
public class DaysLister extends JFrame{
public DaysLister(){
this.setSize(300,400);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setTitle("^_^ Days Lister ^_^");
this.setLocationRelativeTo(null);
this.setLayout(null);
// Buat sebuah array:
String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
// Buat sebuah objek JPanel:
JPanel mainPanel = new JPanel();
mainPanel.setBounds(0,220,100,300);
// Buat sebuah objek JComboBox
JComboBox jcb = new JComboBox(days);
jcb.setEditable(true);
jcb.setBounds(20,20,150,30);
this.add(jcb);
// Buat sebuah objek JList
JList list = new JList(days);
list.setBounds(20,60,130,150);
this.add(list);
// Buat sebuah objek JButton
JButton okButton = new JButton("OK");
this.add(okButton);
okButton.setBounds(0,50,120,100);
mainPanel.add(okButton);
this.add(mainPanel);
this.setVisible(true);
}
public static void main(String[] args){
new DaysLister();
}
}
Bab 3 Komponen-komponen Swing Page | 16
Berikut tampilan dari DayLister.java
Gambar 9: Tampilan dari DayLister.java
3.8. JSpinner
Spinner sangat berguna untuk menampilkan sebuah nilai sequence (urutan) seperti angka atau tanggal.
Spinner memiliki kemiripan dengan Combo box karena menampilan sebuah nilai dalam suatu text field.
Namun, spinner tidak menampilkan daftar pilihan melainkan memberikan sepasang tombol panah
(atas-bawah) untuk mengubah nilai yang tertera di dalam text field.
Sama seperti combo box, spinner juga dapat dibuat menjadi editable, sehingga kita dapat secara
langsung mengetikan nilai di dalam field-nya.
Swing menyediakan 3 tipe dasar spinner, yang direpresentasikan melalui data model yang berbeda:
SpinnerListModel,
SpinnerNumberModel, and
SpinnerDateModel.
Contoh membuat spinner yang menggunakan SpinnerListModel:
String[] options = { "small","medium","large","huge" };
SpinnerListModel model = new SpinnerListModel( options );
JSpinner spinner = new JSpinner( model );
Agar ukuran frame mengikuti ukuran spinner, kita dapat mengetikan satu kode berikut:
frame.pack();
Bab 3 Komponen-komponen Swing Page | 17
Contoh program 4: SpinnerList.java
Program 4: Implementasi JSpinner – SpinnerList.java
Berikut ini tampilan dari SpinnerList.java:
Gambar 10: Tampilan dari SpinnerList.java
Latihan menggunakan SpinnerNumberModel:
Buatlah sebuah program baru berdasarkan kode SpinnerList.java, tetapi kali ini menggunakan
SpinnerNumberModel sbb:
// siapkan beberapa numbers:
double initial=5.0, min=0.0, max=10.0, increment=0.1;
// buat model:
SpinnerNumberModel model =
new SpinnerNumberModel( initial, min, max, increment );
// buat objek spinner berdasarkan model tsb:
JSpinner spinner = new JSpinner(model);
import java.awt.*;
import javax.swing.*;
public class SpinnerList extends JFrame{
public SpinnerList(){
this.setSize(200,200);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setTitle("Spinner List");
this.setLocationRelativeTo(null);
String[] options = { "small","medium","large","huge" };
SpinnerListModel model = new SpinnerListModel( options );
JSpinner spinner = new JSpinner( model );
this.add(spinner);
this.setVisible(true);
this.pack();
}
public static void main(String[] args){
new SpinnerList();
}
}
Bab 3 Komponen-komponen Swing Page | 18
3.9. Border
Semua komponen Swing dapat memiliki dekorasi border. Untuk memberikan dekorasi, kita cukup
menggunakan method setBorder( ). Kita perlu memberikan implementasi dari interface Border sesuai
dengan kebutuhan kita.
Swing menyediakan banyak sekali implementasi Border di dalam package javax.swing.border. Untuk
membuat Border, kita dapat melakukan 2 cara:
menggunakan class BorderFactory
membuat objek berdasarkan class border
Contoh men-set border sebuah label menggunakan BorderFactory:
JLabel labelTwo = new JLabel("I have an etched border.");
labelTwo.setBorder(BorderFactory.createEtchedBorder( ));
BorderFactory sangat mudah digunakan, tetapi tidak menawarkan setiap option dari border yang
digunakan. Misalnya, apabila kita ingin membuat sebuah raised EtchedBorder (default-nya adalah
lowered), maka kita harus menggunakan constructor EtchedBorder.
Contoh membuat objek EtchedBorder dengan option RAISED:
JLabel labelTwo = new JLabel("I have a raised etched border.");
labelTwo.setBorder( new EtchedBorder(EtchedBorder.RAISED) );
Berikut ini beberapa jenis Border yang dapat digunakan:
BevelBorder
SoftBevelBorder
EmptyBorder
EtchedBorder
LineBorder
MatteBorder
TitledBorder
CompoundBorder
Bab 3 Komponen-komponen Swing Page | 19
Contoh Program 5: BorderTest.java
Lanjut ke halaman berikutnya…
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
class BorderTest extends JFrame {
public BorderTest() {
setTitle("Border Test");
setSize(455, 450);
this.setLayout(new GridLayout(6, 2, 5, 5));
JPanel p = new JPanel();
p.setBorder(new BevelBorder (BevelBorder.RAISED));
p.add(new JLabel("RAISED BevelBorder"));
this.add(p);
p = new JPanel();
p.setBorder(new BevelBorder (BevelBorder.LOWERED));
p.add(new JLabel("LOWERED BevelBorder"));
this.add(p);
p = new JPanel();
p.setBorder(new LineBorder (Color.black, 4, true));
p.add(new JLabel("Black LineBorder, thickness = 4"));
this.add(p);
p = new JPanel();
p.setBorder(new EmptyBorder (10,10,10,10));
p.add(new JLabel("EmptyBorder with thickness of 10"));
this.add(p);
p = new JPanel();
p.setBorder(new EtchedBorder (EtchedBorder.RAISED));
p.add(new JLabel("RAISED EtchedBorder"));
this.add(p);
p = new JPanel();
p.setBorder(new EtchedBorder (EtchedBorder.LOWERED));
p.add(new JLabel("LOWERED EtchedBorder"));
this.add(p);
p = new JPanel();
p.setBorder(new SoftBevelBorder (SoftBevelBorder.RAISED));
p.add(new JLabel("RAISED SoftBevelBorder"));
this.add(p);
p = new JPanel();
p.setBorder(new SoftBevelBorder (SoftBevelBorder.LOWERED));
p.add(new JLabel("LOWERED SoftBevelBorder"));
this.add(p);
Bab 3 Komponen-komponen Swing Page | 20
Program 5: Implementasi Border - BorderTest.java
p = new JPanel();
p.setBorder(new MatteBorder (new ImageIcon("ball.png")));
p.add(new JLabel("MatteBorder"));
this.add(p);
p = new JPanel();
p.setBorder(new TitledBorder (
new LineBorder (Color.black, 5),
"Title String"));
p.add(new JLabel("TitledBorder using LineBorder"));
this.add(p);
p = new JPanel();
p.setBorder(new TitledBorder (
new EmptyBorder (10,10,10,10)));
p.add(new JLabel("TitledBorder using EmptyBorder"));
this.add(p);
Color c1 = new Color(86, 86, 86);
Color c2 = new Color(192, 192, 192);
Color c3 = new Color(204, 204, 204);
Border b1 = new BevelBorder(EtchedBorder.RAISED, c3, c1);
Border b2 = new MatteBorder(3,3,3,3,c2);
Border b3 = new BevelBorder (EtchedBorder.LOWERED, c3, c1);
p = new JPanel();
p.setBorder(new CompoundBorder(
new CompoundBorder(b1, b2), b3));
p.add(new JLabel("CompoundBorder"));
this.add(p);
}
public static void main(String args[]) {
BorderTest frame = new BorderTest();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Bab 3 Komponen-komponen Swing Page | 21
Berikut ini tampilan dari BorderTest.java:
Gambar 11: Tampilan BorderTest.java
3.10. JMenu
Menu adalah sebuah komponen standar yang bersifat pull-down. Menu dapat berisi menu lain yang
disimpan sebagai submenu item. Hal ini memungkinkan kita membuat suatu struktur menu yang
kompleks. Kita juga dapat menyimpan berbagai komponen di dalam menu (seperti checkbox,
radiobutton, dll).
Untuk menyimpan menu dalam bentuk horizontal bar, kita gunakan JmenuBar yang dapat diposisikan di
posisi: top, bottom, atau middle.
Contoh membuat Menu:
JMenu utensils = new JMenu("Utensils");
utensils.add(new JMenuItem("Fork"));
utensils.add(new JMenuItem("Knife"));
utensils.add(new JMenuItem("Spoon"));
Bab 3 Komponen-komponen Swing Page | 22
Gambar 12: MenuBar, Menu, & MenuItem
Menggunakan Keyboard Access ( Alt & Ctrl) pada Menu
Kita dapat menggunakan keyboard untuk mengakses menu. Ada 2 cara yang dapat kita lakukan:
1. Mnemonics
Berupa satu karakter di dalam nama menu
Untuk mengaksesnya, kita menekan tombol “Alt + karakter“ mnemonic-nya
Menu items juga dapat memiliki mnemonics.
2. Accelerator
Accelerator merupakan kombinasi keyboard untuk memilih menu item tanpa perlu ditunjukkan
isi menu yang bersangkutan.
Contoh: Ctrl-C biasa digunakan sebagai shortcut untuk menu Copy item di dalam menu Edit.
Bab 3 Komponen-komponen Swing Page | 23
Contoh Program 6: DinnerMenu.java
Lanjut ke halaman berikutnya…
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DinnerMenu extends JFrame {
private JFrame frame;
private JMenu utensil,spices,cheese;
private JMenuItem quitItem;
private JMenuBar menuBar;
private ButtonGroup group;
private JRadioButtonMenuItem rbmi;
public DinnerMenu(){
createUserInterface();
}
private void createUserInterface(){
// create the Utensils menu
JMenu utensils = new JMenu("Utensils");
utensils.setMnemonic(KeyEvent.VK_U);
utensils.add(new JMenuItem("Fork"));
utensils.add(new JMenuItem("Knife"));
utensils.add(new JMenuItem("Spoon"));
JMenu hybrid = new JMenu("Hybrid");
hybrid.add(new JMenuItem("Spork"));
hybrid.add(new JMenuItem("Spife"));
hybrid.add(new JMenuItem("Knork"));
utensils.add(hybrid);
utensils.addSeparator( );
// do some fancy stuff with the Quit item
quitItem = new JMenuItem("Quit");
quitItem.setMnemonic(KeyEvent.VK_Q);
quitItem.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_Q, Event.CTRL_MASK));
utensils.add(quitItem);
// create the Spices menu
spices = new JMenu("Spices");
spices.setMnemonic(KeyEvent.VK_S);
spices.add(new JCheckBoxMenuItem("Thyme"));
spices.add(new JCheckBoxMenuItem("Rosemary"));
spices.add(new JCheckBoxMenuItem("Oregano", true));
spices.add(new JCheckBoxMenuItem("Fennel"));
Bab 3 Komponen-komponen Swing Page | 24
Program 6: Implementasi JMenu & JMenuBar – DinnerMenu.java
// create the Cheese menu
cheese = new JMenu("Cheese");
cheese.setMnemonic(KeyEvent.VK_C);
group = new ButtonGroup( );
rbmi = new JRadioButtonMenuItem("Regular", true);
group.add(rbmi);
cheese.add(rbmi);
rbmi = new JRadioButtonMenuItem("Extra");
group.add(rbmi);
cheese.add(rbmi);
rbmi = new JRadioButtonMenuItem("Blue");
group.add(rbmi);
cheese.add(rbmi);
// create a menu bar and use it in this JFrame
menuBar = new JMenuBar( );
menuBar.add(utensils);
menuBar.add(spices);
menuBar.add(cheese);
this.setJMenuBar(menuBar);
this.setSize(200,200);
this.setVisible(true);
this.setTitle("Dinner Menu");
this.setLocationRelativeTo(null);
}
public static void main(String[] args) {
DinnerMenu application = new DinnerMenu();
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
}
Bab 3 Komponen-komponen Swing Page | 25
Berikut ini beberapa tampilan dari DinnerMenu.java:
Gambar 13: Tampilan DinnerMenu.java
3.11. JPopupMenu
Pop up menu biasa disebut juga sebagai “context menu” merupakan menu yang dapat muncul di mana
saja tergantung posisi mouse. (Untuk windows, biasa diaktifkan menggunakan klik kanan)
Cara pembuatannya mirip dengan JMenu biasa, tetapi kita tidak menempelkannya pada JMenuBar.
Contoh membuat Pop-up Menu:
JPopupMenu contextMenu = new JPopupMenu("Edit");
contextMenu.add(new JMenuItem("Save"));
contextMenu.add(new JMenuItem("Save As"));
contextMenu.add(new JMenuItem("Close"));
Bab 3 Komponen-komponen Swing Page | 26
Contoh Program 7: ContextMenu.java
Program 7: Impelementasi JPopupMenu – ContextMenu.java
import java.awt.*;
import javax.swing.*;
public class ContextMenu extends JFrame {
private JPopupMenu contextMenu;
private JPanel panel;
public ContextMenu( ) {
createUserInterface();
}
private void createUserInterface(){
// Create JPopupMenu
contextMenu = new JPopupMenu("Edit");
contextMenu.add(new JMenuItem("Save"));
contextMenu.add(new JMenuItem("Save As"));
contextMenu.add(new JMenuItem("Close"));
// Create JPanel and attach the popup menu
panel = new JPanel( );
this.add( panel );
panel.setComponentPopupMenu( contextMenu );
this.setSize(400,200);
this.setVisible(true);
this.setTitle("ContextMenu v1.0");
}
public static void main(String[] args) {
ContextMenu application = new ContextMenu( );
application.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE );
}
}
Bab 3 Komponen-komponen Swing Page | 27
Berikut ini tampilan dari ContextMenu.java:
Gambar 14: Tampilan ContextMenu.java
3.12. JScrollPane
JScrollPane merupakan suatu container yang dapat menampung satu komponen. Dengan kata lain,
JScrollPane berfungsi untuk membungkus suatu komponen lain. Secara default, apabila komponen
yang dibungkusnya lebih besar dari JScrollPane itu sendiri, maka JScrollPane akan menyediakan
scrollbars.
Pada saat membuat JScrollPane, kita dapat menentukan kondisi untuk tampilan scrollbars-nya. Hal ini
dikenal dengan nama “scrollbar display policy” yang berlaku untuk scrollbar horizontal maupun vertical.
Berikut ini pilihan yang dapat digunakan untuk scrollbar display policy:
Constants (options) Deskripsi
HORIZONTAL_SCROLLBAR_AS_NEEDED
VERTICAL_SCROLLBAR_AS_NEEDED
Menampilkan scrollbar hanya pada saat komponen tidak
muat dibungkus
HORIZONTAL_SCROLLBAR_ALWAYS
VERTICAL_SCROLLBAR_ALWAYS
Selalu menampilkan scrollbar
HORIZONTAL_SCROLLBAR_NEVER
VERTICAL_SCROLLBAR_NEVER
Tidak pernah menampilkan scrollbar
Contoh membuat JScrollPane:
String filename = "daisies.jpg";
JLabel image = new JLabel( new ImageIcon(filename) );
frame.add(new JScrollPane(image) );
Bab 3 Komponen-komponen Swing Page | 28
Contoh Program 8: ScrollPaneFrame.java
Program 8: Implementasi JScrollPane – ScrollPaneFrame.java
Berikut ini tampilan dari ScrollPaneFrame.java:
Gambar 15: Tampilan ScrollPaneFrame.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ScrollPaneFrame extends JFrame{
JFrame frame;
JLabel image;
public ScrollPaneFrame(){
createUserInterface();
}
private void createUserInterface(){
String filename = "daisies.jpg";
JLabel image = new JLabel( new ImageIcon(filename) );
this.add(new JScrollPane(image) );
this.setTitle("ScrollPaneFrame v1.0");
this.setSize(300, 300);
this.setVisible(true);
}
public static void main(String[] args) {
ScrollPaneFrame app = new ScrollPaneFrame();
app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
Bab 3 Komponen-komponen Swing Page | 29
3.13. JSplitPane
JSplitPane merupakan container khusus yang dapat menampung dua buah komponen, dimana
masing-masing komponen disimpan di dalam sub-pane tersendiri. Pada objek JSplitPane, terdapat
sebuah splliter bar yang berfungsi untuk mengubah ukuran kedua subpane tersebut.
Contoh Program 9: SplitPaneFrame.java
Program 9: Implementasi JSplitPane – SplitPaneFrame.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class SplitPaneFrame extends JFrame{
Component left, right;
JLabel leftImage, rightImage;
String fileOne, fileTwo;
JSplitPane split;
public SplitPaneFrame(){
createUserInterface();
}
private void createUserInterface(){
fileOne = "ladybug.jpg";
fileTwo = "nemo.jpg";
leftImage = new JLabel( new ImageIcon( fileOne ) );
left = new JScrollPane(leftImage);
rightImage = new JLabel( new ImageIcon( fileTwo ) );
right = new JScrollPane(rightImage);
split =
new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, right);
split.setDividerLocation(200);
this.add(split);
this.setTitle("SplitPaneFrame");
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
this.setSize(500, 400);
this.setVisible(true);
}
public static void main(String[] args) {
SplitPaneFrame app = new SplitPaneFrame();
}
}
Bab 3 Komponen-komponen Swing Page | 30
Berikut ini tampilan dari SplitPaneFrame.java:
Gambar 16: Tampilan SplitPaneFrame.java
3.14. JTabbedPane
JTabbedPane merupakan container yang memiliki beberapa tab, di mana setiap tab tersebut memiliki
sebuah nama. Untuk menambahkan sebuah tab ke dalam JTabbedPane, kita tinggal menggunakan
method addTab().
Satu hal yang harus kita perhatikan adalah walaupun JTabbedPane hanya menunjukkan satu set
komponen tab sekali waktu, tetap harus diketahui bahwa semua komponen di tab lainnya tetap “hidup”
dan berada di memori.
Bab 3 Komponen-komponen Swing Page | 31
Contoh Program 10: TabbedPaneFrame.java
Program 10: Implementasi JTabbedPane – TabbedPaneFrame.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class TabbedPaneFrame extends JFrame {
public TabbedPaneFrame(){
createUserInterface();
}
private void createUserInterface(){
JTabbedPane tabby = new JTabbedPane( );
// create the controls pane
JPanel controls = new JPanel( );
controls.add(new JLabel("Service:"));
JList list = new JList(
new String[] { "Web server", "FTP server" });
list.setBorder(BorderFactory.createEtchedBorder( ));
controls.add(list);
controls.add(new JButton("Start"));
// create an image pane
String filename = "lotus.jpg";
JLabel image = new JLabel( new ImageIcon(filename) );
JComponent picture = new JScrollPane(image);
tabby.addTab("Controls", controls);
tabby.addTab("Picture", picture);
this.add(tabby);
this.setTitle("TabbedPaneFrame");
this.setSize(300, 300);
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
this.setVisible(true);
}
public static void main(String[] args) {
TabbedPaneFrame app = new TabbedPaneFrame();
}
}
Bab 3 Komponen-komponen Swing Page | 32
Berikut tampilan dari TabbedPaneFrame.java
Gambar 17: Tampilan TabbedPaneFrame.java
3.15. JOptionPane (Message Dialog)
Dialog biasanya digunakan untuk menampilkan informasi kepada user atau menanyakan sesuatu.
Dialog dapat diakses dengan menggunakan static methods yang terdapat pada class JOptionPane.
Kita dapat membuat beberapa variasi dari JOptionPane sesuai kebutuhan program sebagai berikut:
Jenis Dialog Fungsi
Message dialog Menampilkan suatu pesan kepada user, biasanya disertai dengan sebuah tombol OK
Confirmation dialog Menanyakan sebuah pertanyaan dan menampilkan tombol jawaban: Yes, No, dan Cancel
Input dialog Meminta user untuk memasukkan suatu String
Option dialogs Tipe yang paling umum. Kita dapat menyimpan berbagai komponen di dalamnya.
Untuk membuat variasi dari JOptionPane, kita dapat memanggil method yang bersesuaian sbb:
OptionPane.showMessageDialog, JOptionPane.showConfirmDialog, JOptionPane.showInputDialog, dan
JOptionPane.showOptionDialog
Bab 3 Komponen-komponen Swing Page | 33
Contoh Program 11: ExerciseOptions.java
Program 11 – Implementasi JOptionPane – ExerciseOptions.java
import javax.swing.*;
public class ExerciseOptions extends JFrame{
public ExerciseOptions(){
createUserInterface();
}
private void createUserInterface(){
this.setTitle("ExerciseOptions v1.0");
this.setSize(200, 200);
this.setVisible(true);
this.setLocationRelativeTo(null);
JOptionPane.showMessageDialog(this, "You've got mail!");
JOptionPane.showMessageDialog(this, "You are low on memory.",
"Apocalyptic message", JOptionPane.WARNING_MESSAGE);
int result = JOptionPane.showConfirmDialog(null,
"Do you want to remove Windows now?");
switch (result) {
case JOptionPane.YES_OPTION:
System.out.println("Yes"); break;
case JOptionPane.NO_OPTION:
System.out.println("No"); break;
case JOptionPane.CANCEL_OPTION:
System.out.println("Cancel"); break;
case JOptionPane.CLOSED_OPTION:
System.out.println("Closed"); break;
}
String name = JOptionPane.showInputDialog(null,
"Please enter your name.");
System.out.println(name);
JTextField userField = new JTextField( );
JPasswordField passField = new JPasswordField( );
String message = "Please enter your user name and password.";
result = JOptionPane.showOptionDialog(this,
new Object[] { message, userField, passField },
"Login", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, null, null);
if (result == JOptionPane.OK_OPTION)
System.out.println(userField.getText( ) +
" " + new String(passField.getPassword( )));
System.exit(0);
}
public static void main(String[] args) {
ExerciseOptions app = new ExerciseOptions();
}
}
Bab 3 Komponen-komponen Swing Page | 34
Berikut ini tampilan dari ExerciseOptions.java
Gambar 18: Tampilan ExerciseOptions.java
3.16. JScrollbar & JSlider
JSlider dan JScrollBar merupakan komponen Swing yang memiliki cara kerja serupa. Keduanya
digunakan untuk menentukan suatu nilai dengan cara menggeser sebuah knob secara vertikal atau
horisontal. Pada saat membuat objek slider dan scrollbar, kita dapat menentukan 3 buah nilai:
minimum, maximum, dan initial.
Berbeda dengan scrollbar, objek slider memiliki tick mark, yaitu garis yang menunjukan suatu nilai
tertentu sepanjang slider. Ada 2 jenis tick mark: major dan minor.
Contoh membuat Slider:
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 255, 128);
slider.setMajorTickSpacing(48);
slider.setMinorTickSpacing(16);
slider.setPaintTicks(true);
Bab 3 Komponen-komponen Swing Page | 35
Contoh Program 12: Slippery.java
Program 12: Implementasi JScrollbar & JSlider – Slippery.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Slippery extends JFrame{
JPanel main, scrollBarPanel,sliderPanel;
JScrollBar scrollBar;
public Slippery(){
createUserInterface();
}
private void createUserInterface(){
this.setTitle("Slippery v1.0");
main = new JPanel(new GridLayout(2, 1));
scrollBarPanel = new JPanel( );
scrollBar =
new JScrollBar(JScrollBar.HORIZONTAL, 0, 48, 0, 255);
int height = scrollBar.getPreferredSize( ).height;
scrollBar.setPreferredSize(new Dimension(175, height));
scrollBarPanel.add(scrollBar);
main.add(scrollBarPanel);
sliderPanel = new JPanel( );
final JSlider slider =
new JSlider(JSlider.HORIZONTAL, 0, 255, 128);
slider.setMajorTickSpacing(48);
slider.setMinorTickSpacing(16);
slider.setPaintTicks(true);
sliderPanel.add(slider);
main.add(sliderPanel);
this.add(main, BorderLayout.CENTER);
final JLabel statusLabel =
new JLabel("Welcome to Slippery v1.0");
this.add(statusLabel, BorderLayout.SOUTH);
this.pack( );
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
this.setVisible(true);
}
public static void main(String[] args) {
Slippery app = new Slippery();
}
}
Bab 3 Komponen-komponen Swing Page | 36
Berikut ini tampilan dari Slippery.java:
Gambar 19: Tampilan Slippery.java
3.17. JDesktopPane & JInternalFrame
Apabila kita menginginkan aplikasi windows di dalam windows, kita dapat menggunakan JDesktopPane
dan JInternalFrame. Internal frame ini dapat dipindahkan lokasinya (drag), di-resize, dijadikan icon,
serta di-maximize. Pada dasarnya, internal frame ini sebenarnya merupakan suatu container seperti
biasanya. Artinya kita dapat menyimpan berbagai komponen dan data di dalamnya.
Contoh Program 13: Desktop.java
Program 13 – Implementasi JDesktopPane & JInternalFrame – Desktop.java
import javax.swing.*;
public class Desktop extends JFrame{
public Desktop(){
createUserInterface();
}
private void createUserInterface(){
this.setTitle("Desktop");
JDesktopPane desktop = new JDesktopPane( );
for (int i = 0; i < 5; i++) {
JInternalFrame internal = new JInternalFrame("Frame " + i,
true, true, true, true);
internal.setSize(180, 180);
internal.setLocation(i * 20, i * 20);
internal.setVisible(true);
desktop.add(internal);
}
this.setSize(300, 300);
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
this.setContentPane(desktop);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
Desktop app = new Desktop();
}
}
Bab 3 Komponen-komponen Swing Page | 37
Berikut ini tampilan dari Desktop.java:
Gambar 20: Tampilan Dektop.java
Bab 4 Layout Manager Page | 38
Bab 4 Layout Manager
Selama ini, pada saat kita merancang GUI untuk program Java, salah satu halangannya adalah bahwa
komponen yang digunakan dapat berpindah-pindah lokasi. Hal ini terjadi apabila kita me-resize frame
utama. Sebenarnya, komponen dapat diorganisasikan di dalam container dengan menggunakan class
“layout manager”. Untuk melakukan hal tersebut, kita dapat mengubah secara manual class layout
yang ingin digunakan, dan setiap container dapat memiliki layout manager masing-masing.
Seperti pada gambar di bawah ini, layout manager bertugas menyusun komponen-komponen (button,
label, checkbox, dll) di dalam suatu container (panel, frame, dll). Layout manager menentukan posisi
dan ukuran setiap komponen di dalam container.
Gambar 21: Class LayoutManager
Library AWT dan Swing memiliki beberapa layout manager standar yang penggunaannya seringkali
dikombinasikan sesuai situasi dan kebutuhan kita.
Berikut ini adalah standard Layout Manager yang dapat kita gunakan:
FlowLayout
GridLayout
BorderLayout
BoxLayout
CardLayout
GridBagLayout
GroupLayout
Bab 4 Layout Manager Page | 39
Seperti telah disebutkan sebelumnya, setiap container memiliki default layout manager masing-masing.
Misalnya pada saat kita membuat sebuah container (panel, frame, tabbed pane, split pane, dll), maka
container tersebut memiliki objek LayoutManager masing-masing.
Kita dapat mengubah layout manager default tersebut dengan suatu layout yang baru dengan
menggunakan method setLayout().
Contoh mengubah layout default:
Default layout manager untuk JFrame adalah: FlowLayout
Untuk mengubahnya menjadi BorderLayout, kita dapat menuliskan kode berikut:
myFrame.setLayout(new BorderLayout());
4.1. FlowLayout
FlowLayout merupakan layout manager yang paling sederhana. Layout ini menyusun komponen
berdasarkan ukuran default masing-masing, dengan posisi mulai dari kiri ke kanan dan dari atas ke
bawah di dalam container yang digunakan.
FlowLayout dapat memiliki “row justification”: LEFT, CENTER, atau RIGHT serta “padding”
horizontal/vertical. Secara default, layout ini menggunakan justification CENTER. Artinya, semua
komponen akan disimpan di posisi tengah-tengah. FlowLayout merupakan default untuk JPanel.
Contoh membuat panel dengan flow layout:
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout());
Bab 4 Layout Manager Page | 40
Contoh Program 14: Flow.java
Program 14: Implementasi FlowLayout – Flow.java
Berikut ini tampilan dari Flow.java:
Gambar 22: Tampilan Flow.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Flow extends JFrame {
public Flow( ) {
createUserInterface();
}
private void createUserInterface(){
// FlowLayout adalah layout manager default untuk JPanel
JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout()); // baris ini dapat dihapus
panel1.add(new JButton("One"));
panel1.add(new JButton("Two"));
panel1.add(new JButton("Three"));
panel1.add(new JButton("Four"));
panel1.add(new JButton("Five"));
this.add(panel1);
this.setTitle("Flow");
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
this.setSize(400, 75);
this.setLocation(200, 200);
this.setVisible(true);
}
public static void main(String[] args) {
Flow app = new Flow();
}
}
Bab 4 Layout Manager Page | 41
4.2. GridLayout
GridLayout menempatkan komponen dalam bentuk “rectangular grid”.
Ada 3 constructor untuk GridLayout:
GridLayout(): membuat layout dengan satu kolom per komponen. Hanya satu baris yang
digunakan.
GridLayout(int rows, int cols): membuat suatu layout berdasarkan jumlah baris dan kolom yang
diinginkan.
GridLayout(int rows, int cols, int hgap, int vgap): membuat layout berdasarkan jumlah baris dan
kolom yang diinginkan, serta ukuran jarak (gap) horisontal maupun vertical untuk setiap baris
dan kolom tersebut.
GridLayout menempatkan komponen dengan urutan dari kiri ke kanan dan dari atas ke bawah dan
memaksa setiap komponen untuk menempati space container yang kosong serta membagi rata ukuran
space tersebut.
GridLayout paling cocok digunakan untuk menyusun komponen yang berukuran sama, misalnya 2 buah
JPanel berukuran sama di dalam sebuah frame.
Contoh membuat GridLayout:
frame.add(panel1);
frame.add(panel2);
frame.setLayout(new GridLayout(2, 1));
Kita dapat men-set jumlah baris dan kolom dengan angka 0. Hal ini berarti bahwa kita tidak
mempedulikan berapa banyak komponen yang akan masuk ke dalam dimensi layout manager tersebut.
Contoh: GridLayout(2,0)
Artinya: kita membuat layout manager dengan 2 baris dan jumlah tak terbatas untuk kolomnya.
Bab 4 Layout Manager Page | 42
Contoh Program 15: Grid.java
Program 15: Implementasi GridLayout – Grid.java
Berikut ini tampilan dari Grid.java:
Gambar 23: Tampilan Grid.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Grid extends JFrame {
public Grid( ) {
createUserInterface();
}
private void createUserInterface(){
JPanel panel1 = new JPanel();
panel1.setLayout(new GridLayout(3, 2));
panel1.add(new JButton("One"));
panel1.add(new JButton("Two"));
panel1.add(new JButton("Three"));
panel1.add(new JButton("Four"));
panel1.add(new JButton("Five"));
this.add(panel1);
this.setTitle("Grid");
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
this.setSize(200, 200);
this.setLocation(200, 200);
this.setVisible(true);
}
public static void main(String[] args) {
Grid app = new Grid();
}
}
Bab 4 Layout Manager Page | 43
4.3. BorderLayout
BorderLayout menyusun komponen berdasarkan lokasi geografis: NORTH, SOUTH, EAST, WEST, and
CENTER. Secara optional, kita dapat juga memberikan padding di antara komponen.
BorderLayout merupakan layout default untuk JWindow dan JFrame.
Karena setiap komponen diasosiasikan dengan suatu arah geografis, akibatnya layout ini hanya dapat
menangani maksimal 5 komponen.
Pada saat menambahkan suatu komponen kepada container yang memiliki border layout, kita harus
menentukan secara bersamaan komponen-nya dan posisi-nya.
Contoh membuat BorderLayout:
frame.setLayout(new BorderLayout( ));
frame.add(new JButton("Button1"), BorderLayout.NORTH );
frame.add(new JButton("Button2"), BorderLayout.SOUTH );
Contoh Program 16: BorderLayoutApp1.java
Program 16: Implementasi BorderLayout – BorderLayoutApp1.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BorderLayoutApp1 extends JFrame {
public BorderLayoutApp1( ) {
createUserInterface();
}
private void createUserInterface(){
this.setTitle("Border1");
this.setSize(300, 300);
this.setLocation(200, 200);
this.setLayout(new BorderLayout( ));
this.add(new JButton("North"), BorderLayout.NORTH );
this.add(new JButton("South"), BorderLayout.SOUTH );
this.add(new JButton("East"), BorderLayout.EAST );
this.add(new JButton("West"), BorderLayout.WEST );
this.add(new JButton("Center"), BorderLayout.CENTER );
this.setVisible(true);
}
public static void main(String[] args) {
BorderLayoutApp1 app = new BorderLayoutApp1();
app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
}
Bab 4 Layout Manager Page | 44
Gambar 24: Tampilan BorderLayoutApp1.java
Kita dapat mencegah terjadinya perubahan ukuran pada komponen kita dengan cara membuat
beberapa panel seperti pada program berikut.
Contoh Program 17: BorderLayoutApp7.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BorderLayoutApp2 extends JFrame {
public BorderLayoutApp2( ) {
createUserInterface();
}
private void createUserInterface(){
this.setTitle("Border2");
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
this.setSize(225, 150);
this.setLocation(200, 200);
this.setVisible(true);
this.setLayout(new BorderLayout( ));
JPanel p = new JPanel( );
p.add(new JButton("North"));
this.add(p, BorderLayout.NORTH);
Bab 4 Layout Manager Page | 45
Program 17: Implementasi BorderLayout dengan menggunakan Panel – BorderLayoutApp2.java
Berikut ini tampilan dari BorderLayoutApp2.java
Gambar 25: Tampilan BorderLayoutApp2.java
4.4. BoxLayout
Layout manager yang telah kita bahas sebelumnya merupakan bagian dari package java.awt.
Javax.swing memiliki beberapa tambahan layout manager lagi, salah satunya adalah: BoxLayout.
Layout manager ini sangat berguna untuk membuat toolbars sederhana atau vertical button bars.
Cara kerjanya sangat sederhana yaitu menempatkan komponen dalam satu baris atau satu kolom.
p = new JPanel( );
p.add(new JButton("South"));
this.add(p, BorderLayout.SOUTH);
p = new JPanel( );
p.add(new JButton("East"));
this.add(p, BorderLayout.EAST);
p = new JPanel( );
p.add(new JButton("West"));
this.add(p, BorderLayout.WEST);
p = new JPanel( );
p.add(new JButton("Center"));
this.add(p, BorderLayout.CENTER);
}
public static void main(String[] args) {
BorderLayoutApp2 app = new BorderLayoutApp2();
}
}
Bab 4 Layout Manager Page | 46
Untuk mempermudah penggunaan BoxLayout, Swing menyediakan sebuah kelas yang bernama Box
yaitu sebuah container yang secara otomatis memiliki BoxLayout manager.
Box memiliki beberapa methods yang akan mempermudah kita dalam menggunakan BoxLayout
manager, yaitu:
createHorizontalBox(): untuk membuat box horizontal
createHorizontalGlue(): untuk merekatkan komponen horisontal
createHorizontalStrut(int n) : untuk memberi jarak antar komponen
createVerticalBox(): untuk membuat box vertical
createVerticalGlue() : untuk merekatkan komponen vertikal
createVerticalStrut(int n) : untuk memberi jarak antar komponen
Contoh Program 18: Boxer.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Boxer extends JFrame {
public Boxer(){
createUserInterface();
}
private void createUserInterface(){
Container box = Box.createHorizontalBox( );
box.add(Box.createHorizontalGlue( ));
box.add(new JButton("In the"));
box.add(Box.createHorizontalGlue( ));
box.add(new JButton("clearing"));
box.add(Box.createHorizontalStrut(10));
box.add(new JButton("stands"));
box.add(Box.createHorizontalStrut(10));
box.add(new JButton("a"));
box.add(Box.createHorizontalGlue( ));
box.add(new JButton("boxer"));
box.add(Box.createHorizontalGlue( ));
this.add(box);
this.setTitle("Boxer");
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
this.setSize(250, 250);
this.setLocation(200, 200);
this.pack( );
this.setVisible(true);
}
Bab 4 Layout Manager Page | 47
Program 18: Implementasi BoxLayout – Boxer.java
Berikut ini tampilan dari Boxer.java:
Gambar 26: Tampilan Boxer.java
4.5. CardLayout
CardLayout merupakan layout manager yang mampu menciptakan efek “tumpukan” komponen.
Artinya, layout ini tidak memposisikan komponen di lokasi-lokasi tertentu di dalam kontainer, melainkan
menampilkannya satu demi satu.
Penggunaan CardLayout biasanya untuk membuat panel yang bersifat custom-tabbed. Namun,
sebenarnya kita dapat membuat panel tersebut dengan menggunakan komponen JTabbedPane.
Untuk mempraktekkan cara kerja dan efek “tumpukan” dari CardLayout ini, kita perlu mempelajari
terlebih dahulu mengenai “event-driven programming” yang akan dipelajari di bab berikutnya.
Contoh Program 19: Card.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Card extends JPanel {
CardLayout cards = new CardLayout( );
public Card( ) {
setLayout(cards);
ActionListener listener = new ActionListener( ) {
public void actionPerformed(ActionEvent e) {
cards.next(Card.this);
}
};
public static void main(String[] args) {
Boxer app = new Boxer();
}
}
Bab 4 Layout Manager Page | 48
Program 19: Implementasi CardLayout – Card.java
Berikut ini tampilan dari Card.java:
Gambar 27: Tampilan Card.java
JButton button;
button = new JButton("one");
button.addActionListener(listener);
add(button, "one");
button = new JButton("two");
button.addActionListener(listener);
add(button, "two");
button = new JButton("three");
button.addActionListener(listener);
add(button, "three");
}
public static void main(String[] args) {
JFrame frame = new JFrame("Card");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(200, 200);
frame.setLocation(200, 200);
frame.setContentPane(new Card( ));
frame.setVisible(true);
}
}
klik
Bab 4 Layout Manager Page | 49
4.6. GridBagLayout
GridBagLayout merupakan layaout manager yang sangat fleksibel. Layout ini memampukan kita
untuk memposisikan komponen relatif terhadap komponen lainnya berdasarkan constraint tertentu.
Dengan menggunakan GridBagLayout, kita dapat menciptakan layout apapun juga, tanpa batas.
Komponen disusun pada koordinat tertentu pada sebuah grid yang disebut “logical coordinate”, yang
berarti bahwa koordinat suatu komponen ditentukan oleh sekumpulan komponen lainnya. Baris dan
kolom dari grid tersebut bersifat “stretch” yang bergantung pada size dan constraint yang dimilikinya.
Walaupun fleksibel, pembuatan GridBag ini terkadang sangat membingungkan karena kita harus
mengatur berbagai size dan constraint dari setiap komponen yang digunakan.
Sebenarnya, penggunaan GridBagLayout ini jauh lebih mudah apabila kita menggunakan tools yang
mendukung WYSIWYG GUI builder. (contohnya: NetBeans IDE)
Contoh Program 20: GridBag1.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GridBag1 extends JFrame {
private GridBagConstraints constraints;
public GridBag1( ) {
createUserInterface();
}
private void createUserInterface(){
constraints = new GridBagConstraints( );
this.setLayout(new GridBagLayout( ));
int x, y; // for clarity
this.addGB(new JButton("North"), x = 1, y = 0);
this.addGB(new JButton("West"), x = 0, y = 1);
this.addGB(new JButton("Center"), x = 1, y = 1);
this.addGB(new JButton("East"), x = 2, y = 1);
this.addGB(new JButton("South"), x = 1, y = 2);
this.setTitle("GridBag1");
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
this.setSize(225, 150);
this.setLocation(200, 200);
this.setVisible(true);
}
Bab 4 Layout Manager Page | 50
Program 20: Implementasi GridBagLayout dengan constraint gridx dan gridy – GridBag1.java
Berikut tampilan dari GridBag1.java:
Gambar 28: Tampilan GridBag1.java
Selain constraint gridx dan gridy, kita juga dapat menggunakan constraint lain pada GridBagLayout,
yaitu:
fill
gridwidth
gridheight
weightx
weighty
ipadx
ipady
Contoh-contoh program yang menggunakan contraint-constraint tersebut tidak dituliskan di sini untuk
menghemat tempat, tetapi bisa dilihat di source code yang diberikan.
private void addGB(Component component, int x, int y) {
constraints.gridx = x;
constraints.gridy = y;
this.add(component, constraints);
}
public static void main(String[] args) {
GridBag1 app = new GridBag1();
}
}
Bab 4 Layout Manager Page | 51
4.7. GroupLayout
GroupLayout adalah LayoutManager yang secara hirarki mengelompokkan komponen dengan
tujuan memposisikannya di dalam suatu Container. GroupLayout lebih ditujukan untuk
pengaplikasian menggunakan GUI builder, tetapi kita dapat menggunakannya secara manual juga.
Pengelompokkan komponen dilakukan oleh objek dari class Group. GroupLayout memiliki 2 jenis
group yaitu:
Sequential group
Paralel group
Gambar berikut memperlihatkan 3 buah komponen dengan sequential group sepanjang sumbu
horisontal dan paralel group sepanjang sumbu vertikal.
Gambar 29: Implementasi sequential group secara horisonal dan paralel group secara vertikal
Gambar berikut memperlihatkan 3 buah komponen dengan paralel group sepanjang sumbu horisontal
dan sequential group sepanjang sumbu vertikal.
Gambar 30: Implementasi paralel group sepanjang horisonal dan sequential group sepanjang vertikal
Bab 4 Layout Manager Page | 52
Gambar berikut memperlihatkan penggunaan sequential group sepanjang sumbu horisontal dan
vertikal:
Gambar 31: Implementasi sequential group untuk pada kedua sumbu horisonal dan vertikal
Contoh Program 21: Group.java
import javax.swing.*;
import javax.swing.GroupLayout.*;
public class Group extends JFrame{
JLabel label1, label2;
JTextField tf1, tf2;
public Group( ) {
createUserInterface();
}
public void createUserInterface(){
label1 = new JLabel ("Username: ");
label2 = new JLabel ("Password: ");
tf1 = new JTextField();
tf2 = new JTextField();
JComponent panel = new JPanel();
this.add(panel);
GroupLayout layout = new GroupLayout(panel);
panel.setLayout(layout);
Bab 4 Layout Manager Page | 53
Program 21: Implementasi GroupLayout – Group.java
// Turn on automatically adding gaps between components
layout.setAutoCreateGaps(true);
// Turn on automatically creating gaps between components that touch
// the edge of the container and the container.
layout.setAutoCreateContainerGaps(true);
// Create a sequential group for the horizontal axis.
GroupLayout.SequentialGroup hGroup =
layout.createSequentialGroup();
// The sequential group in turn contains two parallel groups.
// One parallel group contains the labels, the other the text fields.
// Putting the labels in a parallel group along the horizontal axis
// positions them at the same x location.
// Variable indentation is used to reinforce the level of grouping.
hGroup.addGroup(layout.createParallelGroup().
addComponent(label1).addComponent(label2));
hGroup.addGroup(layout.createParallelGroup().
addComponent(tf1).addComponent(tf2));
layout.setHorizontalGroup(hGroup);
// Create a sequential group for the vertical axis.
GroupLayout.SequentialGroup vGroup =
layout.createSequentialGroup();
// The sequential group contains two parallel groups that align
// the contents along the baseline. The first parallel group contains
// the first label and text field, and the second parallel group contains
// the second label and text field. By using a sequential group
// the labels and text fields are positioned vertically after one
another.
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(label1).addComponent(tf1));
vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE).
addComponent(label2).addComponent(tf2));
layout.setVerticalGroup(vGroup);
}
public static void main(String[] args) {
Group g = new Group();
g.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
g.setSize(200, 100);
g.setLocation(200, 200);
g.setVisible(true);
}
}
Bab 4 Layout Manager Page | 54
Berikut ini tampilan dari Group.java
Gambar 32: Tampilan Group.java
Bab 5 Event Driven Programming Page | 55
Bab 5 Event-driven Programming
Event merupakan sebuah objek yang di-generate oleh user pada saat sesuatu terjadi terhadap suatu
komponen. Sebagai contoh, event di-generate pada saat user mengklik sebuah tombol, drag posisi
mouse, atau memilih item dari combo box. Objek event ini di-kirimkan kepada sebuah method khusus
yang kita buat yang disebut sebagai event listener. Event listener ini akan memeriksa objek event,
menentukan jenis event yang terjadi, dan langsung meresponnya.
event source ----> event object ----> event listener (interface) ----> event handler (method)
Java memiliki banyak objek Event, yang merupakan bagian dari package java.awt.event dan
javax.swing.event.
Berikut ini contoh rangkaian kerja dari Event-based model:
Tombol di-klik (oleh user)
Event di-generate (oleh sistem)
Action dijalankan
Event Handling and Listener
Untuk menangani event, kita harus meregistrasi suatu listener kepada objek yang menjadi source event
tersebut (misal: objek JButton). Listener yang kita buat merupakan implementasi dari interface
XXXListener. XXX ini artinya tergantung tipe event yang ingin dibuat. Interface XXXListener
ini didefinisikan di dalam package java.awt.event, java.beans, dan javax.swing.event.
Untuk meregristrasi objek kepada listener tersebut, kita dapat panggil method: addXXXListener()
Sebaliknya, untuk menghapus listener dari suatu objek, kita dapat memanggil method:
removeXXXListener().
Kita dapat meregistrasi beberapa listener kepada sebuah komponen, demikian juga sebaliknya, suatu
instance dari listener dapat diregistrasi untuk menerima event dari banyak komponen.
Setiap interface Listener pasti memiliki method yang harus kita implementasikan.
Misal: Interface ActionListener memiliki satu method yang bernama actionPerformed
Oleh karena itulah, kita harus implementasikan actionPerformed ini, sbb:
private class ContohListener implements ActionListener{
Bab 5 Event Driven Programming Page | 56
// Kita harus menuliskan method actionPerformed ini!!
public void actionPerformed(ActionEvent e){
// tetap harus ditulis walaupun isinya kosong!
}
}
Beberapa interface Listener dapat memiliki lebih dari satu method. Misalnya, interface MouseListener
terdiri dari 5 methods:
mousePressed
mouseReleased
mouseEntered
mouseExited
mouseClicked
Walaupun Anda hanya membutuhkan mouse click, Anda tetap harus mengimplementasikan ke-5
method MouseListener tersebut! Methods untuk event-event yang sebenarnya tidak kita perlukan
tersebut, memiliki empty body.
Contoh Implementasi MouseListener:
public class MyClass implements MouseListener {
... someObject.addMouseListener(this); ...
public void mouseClicked(MouseEvent e) {
//Event listener implementation goes here...
}
// Ke-4 method sisanya harus tetap ditulis, walaupun body-nya kosong!
public void mousePressed(MouseEvent e) { } // Empty method definition.
public void mouseReleased(MouseEvent e) { } // Empty method definition.
public void mouseEntered(MouseEvent e) { } // Empty method definition.
public void mouseExited(MouseEvent e) { } // Empty method definition.
}
Bab 5 Event Driven Programming Page | 57
Berikut ini daftar Event Listener Interfaces yang ada pada package java.awt.event
Event Related to
ActionListener Action events
AdjustmentListener Adjustment events
AWTEventListener Observe passively all events dispatched within AWT
ComponentListener Component (move, size, hide, show) events
ContainerListener Container (ad, remove component) events
FocusListener Focus (gain, loss) events
HierarchyBoundsListener Hierarchy (ancestor moved/resized) events
HierarchyListener Hierarchy (visibility) events
InputMethodListener Input method events (multilingual framework)
ItemListener Item events
KeyListener Keyboard events
MouseListener Mouse buttons events
MouseMotionListener Mouse motion events
MouseWheelListener Mouse wheel events
TextListener Text events
WindowFocusListener Window focus events (new focus management framework)
WindowListener Window events (non focus related)
WindowStateListener Window state events
Berikut ini Event listener interfaces yang ada pada package javax.swing.event
Event Related to
AncestorListener Changes to location and visible state of a JComponent or its parents
CaretListener Text cursor movement events
CellEditorListener Cell editor events
ChangeListener Change events
DocumentListener Text document events
HyperlinkListener Hyperlink events
Bab 5 Event Driven Programming Page | 58
InternalFrameListener Internal frame events
ListDataListener List data events
ListSelectionListener List selection events
MenuDragMouseListener Menu mouse movement events
MenuKeyListener Menu keyboard events
MenuListener Menu selection events
MouseInputListener Aggregrated mouse and mouse motion events
PopupMenuListener Popup menu events
TableColumnModelListener Table column events
TableModelListener Table model data events
TreeExpansionListener Tree expand/collapse events
TreeModelListener Tree model data events
TreeSelectionListener Tree selection events
TreeWillExpandListener Tree expand/collapse pending events
UndoableEditListener Undo/Redo events
Ada 3 Teknik Penulisan Event-Handling di Java
1. Menjadikan JFrame utama untuk meng-implements Listener interface
2. Menggunakan Inner-Class
3. Menggunakan Anonymous Inner-Class
Teknik 1: Menjadikan JFrame utama sebagai implementasi dari Listener
Untuk menuliskan kode Java yang dapat merespon pada suatu event, kita dapat lakukan 4 langkah
berikut:
1. Buatlah komponen yang akan men-generate event (misal: JButton):
JPanel panel = new JPanel();
button1 = new JButton("Click me! ");
panel.add(button1);
this.add(panel);
2. Buatlah sebuah class yang meng-implementasikan listener interface untuk event yang akan
ditangani:
public class ClickMe extends JFrame implements ActionListener
Bab 5 Event Driven Programming Page | 59
3. Tuliskanlah kode untuk semua methods yang didefinisikan oleh listener tersebut:
public void actionPerformed(ActionEvent e){
if (e.getSource() == button1)
button1.setText("You clicked! "); }
4. Regristrasi listener dengan source-nya:
JPanel panel = new JPanel();
button1 = new JButton("Click me! ");
button1.addActionListener(this);
panel.add(button1);
this.add(panel);
Contoh Program 22: ClickMe.java (Lengkap)
Program 22: Implementasi Event-Handling Cara 1: ClickMe.java
import javax.swing.*;
import java.awt.event.*;
public class ClickMe extends JFrame implements ActionListener {
private JButton button1;
private int clickCount = 0;
public ClickMe() {
JPanel panel1 = new JPanel();
button1 = new JButton("Click Me!");
button1.addActionListener(this);
panel1.add(button1);
this.add(panel1);
this.setSize(200,100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("I’m Listening");
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {
clickCount++;
if (clickCount == 1)
button1.setText("I’ve been clicked!");
else
button1.setText("I’ve been clicked "
+ clickCount + " times!");
}
}
public static void main(String [] args) {
ClickMe app = new ClickMe();
}
}
Bab 5 Event Driven Programming Page | 60
Berikut ini tampilan dari ClickMe.java:
Gambar 33: Tampilan ClickMe.java
Teknik 2: Menggunakan Inner Class
Inner class adalah suatu kelas yang bersarang di dalam kelas yang lain. Inner class juga dapat
dimanfaatkan untuk membuat suatu kelas yang meng-implement event listeners. Dengan cara ini,
class utama (yang mendefinisikan JFrame) tidak perlu meng-implement event listener.
Contoh Program 23: ClickMe2.java
import javax.swing.*;
import java.awt.event.*;
public class ClickMe2 extends JFrame {
private JButton button1;
public ClickMe2() {
ClickListener cl = new ClickListener();
JPanel panel1 = new JPanel();
button1 = new JButton("Click Me!");
button1.addActionListener(cl);
panel1.add(button1);
this.add(panel1);
this.setSize(200,100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("I’m Listening");
this.setVisible(true);
}
// Listenter inner class
private class ClickListener implements ActionListener {
private int clickCount = 0;
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button1) {
clickCount++;
if (clickCount == 1)
button1.setText("I’ve been clicked!");
else
button1.setText("I’ve been clicked "
+ clickCount + " times!");
}
Bab 5 Event Driven Programming Page | 61
Program 23: Implementasi Event-Handling Cara 2: ClickMe2.java
Berikut ini tampilan dari ClickMe2.java:
Gambar 34: Tampilan ClickMe2.java
Latihan
Tambahkan exit button kepada ClickMe2.java
Buatlah sebuah JButton, lalu masukkan ke dalam panel1
Di dalam method actionPerformed, modifikasi menjadi sbb:
if (e.getSource() == button1) {
clickCount++;
if (clickCount == 1)
button1.setText("I’ve been clicked!");
else
button1.setText("I’ve been clicked " + clickCount + " times!");
} else if (e.getSource() == exitButton) {
if (clickCount > 0)
System.exit(0);
}
}
}
public static void main(String [] args) {
ClickMe2 app = new ClickMe2();
}
}
Bab 5 Event Driven Programming Page | 62
Teknik 3: Penggunaan Anonymous Inner Class untuk menangani Event
Kita dapat membuat sebuah inner class tanpa menentukan namanya yang disebut sebagai anonymous
inner class. Setiap kali kita membuat komponen (misalnya JButton), kita langsung buatkan sebuah
anonymous inner class yang khusus akan menangani event untuk JButton itu sendiri.
Hal ini berbeda dengan teknik sebelumnya, di mana sebuah class dapat menangani banyak event dari
komponen, yang mana untuk membedakan event-source-nya kita gunakan e.getSource()
Dengan demikian, penggunaan anonymous inner class dapat mempermudah pembacaan kode kita,
karena class didefinisikan secara langsung di-tempat ia akan diakses (di-referenced). Namun,
kekurangannya adalah adanya kemungkinan penurunan performance karena banyaknya jumlah class
yang dibuat. (satu class untuk satu komponen!)
Contoh Penggunaan Anonymous Inner Class:
public class MyClass extends JFrame {
JButton okButton = new JButton("ok");
okButton.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Event listener implementation goes here...
}
});
...
}
Teknik 3 ini biasa digunakan apabila kita membuat aplikasi menggunakan GUI builder seperti NetBeans.
Anonymous Inner Class
Bab 5 Event Driven Programming Page | 63
Contoh Program 24: ClickMe3.java
Program 24: Implementasi Event handling cara 3: ClickMe3.java
Berikut tampilan dari ClickMe3.java:
Gambar 35: Tampilan ClickMe3.java
import javax.swing.*;
import java.awt.event.*;
public class ClickMe3 extends JFrame {
private JButton button1;
private int clickCount = 0;
public ClickMe3() {
JPanel panel1 = new JPanel();
button1 = new JButton("Click Me!");
button1.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
clickCount++;
if (clickCount == 1)
button1.setText("I’ve been clicked!");
else
button1.setText("I’ve been clicked "
+ clickCount + " times!");
}
});
panel1.add(button1);
this.add(panel1);
this.setSize(200,100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("I’m Listening");
this.setVisible(true);
}
public static void main(String [] args) {
ClickMe3 app = new ClickMe3();
}
}
Bab 5 Event Driven Programming Page | 64
Teknik Penanganan Komponen Input
Komponen Input 1: JTextField
JTextField merupakan salah satu komponen yang paling sering digunakan untuk menerima input dari
user. Berikut review cara membuat JTextField:
JTextField textField1 = new JTextField(15);
JTextField textField2 = new JTextField("Initial Value", 20);
Untuk mendapatkan nilai yang user telah ketik ke dalam sebuah JTextField, kita dapat gunakan method
getText()
Contoh mengambil input dari text field:
String lastName = textField1.getText();
Gambar 36: Contoh mengambil input dari JTextField dan menampilkannya di JOptionPane
Input yang didapatkan dari JTextField selalu berupa String. Apabila input yang diharapkan berupa
angka, maka kita perlu kita perlu menggunakan method konversi apabila ingin mendapatkan nilai angka
dari string input tersebut. Untuk melakukan hal ini, kita dapat menggunakan berbagai “parse
methods” yang dimiliki oleh wrapper classes untuk mendapatkan nilai angka tipe primitif-nya.
Misalnya, kita ingin mengkonversi nilai String dari suatu JTextField ke dalam tipe primitif int, maka kita
gunakan “method parseInt” milik “wrapper class Integer” sbb:
int count = Integer.parseInt(textField1.getText());
Berikut ini daftar Wrapper Classes & Methods konversinya:
Wrapper Class Parse Method
Integer parseInt (String)
Short parseShort (String)
Long parseLong (String)
Byte parseByte (String)
Float parseFloat (String)
Double parseDouble (String)
Bab 5 Event Driven Programming Page | 65
Berikut ini contoh-contoh konversi String ke dalam angka
int count = Integer.parseInt(textField1.getText());
short count = Short.parseShort(textField1.getText());
long count = Long.parseLong(textField1.getText());
byte count = Byte.parseByte(textField1.getText());
float count = Float.parseFloat(textField1.getText());
double count = Double.parseDouble(textField1.getText());
Sebaliknya, untuk melakukan konversi angka ke dalam String, kita dapat gunakan method valueOf
yang dimiliki oleh class String
Contoh konversi angka ke dalam String:
int angka = 5;
String nilai = String.valueOf(angka);
Komponen Input 2: RadioButton & CheckBox
Selain JTextField, kita juga bisa mendapatkan input dari RadioButtaon dan CheckBox. Kedua
komponen ini memiliki kemiripan, yaitu nilai yang dikandungnya hanyalah dua: selected atau tidak.
Oleh karena itu, kita dapat menggunakan method isSelected untuk memeriksa apakah
radiobutton/checkbox dipilih oleh user atau tidak.
Contoh mengambil input dari radiobutton/checkbox:
JRadioButton small = new JRadioButton("Small");
small.setSelected(true);
JCheckBox pepperoni = new JCheckBox("Pepperoni");
if (pepperoni.isSelected())
String tops = "Pepperoni";
if (small.isSelected())
String message = "small pizza";
Gambar 37: Mengambil input dari RadioButton/CheckBox dan menampilkannya di JOptionPane
Bab 5 Event Driven Programming Page | 66
Komponen Input 3: JScrollBar & JSlider
Kita juga bisa mendapatkan input dari JScrollBar dan JSlider. Namun, kedua komponen ini tidak
menggunakan ActionListener seperti halnya JButton.
JScrollBar memerlukan AdjustmentListener serta method adjustmentValueChanged
(AdjustmentEvent e)
JSlider memerlukan ChangeListener serta method stateChanged(ChangeEvent e)
Untuk mengambil input, kita gunakan method getValue()
Gambar 37: Mengambil input dari JScrollBar dan JSlider
Contoh inti kode program: Slippery.java
// Buat dan beri listener kepada scrollbar:
JScrollBar scrollBar = new JScrollBar(
JScrollBar.HORIZONTAL, 0, 48, 0, 255);
ScrollBarListener sBL = new ScrollBarListener();
scrollBar.addAdjustmentListener(sBL);
// Buat dan beri listener kepada slider:
slider = new JSlider(JSlider.HORIZONTAL, 0, 255, 128);
SliderListener sL = new SliderListener();
slider.addChangeListener(sL);
private class ScrollBarListener implements AdjustmentListener {
public void adjustmentValueChanged (AdjustmentEvent e) {
statusLabel.setText("JScrollBar's current value = "
+ scrollBar.getValue( ));
}
}
private class SliderListener implements ChangeListener {
public void stateChanged (ChangeEvent e) {
statusLabel.setText("JSlider's current value = " +
slider.getValue( ));
}
}
Bab 5 Event Driven Programming Page | 67
Latihan: Texter.java
Buatlah sebuah program sederhana yang menerima input dari sebuah text field
Pada saat user menekan tombol OK maka input tersebut akan disalin ke dalam sebuah text area.
Ukuran: JTextField(10), JTextArea(10,20), JFrame(300,300),
Gunakan JPanel, agar layout-nya secara otomatis berupa FlowLayout
Tampilan dari Texter.java:
Gambar 38: Tampilan Texter.java
Bab 6 Integrated Development Environment (IDE) Page | 68
Bab 6 Integrated Development Environment (IDE)
Setelah kita menguasai konsep dasar pemrograman desktop dengan menggunakan JavaSwing,
selanjutnya kita bisa menggunakan bantuan tools Integrated Development Environment (IDE) dalam
merancang antarmuka program. Hal ini akan sangat mempercepat proses pembuatan program
dibandingkan dengan melakukan coding secara manual.
Untuk membuat aplikasi desktop berbasis JavaSwing, kita dapat menggunakan berbagai macam IDE
yang tersedia di pasaran baik yang bersifat open source maupun komersil seperti:
NetBeans
Eclipse
Oracle JDeveloper
Borland JBuilder (based on eclipse)
JBoss IDE
RedHat Developer Studio (RHDS)
Jetbrains IntelliJ IDEA
Tools tersebut bukan saja berguna untuk membuat aplikasi desktop, tetapi juga dapat digunakan untuk
membuat berbagai aplikasi web maupun mobile.
Pada bab ini, kita akan menggunakan NetBeans IDE versi 6 untuk membuat sebuah aplikasi desktop
sederhana.
Pengenalan NetBeans IDE
NetBeans IDE adalah IDE yang bersifat open source (gratis) yang dapat kita gunakan untuk membuat
aplikasi desktop, enterprise, web, dan mobile dalam bahasa Java, C/C++, dan Ruby. IDE ini dapat
dijalankan di berbagai platform seperti Windows, Linux, Mac OS X, dan Solaris.
Berikut ini beberapa highlights dari NetBeans 6:
Easy-to-use Java GUI Builder
Visual Web and Java EE Development
Visual Mobile Development
Visual UML Modelling
Ruby and Rails Support
C and C++ Development
NetBeans IDE versi 6 dapat didownload secara cuma-cuma melalui website: www.netbeans.org
Bab 6 Integrated Development Environment (IDE) Page | 69
Tutorial 1: Pengembangan aplikasi GUI Dasar
Tutorial ini merupakan panduan bagi para pemula dalam membuat GUI (graphical user interface).
Secara khusus kita akan membuat sebuah aplikasi sederhana dengan nama ContactEditor dengan
menggunakan NetBeans IDE 6.0 Matisse GUI Builder.
Di dalam tutorial ini, kita akan membuat tampilan layout GUI yang memungkinkan kita untuk melihat
dan meng-edit informasi kontak dari database karyawan.
Hal-hal ini akan dilakukan sepanjang tutorial:
Menggunakan antarmuka GUI Builder
Membuat GUI Container
Menambahkan komponen
Mengubah ukuran komponen
Meratakan posisi komponen
Mengubah property komponen
1. Create New Project
To create a new ContactEditor application project:
1. Choose File > New Project. Alternately, you can click the New Project icon in the IDE toolbar.
2. In the Categories pane, select the General node and in the Projects pane, choose Java
Application. Click Next.
3. Enter ContactEditor in the Project Name field and specify the project location.
4. Ensure that the Set as Main Project checkbox is selected and deselect Create Main Class if it is
selected.
5. Click Finish.
2. Creating a GUI Container
To create a JFrame container:
1. In the Projects window, right-click the ContactEditor node and choose
New > JFrame Form.
2. Enter ContactEditorUI as the Class Name.
3. Enter my.contacteditor as the package.
4. Click Finish.
Bab 6 Integrated Development Environment (IDE) Page | 70
3. Getting Familiar with the GUI Builder
Bab 6 Integrated Development Environment (IDE) Page | 71
The GUI Builder's various windows
Design Area. The GUI Builder's primary window for creating and editing Java GUI forms. The
toolbar's Source and Design toggle buttons enable you to view a class's source code or a
graphical view of its GUI components. The additional toolbar buttons provide convenient access
to common commands, such as choosing between Selection and Connection modes, aligning
components, setting component auto-resizing behavior, and previewing forms.
Inspector. Provides a representation of all the components, both visual and non-visual, in your
application as a tree hierarchy. The Inspector also provides visual feedback about what
component in the tree is currently being edited in the GUI Builder as well as allows you to
organize components in the available panels.
Palette. A customizable list of available components containing tabs for JFC/Swing, AWT, and
JavaBeans components, as well as layout managers. In addition, you can create, remove, and
rearrange the categories displayed in the Palette using the customizer.
Properties Window. Displays the properties of the component currently selected in the GUI
Builder, Inspector window, Projects window, or Files window.
Key Concepts
The IDE's GUI Builder solves the core problem of Java GUI creation by streamlining the workflow
of creating graphical interfaces, freeing developers from the complexities of Swing layout
managers.
It does this by extending the current NetBeans IDE GUI Builder to support a straightforward
"Free Design" paradigm with simple layout rules that are easy to understand and use.
As you lay out your form, the GUI Builder provides visual guidelines suggesting optimal spacing
and alignment of components.
In the background, the GUI Builder translates your design decisions into a functional UI that is
implemented using the new GroupLayout layout manager and other Swing constructs.
Because it uses a dynamic layout model, GUI's built with the GUI Builder behave as you would
expect at runtime, adjusting to accommodate any changes you make without altering the
defined relationships between components.
Whenever you resize the form, switch locales, or specify a different look and feel, your GUI
automatically adjusts to respect the target look and feel's insets and offsets.
4. Adding Components: The Basics
Bab 6 Integrated Development Environment (IDE) Page | 72
To add a JPanel:
1. In the Palette window, select the JPanel component from the Swing category by clicking and
releasing the mouse button.
2. Move the cursor to the upper left corner of the form in the GUI Builder. When the component is
located near the container's top and left edges, horizontal and vertical alignment guidelines
appear indicating the preferred margins. Click in the form to place the JPanel in this location.
5. To resize the JPanel
Select the JPanel you just added. The small square resize handles reappear around the component's
perimeter.
Click and hold the resize handle on the right edge of the JPanel and drag until the dotted alignment
guideline appears near the form's edge.
Release the resize handle to resize the component.
Bab 6 Integrated Development Environment (IDE) Page | 73
6. Repeat The Task
Now that we've added a panel to contain our UI's Name information, we need to repeat the process
to add another directly below the first for the E-mail information.
7. Add title borders to the Jpanels
Select the top JPanel in the GUI Builder.
In the Properties window, click the ellipsis button (...) next to the Border property.
In the JPanel Border editor that appears, select the TitledBorder node in the Available Borders pane.
In the Properties pane below, enter Name for the Title property.
Click the ellipsis (...) next to the Font property, select Bold for the Font Style, and enter 12 for the
Size. Click OK to exit the dialogs.
Select the bottom JPanel and repeat steps 2 through 5, but this time right-click the JPanel and access
the Properties window using the pop-up menu. Enter E-mail for the Title property.
Titled borders are added to both JPanel components.
Bab 6 Integrated Development Environment (IDE) Page | 74
8. Adding Individual Components to the Form
To add a JLabel to the form:
1. In the Palette window, select the JLabel component from the Swing category.
2. Move the cursor over the Name JPanel we added earlier. When the guidelines appear indicating
that the JLabel is positioned in the top left corner of the JPanel with a small margin at the top
and left edges, click to place the label.
To edit the display text of a JLabel:
1. Double-click the JLabel to select its display text.
2. Type First Name: and press Enter.
Bab 6 Integrated Development Environment (IDE) Page | 75
9. To add a JTextField to the form
In the Palette window, select the JTextField component from the Swing category.
Move the cursor immediately to the right of the First Name: JLabel we just added. When the
horizontal guideline appears indicating that the JTextField's baseline is aligned with that of the
JLabel and the spacing between the two components is suggested with a vertical guideline, click to
position the JTextField.
Add an additional JLabel and JTextField immediately to the right of those we just added
10. To resize a JTextField:
Select the JTextField we just added to the right of the Last Name: JLabel.
Drag the JTextField's right edge resize handle toward the right edge of the enclosing JPanel.
When the vertical alignment guidelines appear suggesting the margin between the text field and
right edge of the JPanel, release the mouse button to resize the JTextField.
Bab 6 Integrated Development Environment (IDE) Page | 76
11. Adding Multiple Components to the Form
Now we'll add the Title: and Nickname: Jlabels
To add multiple JLabels to the form:
1. In the Palette window, select the JLabel component from the Swing category by clicking and
releasing the mouse button.
2. Move the cursor over the form directly below the First Name: JLabel we added earlier. When
the guidelines appear indicating that the new JLabel's left edge is aligned with that of the JLabel
above and a small margin exists between them, shift-click to place the first JLabel.
3. While still pressing the Shift key, click to place another JLabel immediately to the right of the
first. Make certain to release the Shift key prior to positioning the second JLabel. If you forget to
release the Shift key prior to positioning the last JLabel, simply press the Escape key.
12. To edit the display text of Jlabels
Double-click the first JLabel to select its display text.
Type Title: and press Enter.
Repeat steps 1 and 2, entering Nickname: for the second JLabel's name property.
Bab 6 Integrated Development Environment (IDE) Page | 77
13. Inserting Components
To insert a JTextField between two JLabels:
1. In the Palette window, select the JTextField component from the Swing category.
2. Move the cursor over the Title: and Nickname: JLabels on the second row such that the
JTextField overlaps both and is aligned to their baselines. If you encounter difficulty positioning
the new text field, you can snap it to the left guideline of the Nickname JLabel as shown in the
first image below.
3. Click to place the JTextField between the Title: and Nickname: JLabels.
14. Add one additional JTextField to the form that will display each contact's nickname on the right side
of the form.
To add a JTextField:
1. In the Palette window, select the JTextField component from the Swing category.
2. Move the cursor to the right of the Nickname label and click to place the text field.
To resize a JTextField:
1. Drag the resize handles of the Nickname: label's JTextField you added in the previous task
toward the right of the enclosing JPanel.
2. When the vertical alignment guidelines appear suggesting the margin between the text field and
JPanel edges, release the mouse button to resize the JTextField.
Bab 6 Integrated Development Environment (IDE) Page | 78
15. Component Alignment
To align components:
1. Select the First Name: and Title: JLabels on the left side of the form.
2. Click the Align Right in Column button in the toolbar. Alternately, you can right-click either one
and choose Align > Right in Column from the pop-up menu.
3. Repeat this for the Last Name: and Nickname: JLabels as well.
16. The JLabels are set to resize correctly
To set component resizeability behavior:
1. Control-click the two inserted JTextField components to select them in the GUI Builder.
2. With both JTextFields selected, right-click either one of them and choose Auto Resizing >
Horizontal from the pop-up menu.
To set components to be the same size:
1. Control-click all four of the JTextFields in the form to select them.
2. With the JTextFields selected, right-click any one of them and choose Set Default Size from the
pop-up menu.
17. Allign a JLabel
To align a JLabel to a component group:
Bab 6 Integrated Development Environment (IDE) Page | 79
1. In the Palette window, select the JLabel component from the Swing category.
2. Move the cursor below the First Name and Title JLabels on the left side of the JPanel. When the
guideline appears indicating that the new JLabel's right edge is aligned with the right edges of
the component group above (the two JLabels), click to position the component.
3. As in the previous examples, double-click the JLabel to select its display text and then enter
Display Format: for the display name.
18. Baseline Alignment
To align the baselines of components:
1. In the Palette window, select the JComboBox component from the Swing category.
2. Move the cursor immediately to the right of the JLabel we just added. When the horizontal
guideline appears indicating that the JComboBox's baseline is aligned with the baseline of the
text in the JLabel and the spacing between the two components is suggested with a vertical
guideline, click to position the combo box.
19. Resize the JcomboBox
To resize the JComboBox:
1. Select the JComboBox in the GUI Builder.
2. Drag the resize handle on the JComboBox's right edge toward the right until the alignment
guidelines appear suggesting the preferred offset between the JComboBox and JPanel edges.
Bab 6 Integrated Development Environment (IDE) Page | 80
20. Add another JTextField “Email”
To add, align, and edit the display text of a JLabel:
1. In the Palette window, select the JLabel component from the Swing category.
2. Move the cursor over the form immediately below the bottom JPanel's E-mail title. When the
guidelines appear indicating that it's positioned in the top left corner of the JPanel with a small
margin at the top and left edges, click to place the JLabel.
3. Double-click the JLabel to select its display text. Then type E-mail Address: and press Enter.
21. Add a JTextField
To add a JTextField:
1. In the Palette window, select the JTextField component from the Swing category.
2. Move the cursor immediately to the right of the E-mail Address label we just added. When the
guidelines appear indicating that the JTextField's baseline is aligned with the baseline of the text
in the JLabel and the margin between the two components is suggested with a vertical
guideline, click to position the text field.
3. Drag the resize handle of the JTextField toward the right of the enclosing JPanel until the
alignment guidelines appear suggesting the offset between the JTextField and JPanel edges.
Bab 6 Integrated Development Environment (IDE) Page | 81
22. Add the JList that will display our ContactEditor's entire contact list.
To add and resize a JList:
1. In the Palette window, select the JList component from the Swing category.
2. Move the cursor immediately below the E-mail Address JLabel we added earlier. When the
guidelines appear indicating that the JList's top and left edges are aligned with the preferred
margins along the JPanel's left edge and the JLabel above, click to position the Jlist.
3. Drag the JList's right resize handle toward the right of the enclosing JPanel until the alignment
guidelines appear indicating that it is the same width as the JTextField above.
23. Component Sizing
To add, align, and edit the display text of multiple buttons:
1. In the Palette window, select the JButton component.
2. Move the JButton over the right edge of the E-mail Address JTextField in the lower JPanel. When
the guidelines appear indicating that the JButton's baseline and right edge are aligned with that
of the JTextField, shift-click to place the first button along the JFrame's right edge. The
JTextField's width shrinks to accommodate the JButton when you release the mouse button.
3. Move the cursor over the top right corner of the JList in the lower JPanel. When the guidelines
appear indicating that the JButton's top and right edges are aligned with that of the JList,
shift-click to place the second button along the JFrame's right edge.
4. Add two additional JButtons below the two we already added to create a column. Make certain
to position the JButtons such that the suggested spacing is respected and consistent. If you
Bab 6 Integrated Development Environment (IDE) Page | 82
forget to release the Shift key prior to positioning the last JButton, simply press the Escape key.
5. Double-click each JButton and enter the text for each of their names. Enter Add for the top
button, Edit for the second, Remove for the third, and As Default for the fourth.
24. To set components to the same size:
1. Select all four JButtons by pressing the Control key while making your selection.
2. Right-click one of them and choose Same Size > Same Width from the pop-up menu. The
JButtons are set to the same size as the button with the longest name.
25. Indentation
To indent JRadioButtons below a JLabel:
1. Add a JLabel named Mail Format to the form below the JList. Make certain the label is left
aligned with the JList above.
2. In the Palette window, select the JRadioButton component from the Swing category.
3. Move the cursor below the JLabel that we just added. When the guidelines appear indicating
that the JRadioButton's left edge is aligned with that of the JLabel, move the JRadioButton
slightly to the right until secondary indentation guidelines appear. Shift-click to place the first
radio button.
4. Move the cursor to the right of the first JRadioButton. Shift-click to place the second and third
JRadioButtons, being careful to respect the suggested component spacing. Make certain to
release the Shift key prior to positioning the last JRadioButton.
5. Double-click each JRadioButton and enter the desired text for each of their names. Enter HTML
for the left radio button, Plain Text for the second, and Custom for the third.
Bab 6 Integrated Development Environment (IDE) Page | 83
26. Add JRadioButtons to a ButtonGroup:
To add JRadioButtons to a ButtonGroup:
1. In the Palette window, select the ButtonGroup component from the Swing category.
2. Click anywhere in the GUI Builder design area to add the ButtonGroup component to the form.
Notice that the ButtonGroup does not appear in the form itself, however, it is visible in the
Inspector's Other Component area.
3. Select all three of the JRadioButtons in the form.
4. In the Properties window, choose buttonGroup1 from the buttonGroup property combo box.
27. Finishing Up
We need to add the buttons that will enable users to confirm the information they enter for an
individual contact and add it to the contact list or cancel, leaving the database unchanged.
To add and edit the display text of buttons:
1. If the lower JPanel is extended to the bottom edge of the JFrame form, drag the bottom edge of
the JFrame down. This gives you space between the edge of the JFrame and the edge of the
JPanel for your OK and Cancel buttons.
2. In the Palette window, select the JButton component from the Swing category.
3. Move the cursor over the form below the E-mail JPanel. When the guidelines appear indicating
that the JButton's right edge is aligned with the lower right corner of the JFrame, click to place
the button.
4. Add another JButton to the left of the first, making certain to place it using the suggested
Bab 6 Integrated Development Environment (IDE) Page | 84
spacing along the JFrame's bottom edge.
5. Double-click each JButton to select their display text. Enter OK for the left button and Cancel for
right one. Notice that the width of the buttons changes to accommodate the new names.
6. Set the two JButtons to be the same size by selecting both, right-clicking either, and choosing
Same Size > Same Width from the pop-up menu.
28. Previewing Your GUI
1. Now that you have successfully built the ContactEditor GUI, you can try your interface to see the
results.
2. You can preview your form as you work by clicking the Preview Form button in the GUI Builder's
toolbar.
3. The form opens in its own window, allowing you to test it prior to building and running.
Bab 7 Pengembangan GUI Lanjutan Page | 85
Bab 7 Pengembangan GUI Lanjutan Menggunakan NetBeans
Pada bagian 2 ini, kita akan mencoba mengimplementasikan:
JMenu
JMenuItem & setMnemonics
JRadioButtonMenuItem
JTable
JDialog
JOptionPane
1. Create a new project
Buatlah sebuah project Java Application baru, dengan nama: Tutorial2
Buang tanda check pada checkbox “Create Main Class”
Klik Next
2. Membuat JFrame Form
a) Buatlah sebuah JFrame Form dengan meng-klik kanan project “Tutorial2”
b) Beri nama: OrderSystem
Bab 7 Pengembangan GUI Lanjutan Page | 86
c) Tuliskan nama package: si.maranatha
d) Klik finish
3. Membuat menu
a) NetBeans menyediakan berbagai komponen menu yang dapat dilihat di bagian Palette, Swing
Menus
b) Klik & drag komponen Menu Bar ke dalam JFrame yang telah dibuat
c) Pada saat Menu Bar di-drop ke dalam JFrame, maka secara otomatis menu bar tersebut akan
di-attach di bagian atas JFrame.
Bab 7 Pengembangan GUI Lanjutan Page | 87
4. Menambah JMenu
a) Secara default, NetBeans memberikan 2 buah JMenu yaitu:
a. jMenu1 (File)
b. jMenu2 (Edit)
b) Kita dapat melihat komponen-komponen Swing yang telah dibuat, melalui Inspector:
c) Tambahkan sebuah JMenu baru ke dalam menu bar tersebut dengan cara men-drag&drop
komponen Menu dari palette
5. Mengedit nama variabel & text JMenu
a) Gantilah nama variabel dan text dari setiap JMenu tersebut dengan cara meng-klik kanan
masing-masing menu, lalu memilih “Change variable name”
b) Gantilah sbb:
a. jMenu1 (file) menjadi fileMenu
b. jMenu2 (Edit) menjadi optionMenu
Bab 7 Pengembangan GUI Lanjutan Page | 88
c. jMenu3 (Menu) menjadi helpMenu
c) Kemudian ganti tampilan teks untuk semua menu tersebut dengan cara mengubah di bagian
Properties, text.
a. jMenu1 File
b. jMenu2 Options
c. jMenu 3 Help
6. Menambahkan JMenuItem & JradioButtonMenuItem
a) Kita dapat menambahkan JMenuItem ke dalam JMenu dengan cara men-drag&drop komponen
Menu Item dari pallete.
b) Tambahkan 2 buah Menu Item kepada Menu “File”
c) Tambahkan 3 buah Menu Item / RadioButton pada menu “Options”
d) Tambahkan 1 buah Menu Item pada menu “Help”
7. Mengubah variable name dan teks & First Run
a) Ubahlah semua variable name & teks untuk setiap menu item yang telah dibuat sbb:
b) Menu File
a. jMenuItem1 var name: newItem, teks: New
b. jMenuItem2 var name: quitItem, teks: Quit
Bab 7 Pengembangan GUI Lanjutan Page | 89
c) Menu Options
a. jRatioButtonMenuItem1 var name: hijauKuningItem, teks: “Menu Hijau, Panel
Kuning”
b. jRatioButtonMenuItem2 var name: biruPinkItem, teks: “Menu Biru, Panel Pink”
c. jRatioButtonMenuItem3 var name: pinkHijauItem, teks: “Menu Pink, Panel Hijau”
d. Tambahkan (drag) sebuah ButtonGroup dari palette ke dalam JFrame
e. Untuk ketiga JRatioButtonMenuItem, pada bagian properties, kategori buttonGroup,
klik drop down list, kemudian pilihlah “buttonGroup1”
f. Ubahlah properties selected sedemikian rupa sehingga hanya radio button yang
pertama yang memiliki atribut selected.
d) Menu Help
a. jMenuItem3 var name: aboutItem, teks: About
e) Run project dengan menekan tombol Run
8. Menambah Panel
Buatlah 2 buah Panel di dalam JFrame sbb:
Bab 7 Pengembangan GUI Lanjutan Page | 90
9. Menambah JTable
Drag&Drop komponen JTable ke dalam panel atas:
10. Customizing JTable
a) Klik kanan JTable tersebut, kemudian pilih “Table Contents…”
b) Akan muncul Customizer Dialog untuk tabel tersebut
c) Pilihlah tab Columns, kemudian ubahlah sbb:
d) Klik tombol Close
e) Hasil:
Bab 7 Pengembangan GUI Lanjutan Page | 91
11. Melakukan Koneksi Database
a) NetBeans dilengkapi dengan feature RDBMS yaitu JavaDB
b) Kita akan melakukan koneksi ke database yang telah ada, yaitu “sample”
c) Pilihlah services, kemudia klik kanan database “sample”
d) Klik connect
e) Isilah:
a. Username: app
b. Password: app
f) Klik OK
12. Data Binding Tabel ke JTable
a) Dengan menggunakan NetBeans, kita dapat dengan mudah melakukan binding sebuah tabel ke
dalam JTable.
b) Pada database “sample”, klik Tables, di situ terlihat banyak tabel seperti “CUSTOMER”,
“DISCOUNT CODE”, dll.
c) Klik tanda ‘+’ pada tabel ORDERS untuk melihat kolom-kolom yang ada.
Bab 7 Pengembangan GUI Lanjutan Page | 92
d) Untuk melakukan binding, klik tabel ORDERS kemudian drag&drop ke dalam JTable yang telah
dibuat sebelumnya.
e) Klik kanan JTable tersebut, pilih “Set default size”
f) Hasil:
13. Intro to Java Persistence API
a) Pada saat kita melakukan binding sebuah tabel, NetBeans secara otomatis membuat sebuah file
yang bernama Orders.java
b) Orders.java ini merupakan Entity Class yang mewakili tabel ORDERS dari database “sample”.
c) Entity Class ini merupakan bagian dari JPA (Java Persistence API) yang akan dibahas di lain waktu
.
d) Untuk saat ini, silahkan klik file tersebut untuk melihat isi source code-nya.
14. Mengubah ukuran
15. Ubahlah ukuran JFrame, JPanel & JTable dengan cara menggeser sisi-sisinya sedemikian rupa
sehingga menjadi lebih panjang sbb:
Bab 7 Pengembangan GUI Lanjutan Page | 93
16. Run Program & Resize ukuran kolom
a) Run Program:
b) Cobalah untuk me-resize kolom.
c) Cobalah untuk menggeser posisi kolom.
17. Tambahkanlah 2 buah JButton ke dalam panel bawah.
a) jButton1 var name: addButton, teks: Add
b) jButton2 var name: updateButton, teks: Update
Bab 7 Pengembangan GUI Lanjutan Page | 94
18. Menambahkan Event-Handling
a) NetBeans menyediakan fasilitas lengkap untuk melakukan event-handling.
b) Untuk melakukan event-handling, pertama-tama kita harus memberikan “listener” kepada
komponen yang diinginkan.
c) Klik kanan tombol addButton, kemudian pilih “Events” > “Action”
d) klik “actionPerformed”
e) NetBeans akan melakukan switch dari “Design View” menjadi “Source Code View” dari file
OrderSystem.java
f) Untuk kembali ke “Design View”, klik saja tombol “Design” di atas.
19. Mengimplementasikan Event-Handling
a) Pada saat kita klik “actionPerformed”, maka secara otomatis NetBeans akan membuatkan
sebuah method yang bernama xxxActionPerformed, dimana xxx merupakan nama variabel dari
Bab 7 Pengembangan GUI Lanjutan Page | 95
komponennya.
b) Berikut adalah method actionPerformed untuk AddButton:
c) Untuk menguji event-handling, cobalah ketikan:
a. System.out.println("Hello, saya bisa membuat program keren loh!!!");
d) Run program, kemudian klik tombol Add
e) Hasil println dapat dilihat di bagian output, pada tab “Tutorial2(run)”
20. NetBeans Autocomplete
a) NetBeans memiliki feature autocomplete pada saat mengetik kode program.
b) Sekarang kita coba memberikan “event-listener” kepada JRatioButtonMenuItem.
c) Klik kanan hijauKuningItem, kemudian pilih Events>Action>actionPerformed
d) Pada method tersebut, cobalah ketik: jPanel1
e) Kemudian lanjutkan dengan mengetik tanda titik: jPanel1.
f) NetBeans akan menampilkan berbagai atribut/method yang dapat digunakan oleh jPanel1.
21. Menggunakan key: Ctrl + Space
a) Setelah mengetik tanda titik “.” kita dapat memaksa NetBeans untuk menampilkan
auto-complete dengan menekan tombol “Ctrl+Space”
b) Cobalah mengetikan: jpanel1.set (lalu berhenti)
Bab 7 Pengembangan GUI Lanjutan Page | 96
c) Kemudian tekan tombol “Ctrl+space”
d) Secara otomatis, NetBeans akan menampilkan auto-complete untuk method yang dimulai
dengan kata “set”:
e) NetBeans juga menampilkan dokumentasi “javaDoc” untuk setiap atribut/method yang kita
sorot.
f) Carilah dan klik method “setBackground”
g) Lalu langsung ketikan: Color.
h) Pilih: yellow
22. Menggunakan Automatic Fixing Error
a) NetBeans juga dilengkapi dengan feature “Automatic fixing error”
b) Perhatikanlah bahwa di dalam source code tersebut, kata Color.yellow diberi garis warna merah.
c) NetBeans juga menampilkan icon lampu disebelah kiri, yang berarti ada eror di dalam kode kita.
d) Klik kanan icon lampu tersebut, lalu pililh Fixable Error, klik Fix Code…
e) Pilih “Add import for java.awt.Color”
Bab 7 Pengembangan GUI Lanjutan Page | 97
f) Perhatikan bahwa garis merah menghilang . Scroll source code ke atas, lihatlah bahwa
NetBeans telah menambahkan kode import:
g) Tips: Anda juga bisa langsung melakukan klik kiri icon tsb untuk langsung menampilkan pilihan
Fix Code.
23. Modifikasi jPanel2 & JFrame
a) Beri background warna kuning juga untuk jPanel2 & JFrame
b) Run program!
c) Klik radio item yang pertama.
d) Note: Untuk memberi warna JFrame, Anda harus mengambil komponen ContentPane terlebih
dahulu. ContentPane inilah yang kita beri warna background.
Selanjutnya, silahkan tambahkan hal-hal ini:
e) Pada method tersebut, beri warna background “green” untuk jMenuBar1.
f) Setelah itu, berikan pula action-listener untuk kedua menu item lainnya.
a. biruPink item
b. pinkHijau menu item
Sehingga menghasilkan:
Bab 7 Pengembangan GUI Lanjutan Page | 98
24. Membuat JDialog
a) Sekarang kita akan membuat sebuah JDialog.
b) Drag&drop Dialog pada palette ke dalam form yang telah kita buat.
c) Perhatikan di dalam Inspector, bahwa komponen JDialog telah ditambahkan ke dalam JFrame.
d) Klik kanan jDialog1 tsb, kemudian pilih Change variable name, beri nama: aboutDialog
25. Dekorasi JDialog
a) aboutDialog tersebut masih kosong.
b) Kita akan mendekorasinya dengan cara menambahkan sebuah gambar, label, dan tombol.
c) Double klik aboutDialog tersebut.
Bab 7 Pengembangan GUI Lanjutan Page | 99
d) Akan ditampilkan form untuk dialog tersebut:
e) Kita akan menambahkan sebuah gambar dan label pada form dialog tersebut.
f) Sebelumnya, copy-kan gambar logo.png ke folder “\Tutorial2\src”
g) Drag&drop sebuah label ke dalam form dialog.
h) Lalu pada properties, klik tanda elipsis dari icon:
i) Akan muncul dialog untuk mengelola jlabel tersebut.
26. Menambahkan resources
a) Akan muncul dialog sbb:
b) Klik tanda tombol “Import to Project…”. Kemudian pilihlah gambar yang telah di-copykan tadi.
c) Klik OK.
Bab 7 Pengembangan GUI Lanjutan Page | 100
27. Tambahkan Label & Button serta modifikasi properties dialog
a) Tambahkanlah sebuah label dengan tulisan: “Order System Versi 1.0”
b) Anda dapat mengubah jenis, ukuran, dan warna font pada bagian properties.
c) Kemudian tambahkan juga sebuah button.
d) Berikanlah action untuk close button tersebut:
1. aboutDialog.setVisible(false);
e) Pada bagian properties, modifikasi hal-hal berikut:
a. title: About
b. minimumSize: 400, 200
c. modal: true (beri tanda check) agar bisa on-top (tidak bisa ke form sebelumnya)
d. resizeable: false (uncheck)
f) Hasil:
28. Kembali ke form utama
1. Untuk kembali ke “design-view” dari form utama, double-klik saja JFrame melalui inspector:
2. Beri action untuk menu item About.
Bab 7 Pengembangan GUI Lanjutan Page | 101
3. Ketikan kode berikut:
aboutDialog.setVisible(true);
4. Berikan pula action untuk menu item Quit:
System.exit(0);
29. Hasil Akhir
Bab 8 Java Database Connectivity (JDBC) Page | 102
Bab 8 Java Database Connectivity (JDBC)
JDBC — Java Database Connectivity — adalah suatu feature di Java yang memungkinkan kita untuk
melakukan:
Koneksi ke hampir semua sistem RDBMS yang ada saat ini,
Eksekusi perintah SQL, dan
Memproses hasil perintah SQL melalui program Java
Library JDBC terdiri atas class-class yang berguna untuk setiap tasks di dalam pemrosesan database,
misalnya class untuk:
Membuat koneksi ke database
Membuat statement menggunakan SQL
Mengeksekusi query SQL (statement) di dalam database
Menampilkan records yang dihasilkan
Semua class-class JDBC adalah bagian dari java.sql package.
Gambar berikut ini memperlihatkan bagaimana program Java dapat mengakses database melalui JDBC:
Pada gambar tersebut, dapat dilihat bahwa library JDBC membutuhkan driver yang sesuai dengan
database yang dipergunakan. Oleh karena itu, sebelum kita dapat menulis program Java yang
mengakses database melalui JDBC, pertama-tama kita harus melakukan instalasi sebuah Driver yang
menghubungkan class-class di dalam Java’s database API dengan database yang akan digunakan.
Bab 8 Java Database Connectivity (JDBC) Page | 103
Untuk setiap database yang ada di pasaran saat ini, hampir semuanya memiliki driver JDBC-nya.
Biasanya driver ini dapat didownload secara gratis melalui website perusahaan database masing-masing.
Driver ini seringkali disebut juga sebagai “connector”.
Berikut ini langkah-langkah mempersiapkan driver untuk database MySQL:
1. Download driver JBDC MySQL dari website berikut: www.mysql.com/products/connector lalu
unzip file tsb.
Driver JDBC untuk MySQL dinamakan: MySQL Connector/J.
Setelah Anda mendownloadnya, unzip file tsb ke suatu folder, misalnya: “c:\MySQL”
2. Tambahkan file driver yang berekstensi “.jar” ke dalam variabel “ClassPath”
Misalnya: *)
c:\mysql\mysql-connector-java-3.1.10-bin.jar
c:\mysql\mysql-connector-java-5.0.7\mysql-connector-java-5.0.7-bin.jar
*) tergantung lokasi dan versi driver yang digunakan
Setelah kita melakukan kedua hal tersebut, program Java akan mampu mengakses database MySQL.
Selanjutnya, kita bisa memulai melakukan pembuatan program yang akan mengakses database
tersebut.
Ada 6 Langkah Koneksi & Akses Database
1. Memanggil Driver JDBC
2. Mendefinisikan URL untuk Koneksi Basis Data & Melakukan Koneksi tsb
3. Membuat Objek Statement
4. Melakukan Query/Update
5. Memproses Hasil
6. Menutup Koneksi
1. Memanggil Driver JDBC
Sebelum kita dapat menggunakan JDBC untuk mengakses database SQL, kita harus melakukan
koneksi terlebih dahulu.
Langkah pertama dalam melakukan koneksi adalah: registrasi driver
Caranya adalah dengan menggunakan method “forName” dari kelas “Class”
Misalnya untuk meregistrasi connector MySQL, gunakan perintah berikut:
Class.forName("com.mysql.jdbc.Driver");
Bab 8 Java Database Connectivity (JDBC) Page | 104
Perhatikan di sini bahwa forName akan melemparkan ClassNotFoundException, sehingga
kita harus membuat statement ini di dalam blok try/catch yang akan menangkap objek
ClassNotFoundException, sebagai berikut:
try {
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException){
// error handling
}
2. Mendefinisikan URL dan Melakukan Koneksi
Setelah kita meregristrasi class driver di langkah 1, selanjutnya kita dapat memanggil static method
getConnection dari class DriverManager untuk membuka koneksi database.
Method ini membutuhkan 3 parameter String:
URL Database
Username
Password
Contoh membuka koneksi:
String url = "jdbc:mysql://localhost/movies";
String user = "root";
String pw = "";
Conection con = DriverManager.getConnection(url, user, pw);
Method getConnection melemparkan SQLException, sehingga kita perlu membuatnya di
dalam blok try/catch.
3. Membuat Objek Statement
Kita memerlukan objek Statement untuk melakukan query dan objek ini dapat dibuat dari objek
Connection.
Statement adalah interface yang berisikan method-method yang diperlukan untuk mengirimkan
statement kepada database agar dieksekusi dan menghasilkan hasil.
Ada 2 method yang dapat kita gunakan untuk mengeksekusi Statement:
executeQuery untuk mengeksekusi statement select
executeUpdate untuk mengkeksekusi statement insert, update, atau delete
Contoh membuat objek statement:
Statement st = conn.createStatement();
Bab 8 Java Database Connectivity (JDBC) Page | 105
Berikut ini kode lengkap dari langkah 1 sampai 3, yang merupakan sebuah method yang bertugas
me-return objek Connection yang akan menjadi penghubung program ke database MySQL
private static Connection getConnection(){
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/movies";
String user = "root";
String pw = " ";
con = DriverManager.getConnection(url, user, pw);
}
catch (ClassNotFoundException e){
System.out.println(e.getMessage());
System.exit(0);
}
catch (SQLException e){
System.out.println(e.getMessage());
System.exit(0);
}
return con;
}
4. Mengeksekusi Query Untuk Statement Select
Setelah kita memiliki objek Statement, kita dapat menggunakannya untuk mengirimkan query
dan mengeksekusinya dengan method executeQuery yang menghasilkan objek bertipe
ResultSet.
ResultSet ini merupakan interface yang merepresentasikan rows yang dihasilkan dari query.
Ada 2 method yang disediakan oleh ResultSet:
Method untuk berpindah dari baris satu ke baris lainnya
Method untuk mengambil data dari sebuah kolom
Contoh mengeksekusi statement select:
String query = "SELECT id, title FROM movie";
ResultSet rs = st.executeQuery(query);
Note: Apabila ingin melakukan insert/update/delete, kita perlu menggunakan
st.executeUpdate(query) yang akan dibahas di langkah ke 7.
Bab 8 Java Database Connectivity (JDBC) Page | 106
5. Memproses Hasil
Dalam memproses hasil, kita menggunakan objek resultSet karena hasil query disimpan dalam objek
ini. Objek ResultSet yang dihasilkan dari statement executeQuery berisi semua baris yang
didapatkan melalui statement select. Kita hanya dapat mengakses baris-baris di dalam ResultSet
ini satu demi satu.
Berikut ini method-method yang digunakan untuk berpindah cursor (baris yang sedang di akses) di
dalam suatu ResultSet:
Method Deskripsi void close() Closes the result set void last() Moves the cursor to the last row int getRow() Gets the current row number boolean next() Moves to the next row
Untuk mengambil isi kolom dalam setiap baris, kita harus menggunakan method yang sesuai dengan
tipe data kolom tersebut:
Method Description
boolean getBoolean(String columnName) Gets the value of the specified column as a boolean
boolean getBoolean(int columnIndex) Gets the value of the specified column as a boolean
Date getDate(String columnName) Gets the value of the specified column as a Date
Date getDate(int columnIndex) Gets the value of the specified column as a Date
double getDouble(String columnName) Gets the value of the specified column as a double
double getDouble(int columnIndex) Gets the value of the specified column as a double
int getInt(String columnName) Gets the value of the specified column as a int
int getInt(int columnIndex) Gets the value of the specified column as a int
String getString(String columnName) Gets the value of the specified column as a String
String getString(int columnIndex) Gets the value of the specified column as a String
Seperti yang tertera pada tabel tersebut, setiap method memiliki 2 versi yang berbeda:
Versi 1 menentukan kolom melalui nama, versi 2 menentukan kolom melalui nomor indeks
(posisi kolom).
Apabila kita mengetahui posisi kolom, kita dapat mengakses nilai kolom secara lebih efisien
daripada melalui nama kolom.
Bab 8 Java Database Connectivity (JDBC) Page | 107
Contoh lengkap pengolahan hasil query select:
ResultSet rs = st.executeQuery(select);
try {
while (rs.next()){
String title = movies.getString("Title");
int year = movies.getInt("Year");
double price = movies.getDouble("Price");
String msg = title + " " + year + " " + price;
System.out.println(msg);
}
}
catch (SQLException e){
System.out.println(e.getMessage());
}
6. Memproses Query Untuk Statement Update/Insert/Delete
Setelah mengerti bagaimana menampilkan data, maka kita perlu mengerti bagaimana
menambah/menghapus/mengupdate data ke tabel.
Untuk melakukan hal tersebut, kita menggunakan method:
executeUpdate("perintah sql untuk insert / update /delete");
Method tersebut akan menghasilkan nilai integer yang merupakan jumlah baris yang dipengaruhi
oleh proses update tersebut.
Contoh statement delete:
int i = st.executeUpdate("delete from movie where id = '2'");
Apabila di dalam query diperlukan parameter dari luar, maka kita harus menggunakan
PreparedStatement:
Berikut contoh penggunaan PreparedStatement:
PreparedStatement st =
conn.prepareStatement ("INSERT INTO movie VALUES (?,?,?)");
st.setString(1, "Passion of The Christ");
st.setInt(2, 2004);
st.setDouble(2, 22.5);
int i = st.executeUpdate();
....
....
st.close();
7. Menutup Koneksi
Sebelum menutup koneksi basis data, kita juga perlu melepaskan objek ResultSet yang ada dengan
kode berikut:
st.close();
Bab 8 Java Database Connectivity (JDBC) Page | 108
Untuk menutup koneksi ke basis data, kita tuliskan sbb:
conn.close();
Berikut ini contoh lengkap program yang mengakses database MySQL
Nama File: ListMovies.java
Langkah-langkah persiapan:
1. Jalankan MySQL server + Apache server (melalui XAMPP Control Panel)
2. Masuk ke phpMyAdmin: http://localhost/phpmyadmin/
3. Di dalam phpMyAdmin, import the “movieSQL.sql” script
4. Browse table “movie”, yang isinya adalah sbb:
Bab 8 Java Database Connectivity (JDBC) Page | 109
Contoh Program 25: ListMovies.java
import java.sql.*;
import java.text.NumberFormat;
public class ListMovies{
public static void main(String[] args){
NumberFormat cf = NumberFormat.getCurrencyInstance();
ResultSet movies = getMovies();
try {
while (movies.next()){
Movie m = getMovie(movies);
String msg = Integer.toString(m.year);
msg += ": " + m.title;
msg += " (" + cf.format(m.price) + ")";
System.out.println(msg);
}
}
catch (SQLException e){
System.out.println(e.getMessage());
}
}
private static ResultSet getMovies(){
Connection con = getConnection();
try {
Statement s = con.createStatement();
String select = "Select title, year, price "
+ "from movie order by year";
ResultSet rows;
rows = s.executeQuery(select);
return rows;
}
catch (SQLException e) {
System.out.println(e.getMessage());
}
return null;
}
private static Connection getConnection() {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost/movies";
String user = "root";
String pw = "";
con = DriverManager.getConnection(url, user, pw);
}
Bab 8 Java Database Connectivity (JDBC) Page | 110
Program 25: Pengaksesan database menggunakan JDBC – ListMovies.java
Berikut ini adalah hasil dari ListMovie.java:
1946: It’s a Wonderful Life ($16.45)
1965: The Great Race ($14.25)
1974: Young Frankenstein ($18.65)
1975: The Return of the Pink Panther ($13.15)
1977: Star Wars ($19.75)
1987: The Princess Bride ($18.65)
1989: Glory ($16.45)
catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
System.exit(0);
}
catch (SQLException e) {
System.out.println(e.getMessage());
System.exit(0);
}
return con;
}
private static Movie getMovie(ResultSet movies) {
try {
String title = movies.getString("Title");
int year = movies.getInt("Year");
double price = movies.getDouble("Price");
return new Movie(title, year, price);
}
catch (SQLException e) {
System.out.println(e.getMessage());
}
return null;
}
private static class Movie {
public String title;
public int year;
public double price;
public Movie(String title, int year, double price) {
this.title = title;
this.year = year;
this.price = price;
}
}
}
Bab 8 Java Database Connectivity (JDBC) Page | 111
1995: Apollo 13 ($20.85)
1997: The Game ($16.45)
2001: The Lord of the Rings: The Fellowship of the Ring ($21.95)
Peringatan Untuk Pengguna JDBC
Berikut cuplikan dokumentasi dari MySQL Connector/J:
“Although JDBC is useful by itself, we would hope that if you are not familiar with JDBC that after
reading the first few sections of this manual, that you would avoid using naked JDBC for all but the most
trivial problems and consider using one of the popular persistence frameworks such as Hibernate,
Spring's JDBC templates or Ibatis SQL Maps to do the majority of repetitive work and heavier lifting that
is sometimes required with JDBC.”
Produk Persistence Framework yang cukup populer digunakan saat ini adalah Hibernate dan Oracle
TopLink. Framework ini dinamakan JPA (Java Persisitence API) yang merupakan bagian standar dari
Java Enterprise Edition (J2EE) yang akan dipelajari di bab berikutnya.
Bab 9 Java Persistence API (JPA) Page | 112
Bab 9 Java Persistence API (JPA)
Kata “Enterprise” merupakan istilah yang seringkali digembar-gemborkan dalam pengembangan
software sekarang ini. Pada saat seseorang menyatakan bahwa ia sedang mengembangkan aplikasi
enterprise, kata kuncinya hanyalah satu: informasi. Artinya pada dasarnya, aplikasi enterprise
didefinisikan berdasarkan kebutuhan aplikasi untuk mengumpulkan, men-transform, dan report
sejumlah besar informasi.
Banyak cara untuk menyimpan data (persisting data). Namun, sampai dengan saat ini, tidak ada
konsep yang mampu mengalahkan konsep Relational Database. Dengan kata lain, mayoritas data
perusahaan di seluruh dunia disimpan di dalam bentuk Relational Database. Hal ini berarti bahwa
memahami data relasional merupakan kunci di dalam pengembangan aplikasi enterprise.
Untuk JAVA PLATFORM, salah satu kunci keberhasilannya adalah penerimaan bahasa tsb yang luas untuk
membuat aplikasi enterprise yang memanfaatkan sistem basis data.
Consumer web sites (online shopping): Amazon, Ebay
Automated system: sistem parkir, tiket box, atm, dll
Desktop & mobile system
Dibalik kesuksesan Java dalam pengelolaan sistem basis data, ternyata masih ada satu masalah yang
besar! Proses pemindahan (konversi) data dari sistem basis data ke model objek (dan juga sebaliknya)
di dalam aplikasi java masih merupakan hal yang sulit dilakukan. Programmer/developers Java
seringkali harus menghabiskan waktu yang cukup banyak untuk mengkonversi “baris” dan “kolom”
menjadi objek. Untungnya, saat ini telah ada satu solusi yang luar biasa!
Standar pengaksesan database yang didukung baik komunitas open source (Apache, JBoss, Hibernate,
etc) maupun commercial vendor (Sun, IBM, Oracle, BEA, etc): Java Persistence API (JPA).
With JPA, for the first time, developers have a standard way of bridging the gap between
object-oriented domain models and relational database systems.
Java Persistence API adalah sebuah framework yang dapat Anda gunakan untuk penyimpanan data
(persistence) secara efektif!
The old way but still working good & supported:
JDBC
Enterprise JavaBeans (EJB)
Java Data Objects (JDO)
Bab 9 Java Persistence API (JPA) Page | 113
JDBC
JDBC is a simple and portable abstraction of the proprietary client programming interfaces offered by
database vendors, that allows Java programs to fully interact with the database. This interaction is
heavily reliant on SQL, offering developers the chance to write queries and data manipulation
statements in the language of the database, but executed and processed using a simple Java
programming model.
THE PROBLEM: This is a very effective programming model until the minute you realize that the
application has to support a new database vendor and that it doesn’t support the dialect of SQL you
have been using.
Enterprise JavaBeans (EJB)
The first release of the Java 2 Enterprise Edition (J2EE) platform introduced a new solution for Java
persistence in the form of the entity bean, part of the Enterprise JavaBean (EJB) family of components.
Intended to fully insulate developers from dealing directly with persistence, it introduced an
interface-based approach, where the concrete bean class is never directly used by client code.
THE PROBLEM: despite the improvements introduced with EJB 2.0, there is one problem that could not
be overcome by the EJB expert group: complexity.
Java Data Objects (JDO)
Due in part to some of the failures of the EJB persistence model, and some amount of frustration at not
having a standardized persistence API that was satisfactory, another persistence specification effort was
attempted. Java Data Objects (JDO) was inspired and supported primarily by the object-oriented
database (OODB) community
THE PROBLEM: It had a query language that was decidedly object-oriented in nature, which did not sit
well with the relational database users, who as it turned out were the majority.
JDO reached the status of being an extension of the Java Development Kit (JDK) but never became an
integrated part of the enterprise Java platform.
Java Persistence API
The Java Persistence API is a lightweight, POJO-based framework for Java persistence. The model of
the Java Persistence API is simple and elegant, powerful and flexible. It is natural to use, and easy to
learn.
Bab 9 Java Persistence API (JPA) Page | 114
POJO Persistence
Perhaps the most important aspect of the Java Persistence API is the fact that the objects are POJOs,
meaning that there is nothing special about any object that is made persistent.
API yang paling populer saat ini:
TopLink dari Oracle (Tersedia open source: TopLink Essentials)
Hibernate (open source)
“The domain model has a class. The database has a table. They look pretty similar. It should be simple to
convert from one to the other automatically.”
The science of bridging the gap between the object model and the relational model is known as
object-relational mapping (ORM)
Contoh: Class diagram “Employee” & Tabel “Emp”
Pada Java, Proses Mapping ini dapat dilakukan dengan menggunakan ANNOTATIONS
Annotations (@)
Annotation metadata is a language feature that allows structured and typed metadata (nama tabel,
nama kolom, constraint) to be attached to the source code. It was introduced as part of Java SE 5 and
is a key part of the EJB 3.0 and Java EE 5 specifications. Although annotations are not required by the
Java Persistence API, they are a convenient way to learn and use the API.
Cara lain selain menggunakan Annotations adalah dengan menggunakan file XML sebagai file konfigurasi
pemetaan.
Bab 9 Java Persistence API (JPA) Page | 115
Mapping Java class menjadi Entity class
Regular Java classes are easily transformed into entities simply by annotating them. In fact, by adding a
couple of annotations, virtually any class with a no-arg constructor can become an entity.
This example show the mapping of employee class to Employee entity.
Employee class biasa ORM Entitas Employee
Program 26: POJO Class Employee – Employee.java
public class Employee {
private int id;
private String name;
private long salary;
public Employee() {
}
public Employee(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getSalary() {
return salary;
}
public void setSalary(long salary) {
this.salary = salary;
}
}
Bab 9 Java Persistence API (JPA) Page | 116
Anotating Employee Class
To turn Employee into an entity we first need to annotate the class with @Entity. This is primarily just
a marker annotation to indicate to the persistence engine that the class is an entity.
The second annotation that we need to add is @Id. This annotates the particular field or property that
holds the persistent identity of the entity (the primary key) and is needed so the provider knows which
field or property to use as the unique identifying key in the table.
Program 27: Entity Class Employee – Employee.java
import javax.persistence.*;
@Entity
public class Employee {
@Id private int id;
private String name;
private long salary;
public Employee() {
}
public Employee(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getSalary() {
return salary;
}
public void setSalary(long salary) {
this.salary = salary;
}
}
Bab 9 Java Persistence API (JPA) Page | 117
Entity Manager
A specific API call needs to be invoked before an entity actually gets persisted to the database.
In fact, separate API calls are needed to perform many of the operations on entities (create, delete,
update, find). This API is implemented by the entity manager and encapsulated almost entirely within
a single interface called EntityManager. When all is said and done, it is to an entity manager that the
real work of persistence is delegated. Until an entity manager is used to actually create, read, or
write an entity, the entity is nothing more than a regular (non-persistent) Java object.
How does Entity Manager works?
When an entity manager obtains a reference to an entity, either by having it explicitly passed in or
because it was read from the database, that object is said to be managed by the entity manager.
The set of managed entity instances within an entity manager at any given time is called its persistence
context. Only one Java instance with the same persistent identity may exist in a persistence context at
any time.
For example, if an Employee with a persistent identity (or id) of 158 exists in the persistence context,
then no other object with its id set to 158 may exist within that same persistence context.
Entity managers are configured to be able to persist or manage specific types of objects, read and write
to a given database, and be implemented by a particular persistence provider (or provider for short). It
is the provider that supplies the backing implementation engine for the entire Java Persistence API, from
the EntityManager through to Query implementation and SQL generation.
Obtaining an Entity Manager
An entity manager is always obtained from an EntityManagerFactory.
The following example demonstrates creating an EntityManagerFactory for the persistence unit named
“EmployeeService”:
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("EmployeeService");
Now that we have a factory, we can easily obtain an entity manager from it. The following example
demonstrates creating an entity manager from the factory that we acquired in the previous example:
EntityManager em = emf.createEntityManager();
With this entity manager, we are now in a position to start working with persistent entities.
Bab 9 Java Persistence API (JPA) Page | 118
Operation on Entity
Persisting an Entity
Finding an Entity
Removing an Entity
Updating an Entity
Transaction
Query
Persisting an Entity (INSERT)
Persisting an entity is the operation of taking a transient entity, or one that does not yet have any
persistent representation in the database, and storing its state so that it can be retrieved later.
We are going to start by using the entity manager to persist an instance of Employee.
Here is a code example that does just that:
Employee emp = new Employee(158);
em.persist(emp);
Note: If the entity manager encounters a problem doing this, then it will throw an unchecked
PersistenceException
The following code shows how to incorporate this into a simple method that creates a new employee
and persists it to the database.
public Employee createEmployee(int id, String name, long salary) {
Employee emp = new Employee(id);
emp.setName(name);
emp.setSalary(salary);
em.persist(emp);
return emp;
}
Finding an Entity
Once an entity is in the database, then the next thing one typically wants to do is find it again. In this
section we will show how an entity can be found using the entity manager.
There is really only one line that we need to show:
Employee emp = em.find(Employee.class, 158);
The code for a method that looks up and returns the Employee with a given id:
Bab 9 Java Persistence API (JPA) Page | 119
public Employee findEmployee(int id) {
return em.find(Employee.class, id);
}
Removing an Entity
In order to remove an entity, the entity itself must be managed, meaning that it is present in the
persistence context. This means that the calling application should have already loaded or accessed
the entity and is now issuing a command to remove it.
A simple example for removing an employee is:
Employee emp = em.find(Employee.class, 158);
em.remove(emp);
In our application method for removing an employee, we can check the existence of the employee
before we issue the remove() call:
public void removeEmployee(int id) {
Employee emp = em.find(Employee.class, id);
if (emp != null) {
em.remove(emp);
}
}
Updating an Entity
An entity may be updated in a few different ways, but for now we will illustrate the most common and
simple case. This is the case where we have a managed entity and want to make changes to it.
If we do not have a reference to the managed entity, then we must first obtain one using find() and then
perform our modifying operations on the managed entity.
This code adds $1,000 to the salary of the employee with id 158:
Employee emp = em.find(Employee.class, 158);
emp.setSalary(emp.getSalary() + 1000);
Note the difference between this operation and the others. In this case we are not calling into the entity
manager to modify the object but directly on the object itself.
Bab 9 Java Persistence API (JPA) Page | 120
Method for Updating an Employee
public Employee raiseEmployeeSalary(int id, long raise) {
Employee emp = em.find(Employee.class, id);
if (emp != null) {
emp.setSalary(emp.getSalary() + raise);
}
return emp;
}
Transactions
The typical situation when running inside the Java EE container environment is that the standard Java
Transaction API (JTA) is used. In our example in this chapter, though, we are not running in Java EE.
We are in a Java SE environment, and the transaction service that should be used in Java SE is the
EntityTransaction service.
Example: Beginning and Committing an EntityTransaction
em.getTransaction().begin();
createEmployee(158, "John Doe", 45000);
em.getTransaction().commit();
Queries
In the Java Persistence API, a query is similar to a database query, except that instead of using
Structured Query Language (SQL) to specify the query criteria, we are querying over entities and using a
language called Java Persistence Query Language (JPQL).
A query is implemented in code as a Query object. Query objects are constructed using the
EntityManager as a factory.
A query can be defined either statically or dynamically.
Static Query vs Dynamic Query
A static query is defined in either annotation or XML metadata, and it must include both the query
criteria as well as a userassigned name. This kind of query is also called a named query, and it is later
looked up by its name at the time it is executed.
A dynamic query can be issued at runtime by supplying only the JPQL query criteria. These may be a
little more expensive to execute because the persistence provider cannot do any query preparation
Bab 9 Java Persistence API (JPA) Page | 121
beforehand, but they are nevertheless very simple to use and can be issued in response to program logic
or even user logic.
Following is an example showing how to create a query and then execute it to obtain all of the
employees in the database:
Query query = em.createQuery("SELECT e FROM Employee e");
Collection emps = query.getResultList();
STEPS:
1. We create a Query object by issuing the createQuery() call on the EntityManager and passing in
the JPQL string that specifies the query criteria.
2. To execute the query we simply invoke getResultList() on it. This returns a List (a subinterface of
Collection) containing the Employee objects that matched the query criteria.
Method for Issuing a Query
public Collection<Employee> findAllEmployees() {
Query query = em.createQuery("SELECT e FROM Employee e");
return (Collection<Employee>) query.getResultList();
}
Bab 9 Java Persistence API (JPA) Page | 122
Putting It All Together: EmployeeService.java
Program 28: Method-method Pengelolaan Employee menggunakan JPA - EmployeeService.java
import javax.persistence.*;
import java.util.Collection;
public class EmployeeService {
protected EntityManager em;
public EmployeeService(EntityManager em) {
this.em = em;
}
public Employee createEmployee(int id, String name, long salary)
{
Employee emp = new Employee(id);
emp.setName(name);
emp.setSalary(salary);
em.persist(emp);
return emp;
}
public void removeEmployee(int id) {
Employee emp = findEmployee(id);
if (emp != null) {
em.remove(emp);
}
}
public Employee raiseEmployeeSalary(int id, long raise) {
Employee emp = em.find(Employee.class, id);
if (emp != null) {
emp.setSalary(emp.getSalary() + raise);
}
return emp;
}
public Employee findEmployee(int id) {
return em.find(Employee.class, id);
}
public Collection<Employee> findAllEmployees() {
Query query = em.createQuery("SELECT e FROM Employee e");
return (Collection<Employee>) query.getResultList();
}
}
Bab 9 Java Persistence API (JPA) Page | 123
Run Program: EmployeeTest.java
Program 29: Aplikasi Utama Pengelolaan Employee - EmployeeTest.java
import javax.persistence.*;
import java.util.Collection;
public class EmployeeTest {
public static void main(String[] args) {
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("EmployeeService");
EntityManager em = emf.createEntityManager();
EmployeeService service = new EmployeeService(em);
// create and persist an employee
em.getTransaction().begin();
Employee emp = service.createEmployee(158, "John Doe", 45000);
em.getTransaction().commit();
System.out.println("Persisted " + emp);
// find a specific employee
emp = service.findEmployee(158);
System.out.println("Found " + emp);
// find all employees
Collection<Employee> emps = service.findAllEmployees();
for (Employee e : emps) {
System.out.println("Found employee: " + e);
}
// update the employee
em.getTransaction().begin();
emp = service.raiseEmployeeSalary(158, 1000);
em.getTransaction().commit();
System.out.println("Updated " + emp);
// remove an employee
em.getTransaction().begin();
service.removeEmployee(158);
em.getTransaction().commit();
System.out.println("Removed Employee 158");
// close the EM and EMF when done
em.close();
emf.close();
}
}
Bab 9 Java Persistence API (JPA) Page | 124
Packaging It Up
Now that we know the basic building blocks of the Java Persistence API, we are ready to organize the
pieces into an application that runs in Java SE.
Create a Persistence Unit
The configuration that describes the persistence unit is defined in an XML file called
persistence.xml
Each persistence unit is named, so when a referencing application wants to specify the
configuration for an entity it need only reference the name of the persistence unit that defines
that configuration.
Elements in the persistence.xml File
<persistence>
<persistence-unit name="EmployeeService"
transaction-type="RESOURCE_LOCAL">
<class>examples.model.Employee</class>
<properties>
<property name="toplink.jdbc.driver"
value="org.apache.derby.jdbc.ClientDriver"/>
<property name="toplink.jdbc.url"
value="jdbc:derby://localhost:1527/EmpServDB;create=true"/>
<property name="toplink.jdbc.user" value="app"/>
<property name="toplink.jdbc.password" value="app"/>
</properties>
</persistence-unit>
</persistence>
Referensi Bahasa Pemrograman Java Page | 125
Referensi Bahasa Pemrograman Java
Tipe Data Primitif
Type Bits Bytes Minimum Range Maximum Range
byte 8 1 -128 or -27 127 or 27-1
short 16 2 -32,768 or -215 32,767 or 215-1
int 32 4 -2,147,483,648 or -231 2,147,483,647 or 231-1
long 64 8 -263 263-1
float 32 4 -3.4E38 3.4E38
double 64 8 -1.7E308 1.7E308
char 16 2 n/a n/a
boolean 8 1 n/a n/a
Operator Aritmatika
Operator Name # Operands Description
+ Addition 2 Add two operands
- Subtraction 2 Subtract the right operand from the left
* Multiplication 2 Multiplies the right operand and left operand
/ Division 2 Divides the right operand into the left operand
% Modulus 2 Returns the value that is left over after dividing the right operand into the left operand
++ Increment 1 Adds 1 to the operand (x = x + 1)
-- Decrement 1 Subtracts 1 from the operand (x = x -1)
+ Positive Sign 1 Promotes byte, short, and char types to the int type
- Negative Sign 1 Changes a positive value to negative, and vice versa
Karakter Khusus
Sequence Character
\n New line
\t Tab
\r Return
\” Quotation Mark
\\ Backslash
Referensi Bahasa Pemrograman Java Page | 126
Assignment Operators
Operator Name Description
= Assignment Assigns a new value to the variable
+= Addition Adds the operand to the starting variable value of the variable and assigns the result to the variable
-= Subtraction Subtracts the operand from the starting value of the variable and assigns the result to the variable
*= Multiplication Multiplies the operand by the starting value of the variable and assigns the result to the variable
/= Division Divides the operand by the starting value of the variable and assigns the result to the variable
%= Modulus Derives the value that is left over after dividing the right operand by the value in the variable, and then assigns this value to the variable
Ekspresi Boolean
Operator Name Description
== Equality Returns a true value if both operands are equals
!= Inequality Returns a true value if the left and right operands are not equal
> Greater Than Returns a true value if the left operand is greater than the right operand
< Less Than Return a true value if the left operand is less than the right operand
>= Greater Than Or Equal Returns a true value if the left operand is greater than or equal to the right operand
<= Less Than or Equal Return a true value if the left operand is less than or equal to the right operand
Operator AND dan OR
Operator Name Example Description
&& AND a && b true if both a and b are true
|| OR a || b true if either a or b (or both) is true
^ XOR a ^ b true if only a or b is true
! NOT !a true if a is not true
String
String bukan merupakan tipe data primitif melainkan tipe data reference
Contoh: String message1 = "Invalid data entry";
Referensi Bahasa Pemrograman Java Page | 127
Untuk menyambung (concat) dua/lebih string, gunakan operator +
Untuk membandingkan 2 buah String, kita harus menggunakan method “equals” atau
“equalgnoreCase” yang dimiliki oleh kelas String.
Variabel & Assignment
Sintaks: tipeData namaVariabel
Contoh:
int counter = 1;
boolean valid = false;
char letter = ‘A’;
char letter = 65;
double distance = 3.65e+9;
Method print, println,dan printf
print posisi akhir kursor berada di garis yang sama
o Contoh: System.out.print ("Hello World");
println posisi akhir kursor berada di garis yang baru (seolah menekan enter)
o Contoh: System.out.println("Hello World");
printf print dalam bentuk format tertentu (f = formatted)
o Contoh: System.out.printf("%s\n %s\n", "Hello", "World");
Using Console for Input & Output
Dengan java versi 5, cara paling mudah untuk mendapatkan input dari console adalah dengan
menggunakan Scanner class
Untuk menampilkan output ke console adalah menggunakan method (fungsi)
System.out.println
Sebelum menggunakan Scanner class, kita harus melakukan proses import sbb:
import java.util.Scanner;
Untuk membaca input dari console, kita buat objek scanner dengan cara menuliskannya sbb:
Scanner sc = new Scanner(System.in);
Ada 4 buah methods dari objek Scanner (yaitu sc) yang dapat kita gunakan sesuai kebutuhan:
Method Description
Referensi Bahasa Pemrograman Java Page | 128
next() or nextLine() Reads a String value from the user
nextInt() Reads an integer value from the user
nextDouble() Reads a double value from the user
nextBoolean() Reads a boolean value from the user
Struktur Kontrol Selection
Java memiliki 5 conditional statements yaitu: if, else, switch, case, dan break.
1. IF
2. IF-ELSE
3. SWITCH-CASE
switch (expr) { //note: expr hanya boleh berupa int atau char
case value1:
statement_1a;
statement_1b;
break;
case value2:
Referensi Bahasa Pemrograman Java Page | 129
statement_2;
break;
default:
statement_da;
statement_db;
break;
}
Struktur Kontrol Loop
1. While Loop
while (true){
// statements
}
2. Do-While Loop
do {
//statements (body)
}
while (expression);
3. For Loop
Note:
Init: statement untuk menginisialisasi variabel loop, dieksekusi sekali
Cont: Ekspresi Boolean untuk keberlanjutan loop, dieksekusi sebelum pengulangan
Adj: statement untuk meng-adjust variabel loop, dieksekusi setelah pengulangan
Array
Array adalah variabel yang yang dikelompokkan bersama dalam suatu nama.
Referensi Bahasa Pemrograman Java Page | 130
Ada 4 Tahap Manipulasi Array:
1. Array declaration
2. Array creation
3. Array initialization
4. Array processing
Contoh Deklarasi Array:
String[] students; // An array of String variables
int[] values; // An array of integer variables
boolean[] truthTable; // An array of boolean variables
char[] grades; // An array of character variables
Contoh Pembuatan Array:
String[] names = new String[10];
Int[] numbers = new int[20];
Contoh Inisialisasi Array:
Cara 1: assign satu per satu:
String[] days = new String[7];
days[0] = "Sunday";
days[1] = "Monday";
days[2] = "Tuesday";
days[3] = "Wednesday";
days[4] = "Thursday";
days[5] = "Friday";
days[6] = "Saturday";
Cara 2: shorthand way menggunakan { }:
String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday" };
Referensi Bahasa Pemrograman Java Page | 131
Contoh Pemrosesan & Menampilkan Isi Array Menggunakan FOR-LOOP:
String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday","Friday", "Saturday" };
for (int i = 0; i < days.length; i++{
System.out.println(days[i]);
}
Contoh Pemrosesan & Menampilkan Array Menggunakan: Enhanced FOR-LOOP (FOREACH):
String[] days = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday","Friday", "Saturday" };
for (String dayElement: days){
System.out.println(dayElement);
}
Referensi Bahasa Pemrograman Java Page | 132
Exception Handling
Exceptional adalah kesalahan (error) yang disebabkan oleh situasi yang TIDAK DAPAT DIGARANSI
100% OKE ketika program dijalankan (saat runtime)
An exception is an object that’s created when an error occurs in a Java program and Java can’t
automatically fix the error.
The exception object contains information about the type of error that occurred.
Java Exception Hierarchy:
Handling Exception: Try-Catch
We catch an exception by using a try-catch statement, which has this general form:
try {
// statements that can throw exceptions
}
catch (exception-type identifier) {
// statements executed when exception is thrown
}
Referensi Bahasa Pemrograman Java Page | 133
Contoh Penanganan Exception pada kasus “Divide-by-Zero”:
public class DivideByZero {
public static void main(String[] args){
int a = 5;
int b = 0; // you know this won’t work
try {
int c = a / b; // but you try it anyway
}
catch (ArithmeticException e){
System.out.println("Oops, you can’t divide by zero.");
}
}
}
Catching All Exceptions
If we have some code that might throw several different types of exceptions, and we want to provide
specific processing for some but general processing for all the others, we can code the try statement as
following:
try {
// statements that might throw several types of exceptions
}
catch (InputMismatchException e) {
// statements that process InputMismatchException
}
catch (IOException e) {
// statements that process IOException
}
catch (Exception e) {
// statements that process all other exception types
}
Referensi Bahasa Pemrograman Java Page | 134
Finally
A finally block is a block that appears after all of the catch blocks for a statement.
It’s executed whether or not any exceptions are thrown by the try block or caught by any catch
blocks.
The basic framework for a try statement with a finally block is this:
try {
// statements that can throw exceptions
}
catch (exception-type identifier){
// statements executed when exception is thrown
}
finally{
// statements that are executed
// whether or not exceptions occur
}
Konsep Dasar PBO Page | 135
Konsep Dasar Pemrograman Berorientasi Objek
CLASS & OBJECT
Kita dapat membuat banyak OBJECT dari satu CLASS
Untuk membuat banyak OBJECT, kita cukup gunakan keyword “new” berulang kali
Misal:
Rekening CLASS
myRekening OBJECT
Membuat CLASS REKENING
public class Rekening {
// Method untuk menampilkan pesan kepada pemilik Rekening
public void tampilkanPesan() {
System.out.println("Selamat Datang di Rekening Anda!" );
} // end method tampilkanPesan
} // end class Rekening
Membuat OBJECT myRekening: new
public class RekeningTest {
// main method begins program execution
public static void main( String args[] ) {
// 1. buat objek Rekening beri nama myRekening
Rekening myRekening = new Rekening();
// 2. panggil method tampilkanPesan yang dimiliki Rekening
myRekening.tampilkanPesan();
} // end main
} // end class RekeningTest
Konsep Dasar PBO Page | 136
Method
Method adalah suatu sarana komunikasi antar objek di dalam suatu program.
Contoh method “tampilkanPesan”:
public void tampilkanPesan( String namaAnda){
//kode program
}
CONSTRUCTOR
Constructor merupakan suatu method khusus yang dimiliki oleh setiap class, dan secara default
nama method khusus ini sama dengan nama class ybs.
Method khusus ini selalu didefinisikan sebagai public dan tidak memiliki return type.
Biasanya Constructor digunakan untuk melakukan proses inisialisasi.
Contoh Inisialisasi Variabel di dalam Constructor:
public class DaftarNilai {
private String namaMataKuliah;
public DaftarNilai(String namaInisial) {
namaMataKuliah = namaInisial;
}
public void setMataKuliah( String nama ){
namaMataKuliah = nama; // store the course name
}
public String getMataKuliah(){
return namaMataKuliah;
}
}
SET dan GET methods
Suatu CLASS biasanya memiliki beberapa methods yang berfungsi untuk memanipulasi nilai Instance
Variable.
Method ini biasanya diberi nama dengan awalan set dan get disertai dengan nama Instance Variable
ybs.
Misalnya: Class DaftarNilai memiliki instance variable “namaMataKuliah”
Konsep Dasar PBO Page | 137
Maka, kita buatkan methods untuk memanipulasi instance variable tersebut sbb:
o setNamaMataKuliah
o getNamaMataKuliah
Contoh:
public class DaftarNilai {
private String namaMataKuliah; // course name for this DaftarNilai
// method to set the course name
public void setMataKuliah( String nama ){
namaMataKuliah = nama; // store the course name
}
// method to retrieve the course name
public String getMataKuliah(){
return namaMataKuliah;
}
}
Access Modifier
Semua anggota CLASS (method dan atribut) harus memiliki access modifier.
Java memiliki 4 Access Modifier:
o public (+)
o private (-)
o protected (#)
o package (~)
Jika anggota suatu CLASS dideklarasikan sebagai public, maka ia dapat diakses dari manapun juga,
termasuk dari class lain.
Jika anggota suatu CLASS dideklarasikan sebagai private, maka ia tidak dapat diakses dari tempat
lain, kecuali di dalam CLASS itu sendiri.
Konsep Inheritance
Pada dasarnya, inheritance merupakan feature penting dari OOP, yaitu merupakan suatu bentuk
software reuse di mana class yang baru dibuat dengan cara memanfaatkan anggota (atribut &
method) class yang telah ada.
Konsep Dasar PBO Page | 138
Dengan menggunakan inheritance, programmers akan menghemat banyak waktu pada saat
membuat software.
Pada saat membuat suatu class baru, programmer dapat men-desain class tersebut sedemikian rupa
agar meng-inherit (menuruni sifat) anggota class yang telah ada.
Class yang telah ada ini disebut superclass, dan class yang baru disebut subclass.
Untuk melakukan proses inheritance dari subclass kepada superclass, kita cukup gunakan keyword:
EXTENDS
Contoh Inheritance hierarchy untuk university:
Contoh Kode Inheritance:
// SUPERCLASS:
public class CommunityMember{
}
// SUBCLASS:
public class Employee extends CommunityMember{
}
Keterangan: Dengan menggunakan extends, semua private/protected variables & methods yang
dimiliki oleh class CommunityMember, akan secara otomatis dapat dimiliki dan diakses oleh
class Employee.
Abstract Class
Java lets us define a method without implementing it by declaring the method with the abstract
modifier.
Konsep Dasar PBO Page | 139
Implementasi abstract method dilakukan di kelas turunannya.
Contoh class diagram yang menggambarkan abstract class SHAPE dan 2 concrete class (CIRCLE &
RECTANGLE) yang akan mengimplementasikan semua abstract method yang ada pada class SHAPE:
Keterangan: implementasi abstract method area() dan circumference() akan ada di class Circle &
Rectangle.
Konsep Polymorphism
Polymorphism berasal dari bahasa Yunani yang artinya “different form” atau berbeda bentuk.
Polymorphism merupakan suatu feature di OOP di mana kita dapat memiliki objek berbeda yang
berasal dari superclass yang sama.
Contoh penggunaan Polymorphism:
public class AbstractDemo{
Shape s1 = new Circle();
Shape s2 = new Rectangle();
double area1 = s1.area();
double area2 = s2.area();
}
Keterangan Program:
o Kedua s1 dan s2 merupakan objek bertipe “Shape”, akan tetapi mereka memiliki bentuk
Konsep Dasar PBO Page | 140
yang berbeda (polymorphism).
o s1 berbentuk Circle
o s2 berbentuk Rectangle
o Pada saat run-time & method “area()” dipanggil, compiler akan menentukan method
“area()” mana yang harus dijalankan. (dynamic binding)
o s1 menghitung area dari Circle
o s2 menghitung area dari Rectangle
Interface
Java supports single inheritance. That means a subclass in Java can have only one superclass.
However, if multiple inheritance is needed, Java provides a solution: use an interface.
An interface is a template that contains some method declarations. It provides only declarations
for the methods, and no implementation.
Untuk mendefinisikan interface, kita gunakan keyword interface, sbb:
interface <InterfaceName> {
<dataType1> <var1>;
<dataType2> <var2>;
<ReturnType1> <methodName1> ( );
<ReturnType2> <methodName2> (<parameters>);
} // interface definition ends here.
Semua methods yang ada di dalam interface secara implisit merupakan public dan abstract.
Variabel yang ada didefinisikan di dalam interface merupakan constants (tidak dapat diubah
nilainya) dan dapat diakses oleh semua instance class yang mengimplementasikan interface tsb.
Dengan kata lain, variabel tersebut bersifat public, final, dan static.