The program I am working on contains two classes, GUI & DatabaseHelper. The table model used is DefaultTableModel.
The GUI contains consists of a simple JTable. It is initialised with data from the DatabaseHelper on startup. This works.
However, when trying to load new data into the table, it is not quite so straight forward.
My approach thus far has been:
model = DatabaseHelper.LoadData() // returns a default table model with new data.
tabel = new JTable();
tabel.setModel();
What happens now is that the loaded data is appended onto the already existing JTable.
If it is possible I would like to implement a solution using only the default table model. Thank you for any suggestions!
EDIT:
public void initGUI(){
setJMenuBar(makeMenuBar());
container = new JPanel(new BorderLayout());
model = db.initialiseTable(); // Load initialisation data from the database
table = new JTable();
table.setModel(model);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
scrollPane = new JScrollPane(table);
container.add(scrollPane, BorderLayout.CENTER);
add(container);
}
Returning a new model from database:
public DefaultTableModel loadData(){
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/version1", "root", "root");
System.out.println("\nDatabase Connection Established.\n");
String query = "SELECT * FROM table WHERE test_number = 2";
stmt = con.createStatement();
rs = stmt.executeQuery( query );
md = rs.getMetaData();
columns = md.getColumnCount();
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <=columns-1; i++){
row.addElement( rs.getObject(i+1) );
}
data.addElement( row );
}
}catch(SQLException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
columnNames.add(" ");
columnNames.add("Column 1");
columnNames.add("Column 2");
DefaultTableModel model = new DefaultTableModel(data, columnNames);
return model;
}
ActionPerformed, code handles new model returned from the DatabaseHelper
model = new DefaultTableModel();
model = db.loadData();
table = new JTable();
table.setModel(model);