Tampilkan database MySQL ke JTable Java dengan NetBean 5.0

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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s