Code:
import java.awt.*;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.*;
public class SimpleTable extends JPanel {
private String user = "root";
private String pass = "";
private String url = "jdbc:mysql://localhost/penjualan";
private String[] header = {"Item Code","Description","Item Group"};
private Connection conn;
private Statement stmt;
private ResultSet rs;
private JTable table;
JScrollPane scrollTable;
private Object[][] dataTable = null;
public SimpleTable() {
super(new BorderLayout());
table = new JTable();
scrollTable = new JScrollPane();
scrollTable.setViewportView(table);
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnfe) {
System.err.println("Class Driver tidak ditemukan : " + cnfe.getMessage());
}
try {
conn = DriverManager.getConnection(url, user, pass);
stmt = conn.createStatement();
String query = "SELECT * FROM tbarang";
rs = stmt.executeQuery(query);
ResultSetMetaData meta = rs.getMetaData();
int col = meta.getColumnCount();
int baris = 0;
while(rs.next()) {
baris = rs.getRow();
}
dataTable = new Object[baris][col];
int x = 0;
rs.beforeFirst();
while(rs.next()) {
dataTable[x][0] = rs.getString("itemcode");
dataTable[x][1] = rs.getString("description");
dataTable[x][2] = rs.getString("itemgroup");
x++;
}
table.setModel(new DefaultTableModel(dataTable, header));
add(scrollTable, BorderLayout.NORTH);
stmt.close();
rs.close();
conn.close();
} catch (SQLException se) {
System.err.println("Kesalahan perintah SQL : " + se.getMessage());
}
}
private static void tampilkanGUI() {
JFrame frame = new JFrame("Contoh Data dari Database");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SimpleTable content = new SimpleTable();
content.setOpaque(true);
frame.setContentPane(content);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String args[]) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
tampilkanGUI();
}
});
}
http://www.goldenstudios.or.id/forum/showthread.php?tid=1734