Selasa, 14 Agustus 2012
Demo List
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class DemoList implements ActionListener {
public JFrame frame;
public JList list;
public JButton btnTambah, btnHapus;
public JTextField tfItem;
public JScrollPane scroller;
public DemoList() {
tfItem = new JTextField(12);
tfItem.setLocation(10,20);
tfItem.setSize(tfItem.getPreferredSize());
DefaultListModel lm;
lm = new DefaultListModel();
lm.addElement("Java");
lm.addElement("C");
lm.addElement("C++");
list = new JList(lm);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scroller = new JScrollPane(list);
scroller.setLocation(10, 43);
scroller.setSize(new Dimension(135, 170));
btnTambah = new JButton("Tambah");
btnTambah.setLocation(150, 20);
btnTambah.setSize(btnTambah.getPreferredSize());
btnTambah.addActionListener(this);
btnTambah.setMnemonic('T');
btnHapus = new JButton("Hapus");
btnHapus.setLocation(150, 50);
btnHapus.setSize(btnTambah.getPreferredSize());
btnHapus.addActionListener(this);
btnHapus.setMnemonic('H');
}
public void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
frame = new JFrame("Demo JList");
frame.setLayout(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(tfItem);
frame.getContentPane().add(scroller);
frame.getContentPane().add(btnTambah);
frame.getContentPane().add(btnHapus);
frame.setBounds(0, 0, 430, 350);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == btnTambah) {
String s = tfItem.getText().trim();
if (!s.equals("")) {
((DefaultListModel) list.getModel()).addElement(s);
}
if (list.getModel().getSize() == 1) {
btnHapus.setEnabled(true);
}
} else {
int index = list.getSelectedIndex();
if (index == -1) {
JOptionPane.showMessageDialog(frame,
"Anda harus memilih salah satu item " +
"terlebih dahulu");
return;
}
((DefaultListModel)list.getModel()).remove(index);
int size = list.getModel().getSize();
if (size == 0) {
btnHapus.setEnabled(false);
} else {
if (index == list.getModel().getSize()) {
index--;
}
list.setSelectedIndex(index);
list.ensureIndexIsVisible(index);
}
}
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
DemoList app = new DemoList();
app.createAndShowGUI();
}
});
}
}
Langganan:
Posting Komentar (Atom)
Tidak ada komentar:
Posting Komentar