0

I have a Java Class, i create a Query (JPA with EclipseLink) to Load Info from DB when a JTabbedPane is clicked, the data is loaded into the TableModel which is bound to a JTable. I use MouseClicked of MouseEvent, to get the selected tab. But some tables fail to load, i feel as if nothing is clicked, but when i go around through the tabs and come back to the tab that failed to load it eventually loads the data sometimes. My Code below:

private void jTabbedPane1MouseClicked(java.awt.event.MouseEvent evt) {  
  int selectTab = jTabbedPane1.getSelectedIndex();
  if (selectTab == 1) {
    bookValueTable.getColumnModel().getColumn(0).setMaxWidth(150);
    bookValueTable.getColumnModel().getColumn(1).setMaxWidth(150);
    if (!tab2Opened) { //this makes sure the data is not loaded multiple time....
        tab2Opened = true;
        Query q = em.createQuery("select e from EnterpriseInvestments e Where e.acctYear = :acctYear");
        q.setParameter("acctYear", acctYear);
        List<EnterpriseInvestments> resultList = q.getResultList();
        for(EnterpriseInvestments p: resultList){
          Object row[] = {p.getEnterprise().getRcNo(), p.getAcctYear(), p.getInvestmentItem(),
                nf.format(p.getInvestmentAmount())};
            shareCapitalModel.addRow(row);
        }
    }
    bookValueTable.setRowSorter(new TableRowSorter(shareCapitalModel));
}

I dont know where the problem is coming from: The JPA, The TabbedPane or the EventHandler!

kleopatra
  • 51,061
  • 28
  • 99
  • 211
M.Hussaini
  • 135
  • 1
  • 5
  • 15

2 Answers2

3

In addition to @JB's guidance on listeners, I suspect that latency in your JPA query is blocking the event dispatch thread (EDT). Although you must update the table model on the EDT, you can do the query in the doInBackground() method of a SwingWorker, as shown in the API.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
2

If I understand correctly, you want to load the content of a table once the tab containing it is selected.

First of all, you should not use a MouseListener to do that. It's a too low-level listener. And moreover, you could use the keyboard to switch tabs. To detected a tab selection change, you should add a ChangeListener to the tabbed pane.

Another thing you should do is remove the JPA code from the listener, and put it in a separate method, and even in a separate class. It's not the business of the GUI code to know how to get data from the database. Do that in a Data Access Object, and unit test this Data Access Object to know if it works correctly. One you know that, use it in your GUI. If there is a problem, it will be in the GUI code since you have tested that the data access code works.

Using a debugger, and ultimately, logging statements, also helps diagnosing where the problem comes from.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255