I currently have 2 classes, one displaying the GUI and one is to get items from the database. My code is as follows:
This code is to display the JTable in my GUI
public void table() {
if(SOMR.tableCall() == true) {
this.columnNames = SOMR.getCol();
this.data = SOMR.getData();
JTable table = new JTable(data, columnNames)
{
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
JScrollPane scrollPane = new JScrollPane( table );
add( scrollPane, BorderLayout.CENTER );
}
}
and this code is to retrieve the items and pass them to the above codes to display the items retrieved to the JTable
public boolean table() {
Connection connection = null;
ResultSet resultSet = null;
PreparedStatement preparedStatement = null;
try
{
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:db");
preparedStatement = connection.prepareStatement("SELECT item1, item2, item3 FROM menu WHERE can = ? AND id = ?");
preparedStatement.setInt(1, can);
preparedStatement.setInt(2, id);
resultSet = preparedStatement.executeQuery();
ResultSetMetaData md = resultSet.getMetaData();
columns = 3;//md.getColumnCount();
for(int i = 1; i<=columns; i++) {
columnNames.addElement(md.getColumnName(i));
}
while(resultSet.next()) {
row = new Vector(columns);
for (int i = 1; i<=columns; i++) {
row.addElement(resultSet.getObject(i));
}
data.addElement(row);
}
tablecall = true;
return tablecall;
}
catch (Exception ex)
{
tablecall = false;
ex.printStackTrace();
}
finally
{
try
{
resultSet.close();
preparedStatement.close();
connection.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
return tablecall;
}
I have followed the way of displaying the JTable from Table From Database, however I do not really know how to go about inserting, updating and deleting a row from the JTable and update in the database, then refresh the JTable to display from the newly updated database.
I would like to add an 'add item' button, then it will popup a frame/window with fields to enter, then after clicking 'add' in the popup frame, the JTable and the database will be updated at the same time.
Could anyone please help me in this? I'm lost.. Thank you very much!