Tugas 9 PBO C Error Handling
Nama : Dewangga Dharmawan
NRP : 05111940000029
Kelas : PBO C
Dosen : Fajar Baskoro
Program yang akan dicoba errornya adalah Address Book oleh David J. Barnes dan Michael Kolling, sebagian diambil dari buku Object FIrst Java. Sebagian ditemukan di Gitlab via Google
Diagram Kelas Address Book
Class AddressBookDemo
/**
* Class ini mengisikan sampel data input program AddressBook
* (Sebagian program dibuat oleh David J. Barnes dan Michael Kolling)
* (Sisanya memiliki sedikit kombinasi)
*
* @author (Dewangga Dharmawan)
* @version (21/12/2020)
*/
public class AddressBookDemo
{
private AddressBook book;
private AddressBookGUI interact;
//Sample data (Ketiganya merupakan string)
public AddressBookDemo()
{
ContactDetails[] sampleDetails = {
new ContactDetails("nova", "555-1220", "Almagano Street, Torn City")
};
book = new AddressBook();
for(ContactDetails details : sampleDetails)
book.addDetails(details);
//GUI address book
interact = new AddressBookGUI(book);
}
//Metode menampilkan address book
public void showInterface()
{
interact.setVisible(true);
}
//Mengembalikan sample address book
public AddressBook getBook()
{
return book;
}
}
Class AddressBookGUI
/**
* Class ini untuk memberikan GUI untuk program
*
* @author (Dewangga Dharmawan)
* @version (21/12/2020)
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
public class AddressBookGUI extends JFrame
{
//Deklarasi ukuran frame dan alamat yang akan ditampilkan dan diubah
private static final int PREFERRED_WIDTH = 500,
PREFERRED_HEIGHT = 500;
private static final Dimension PREFERRED_SIZE = new Dimension(PREFERRED_WIDTH, PREFERRED_HEIGHT);
private AddressBook book;
//Metode membuat panel
public AddressBookGUI(AddressBook book)
{
this.book = book;
setTitle("Buku Ungu");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev)
{
setVisible(false);
}
});
final Container contentPane = getContentPane();
JTabbedPane tabbedArea = new JTabbedPane();
tabbedArea.add("Cari", setupSearchArea());
tabbedArea.add("Tambah", setupDataEntry());
tabbedArea.add("Tampil", setupListArea());
contentPane.add(tabbedArea);
setSize(PREFERRED_SIZE);
}
//Menampilkan layar jika ditutup
public void showWindow()
{
setVisible(true);
}
//Mengembalikan ukuran layar
public Dimension getPreferredSize()
{
return PREFERRED_SIZE;
}
//Menampilkan layar memasukan data
//Sekaligus antara menghapus atau menambah data
private Container setupDataEntry()
{
Box nameLabelArea = Box.createHorizontalBox();
nameLabelArea.add(new JLabel("Nama", JLabel.LEFT));
nameLabelArea.add(Box.createGlue());
final JTextField nameField = new JTextField(50);
Box nameArea = Box.createVerticalBox();
nameArea.add(nameLabelArea);
nameArea.add(nameField);
Box phoneLabelArea = Box.createHorizontalBox();
phoneLabelArea.add(new JLabel("Telepon", JLabel.LEFT));
phoneLabelArea.add(Box.createGlue());
final JTextField phoneField = new JTextField(50);
Box phoneArea = Box.createVerticalBox();
phoneArea.add(phoneLabelArea);
phoneArea.add(phoneField);
Box addressLabelArea = Box.createHorizontalBox();
addressLabelArea.add(new JLabel("Alamat", JLabel.LEFT));
addressLabelArea.add(Box.createGlue());
Box addressArea = Box.createVerticalBox();
final JTextArea address = new JTextArea(10, 50);
addressArea.add(addressLabelArea);
addressArea.add(address);
Box singleLineFields = Box.createVerticalBox();
singleLineFields.add(nameArea);
singleLineFields.add(phoneArea);
JPanel detailsPanel = new JPanel();
detailsPanel.setLayout(new BorderLayout());
detailsPanel.add(singleLineFields, BorderLayout.NORTH);
detailsPanel.add(addressArea, BorderLayout.CENTER);
JPanel buttonArea = new JPanel();
JButton add = new JButton("Tambah");
JButton clear = new JButton("Hapus");
add.addActionListener(e -> {
book.addDetails(
new ContactDetails(nameField.getText(),phoneField.getText(),
address.getText()));
});
clear.addActionListener(e -> {
nameField.setText("");
phoneField.setText("");
address.setText("");
});
buttonArea.add(add);
buttonArea.add(clear);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(detailsPanel, BorderLayout.CENTER);
panel.add(buttonArea, BorderLayout.SOUTH);
return panel;
}
//Menampilkan layar mencari entri
private Container setupSearchArea()
{
//Bagian memasukan yang akan dicari
Box searchLabelArea = Box.createHorizontalBox();
searchLabelArea.add(new JLabel("Cari", JLabel.LEFT));
searchLabelArea.add(Box.createGlue());
final JTextField searchField = new JTextField(50);
Box searchArea = Box.createHorizontalBox();
searchArea.add(searchLabelArea);
searchArea.add(searchField);
//Menampilkan pencarian yang sesuai
final JTextArea resultList = new JTextArea(10, 50);
resultList.setEditable(false);
JScrollPane scrollArea =
new JScrollPane(resultList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
//Jika ada perubahan, maka akan dilakukan pencarian ulang
searchField.getDocument().addDocumentListener(new DocumentListener(){
public void changedUpdate(DocumentEvent ev)
{
research();
}
public void insertUpdate(DocumentEvent ev)
{
research();
}
public void removeUpdate(DocumentEvent ev)
{
research();
}
//Jika yang dicari kosong, maka datanya akan dihapus
private void research()
{
String searchString = searchField.getText();
StringBuilder buffer = new StringBuilder();
if(searchString.length() > 0)
{
ContactDetails[] results = book.search(searchString);
for(int i = 0; i < results.length; i++)
buffer.append(results[i].toString()).append("\n\n");
}
resultList.setText(buffer.toString());
}
});
JPanel listArea = new JPanel();
listArea.setLayout(new BorderLayout());
listArea.add(searchArea, BorderLayout.NORTH);
listArea.add(scrollArea, BorderLayout.CENTER);
return listArea;
}
//Menampilkan layar daftar nama, alamat, dan nomor telepon
private Container setupListArea()
{
final JTextArea details = new JTextArea(10, 50);
details.setEditable(false);
JScrollPane scrollArea =
new JScrollPane(details, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JPanel buttonArea = new JPanel();
JButton list = new JButton("Daftar"), clear = new JButton("Bersihkan");
list.addActionListener(e -> details.setText(book.listDetails()));
clear.addActionListener(e -> details.setText(""));
buttonArea.add(list);
buttonArea.add(clear);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add(scrollArea, BorderLayout.CENTER);
panel.add(buttonArea, BorderLayout.SOUTH);
return panel;
}
}
Class ContactDetails
/**
* Class ini menampilkan nama, alamat, dan nomor telepon
*
* @author (Dewangga Dharmawan)
* @version (21/12/2020)
*/
public class ContactDetails implements Comparable<ContactDetails>
{
private String name, phone, address;
//Metode menyiapkan susunan nama, alamat, dan nomor telepon
//Jika ada white space (spasi), dihapuskan
public ContactDetails(String name, String phone, String address)
{
//Jika null, menggunakan string kosong
if(name == null)
name = "";
if(phone == null)
phone = "";
if(address == null)
address = "";
this.name = name.trim();
this.phone = phone.trim();
this.address = address.trim();
//Mengecek apabila nama, nomor telepon, dan alamat ada
if(this.name.length() == 0 || this.phone.length() == 0 || this.address.length() == 0)
{
throw new IllegalStateException("Ada yang masih kosong");
}
}
//Mengembalikan nama
public String getName()
{
return name;
}
//Mengembalikan alamat
public String getAddress()
{
return address;
}
//Mengembalikan nomor telepon
public String getPhone()
{
return phone;
}
//Metode mengecek persamaan antara dua objek
public boolean equals(Object other)
{
if(other instanceof ContactDetails)
{
ContactDetails otherDetails = (ContactDetails) other;
return name.equals(otherDetails.getName()) &&
phone.equals(otherDetails.getPhone()) &&
address.equals(otherDetails.getAddress());
}
else
return false;
}
//Membandingkan detil objek untuk mengurutkan daftar
public int compareTo(ContactDetails otherDetails)
{
int comparison = name.compareTo(otherDetails.getName());
if(comparison != 0)
return comparison;
comparison = phone.compareTo(otherDetails.getPhone());
if(comparison != 0)
return comparison;
return address.compareTo(otherDetails.getAddress());
}
//Mengembalikan tampilan nama, nomor telepon, dan alamat
public String toString()
{
return name + "\n" + phone + "\n" + address;
}
//Membuat kode hashcode untuk menyimpan kontak
public int hashCode()
{
int code = 17;
code = 37 * code + name.hashCode();
code = 37 * code + phone.hashCode();
code = 37 * code + address.hashCode();
return code;
}
}
Class AddressBook
/**
* Class untuk menyimpan beberapa kontak berdasarkan nama dan nomor telepon
*
* @author (Dewangga Dharmawan)
* @version (21/12/2020)
*/
import java.util.*;
public class AddressBook
{
//Deklarasi penyimpanan kontak dan banyaknya
private TreeMap<String, ContactDetails> book;
private int numberOfEntries;
//Inisialisasi buku kontak
public AddressBook()
{
book = new TreeMap<>();
numberOfEntries = 0;
}
//Memberikan objek kontak
public ContactDetails getDetails(String key)
{
//Mengecek apabila keynya kosong atau tidak
if(key == null)
{
throw new IllegalArgumentException(
"ada nilai null dalam getDetails");
}
if(key.trim().length() == 0)
{
throw new IllegalArgumentException(
"Nilai kosong masuk dalam getDetails");
}
return book.get(key);
}
//Memberikan key, yang mana digunakan atau tidak
public boolean keyInUse(String key)
{
return book.containsKey(key);
}
//Menambahkan detil buku kontak
public void addDetails(ContactDetails details)
{
if(details != null)
{
book.put(details.getName(), details);
book.put(details.getPhone(), details);
numberOfEntries++;
}
}
//Mengubah detail kontak tertentu
public void changeDetails(String oldKey, ContactDetails details)
{
if(keyInUse(oldKey) && details != null)
{
removeDetails(oldKey);
addDetails(details);
}
}
//Menampilkan kontak dengan search tertentu
public ContactDetails[] search(String keyPrefix)
{
List<ContactDetails> matches = new LinkedList<>();
if(keyPrefix != null)
{
SortedMap<String, ContactDetails> tail = book.tailMap(keyPrefix);
Iterator<String> it = tail.keySet().iterator();
boolean endOfSearch = false;
while(!endOfSearch && it.hasNext())
{
String key = it.next();
if(key.startsWith(keyPrefix))
matches.add(book.get(key));
else
endOfSearch = true;
}
}
ContactDetails[] results = new ContactDetails[matches.size()];
matches.toArray(results);
return results;
}
//Memberikan banyak kontak dalam buku
public int getNumberOfEntries()
{
return numberOfEntries;
}
//Menghapus kontak
public void removeDetails(String key)
{
//Mengecek apabila ada key yang tidak valid
if(keyInUse(key))
{
ContactDetails details = book.get(key);
book.remove(details.getName());
book.remove(details.getPhone());
numberOfEntries--;
}
}
//Menampilkan semua kontak secara daftar
public String listDetails()
{
StringBuilder allEntries = new StringBuilder();
Set<ContactDetails> sortedDetails = new TreeSet<>(book.values());
for(ContactDetails details : sortedDetails)
allEntries.append(details).append("\n\n");
return allEntries.toString();
}
}
Implementasi
Menjalankan program dengan menggunakan Class AddressBookDemo lalu menekan showInterface()
Memasukan input kosong (Pada salah satu input), dan menampilkan status errornya
Komentar
Posting Komentar