display a TableModel as a JTable
Given three classes:
View JFrame for the GUI
MyTableModel represents the data
DBDemo has db connection
In View there's:
private javax.swing.JTable db;
db.setModel(MyTableModel.getInstance());
Should DBDemo, which connects to the actual database, morph into an inner
class for MyTableModel, perhaps?
From the view, how do I make the JTable synchronize with the MyTableModel
instance? A listener of some sort?
code:
thufir@arrakis:~$
thufir@arrakis:~$ cat NetBeansProjects/ubuntu-jdbc/src/a00720398/model/
MyTableModel.java
package a00720398.model;
import javax.swing.table.*;
public class MyTableModel extends AbstractTableModel {
private static final TableModel INSTANCE = new MyTableModel();
private MyTableModel() {}
public static TableModel getInstance() {
return INSTANCE;
}
public int getColumnCount() {
return 1; //dummy
}
public String getColumnName(int i) {
return "foo";
}
public int getRowCount() {
return 3;
}
public Object getValueAt(int row, int col) {
return new Object(); //critical to fill this in
}
}
thufir@arrakis:~$
thufir@arrakis:~$ cat NetBeansProjects/ubuntu-jdbc/src/a00720398/model/
DBDemo.java
package a00720398.model;
import java.sql.*;
import java.util.Properties;
public class DBDemo {
private static final String DBCLASSNAME = "com.mysql.jdbc.Driver";
private static final String CONNECTION = "jdbc:mysql://localhost/
COFFEEBREAK";
public void db() throws ClassNotFoundException, SQLException {
Class.forName(DBCLASSNAME);
Properties p = new Properties();
p.put("user", "java");
p.put("password", "password");
Connection c = DriverManager.getConnection(CONNECTION, p);
Statement stmt = c.createStatement();
stmt.executeUpdate("CREATE TABLE COFFEES " +
"(COF_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, " +
"SALES INTEGER, TOTAL INTEGER)");
stmt.executeUpdate("INSERT INTO COFFEES " +
"VALUES ('Colombian', 101, 7.99, 0, 0)");
stmt.executeUpdate("INSERT INTO COFFEES " +
"VALUES ('French_Roast', 49, 8.99, 0, 0)");
stmt.executeUpdate("INSERT INTO COFFEES " +
"VALUES ('Espresso', 150, 9.99, 0, 0)");
stmt.executeUpdate("INSERT INTO COFFEES " +
"VALUES ('Colombian_Decaf', 101, 8.99, 0, 0)");
stmt.executeUpdate("INSERT INTO COFFEES " +
"VALUES ('French_Roast_Decaf', 49, 9.99, 0, 0)");
String query = "SELECT COF_NAME, PRICE FROM COFFEES";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String s = rs.getString("COF_NAME");
float n = rs.getFloat("PRICE");
System.out.println(s + " " + n);
}
String updateString = "UPDATE COFFEES " +
"SET SALES = 75 " +
"WHERE COF_NAME LIKE 'Colombian'";
stmt.executeUpdate(updateString);
c.close();
}
}
thufir@arrakis:~$
thufir@arrakis:~$
thanks,
Thufir