Reputation: 446
I'm working on a JAVA project using NetBeans.
I Bound JTable with a MysqlDB table. I want to be able to make changes on the DB by changing the cells of the JTable. How can i do that? I tried to test the action listener but it doesn't work.
public void TableListener()
{
BookList.getModel().addTableModelListener(new TableModelListener() {
//BookList is the name of the JTable.
@Override
public void tableChanged(TableModelEvent tme) {
TableModel tm = (TableModel)tme.getSource();
System.out.println(tm.getColumnCount()+" Hi");
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
}
I created this method in the JFrame class and called it in the main method. it is not supposed to update the database but i just wanted to know if it is working. tm.getColumnCount
is not being printed.
If using the listener is wrong please tell me the right way.
Upvotes: 0
Views: 524
Reputation: 11
Good design principles say that you should use a separate class (called a DAO or "Data Access Object") to handle communication with the DB. This helps separate the concerns of your application and keeps your code clean and understandable.
You can use a listener similar to the way you are doing it to call the appropriate DAO method to handle the CRUD operations on the DB.
As for why your TableModelListener isn't working as expected, you have set it up in a strange way, which is probably causing your problem. Try referring to this page : https://docs.oracle.com/javase/tutorial/uiswing/components/table.html#data
Notice that you are defining an anonymous TableListener inside your TableListener class : BookList.getModel().addTableModelListener(new TableModelListener() {...}
You can do it this way, but then there's no point in writing the TableListener that your code sample is from.
Basically, your issue is that you're trying to bind and use your listener inside your listener class. The listener class should simply define the behavior of your listener. You should then add the listener to the JTable outside of the listener class. I think this will solve your problem.
Upvotes: 1