JTable
digunakan untuk menampilkan data dalam bentuk tabel, suatu bentuk yang banyak
digunakan dalam pemrograman database.
berikut contoh sintaknya :
import
java.awt.event.ActionEvent;
import
java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.table.*;
public class table extends JFrame implements ActionListener {
DefaultTableModel tableModel = new DefaultTableModel();
JTable table = new JTable();
JButton bt1 = new JButton("Tambah Baris Kosong");
JButton bt2 = new JButton("Tambah Baris");
public table() {
setTitle("Contoh Penggunaan JTable");
setSize(600, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
buatTampilan();
setVisible(true);
}
void buatTampilan() {
table.setModel(tableModel);
tableModel.addColumn("Kolom 1");
tableModel.addColumn("Kolom 2");
tableModel.addColumn("Kolom 3");
tableModel.addColumn("Kolom 4");
tableModel.addRow(new Object[] { "Data Kolom 0 Baris 0",
"Data Kolom 1 Baris
0", "Data Kolom 2 Baris
0",
"Data Kolom 3 Baris
0" });
tableModel.addRow(new Object[] { "Data Kolom 0 Baris 1",
"Data Kolom 1 Baris
1", "Data Kolom 2 Baris
1",
"Data Kolom 3 Baris
1" });
tableModel.addRow(new Object[] { "Data Kolom 0 Baris 2",
"Data Kolom 1 Baris
2", "Data Kolom 2 Baris
2",
"Data Kolom 3 Baris
2" });
JScrollPane scroll = new JScrollPane();
scroll.getViewport().add(table);
JPanel panel = new JPanel();
panel.add(bt1);
bt1.addActionListener(this);
panel.add(bt2);
bt2.addActionListener(this);
getContentPane().add(panel, "North");
getContentPane().add(scroll);
}
public static void main(String[] args) {
new table();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == bt1) {
tableModel.addRow(new Object[] {});
} else if (e.getSource() == bt2) {
int i = tableModel.getRowCount();
tableModel.addRow(new Object[] { "Data Kolom 0 Baris " + i,
"Data Kolom 1 Baris
" + i, "Data Kolom 2 Baris
" + i,
"Data Kolom 3 Baris
" + i
});
}
}
}
0 komentar:
Posting Komentar