0

The function need to be accomplished is:

  1. Select main group
  2. Select from sub-group (TEST NAME)
  3. Click >> button which means move the selection to Jtable
  4. Show the slected (Test) with corresponding price on Jtable

conditions:

  • if the selected node (test name) alread has been selected and added to the Jtable show message say: Test name already added.
  • we can select and add many test name

Demo image

impotant to say that JTree data come from two tables main-group and sub-group

Here the code: of >> button

  try {
        DefaultMutableTreeNode selectedElement = (DefaultMutableTreeNode) TestTree.getSelectionPath().getLastPathComponent();
        Object[] row = {selectedElement};
        DefaultTableModel model = (DefaultTableModel) myTests_table.getModel();
        System.out.println(String.valueOf(row).toString() + "Hi");
        if (selectedElement.isLeaf() == true) {
            //model.addRow(row);
            // retrive date from DB price
            String sql = "SELECT  sub_group.name AS 'name', sub_group.price AS 'price'"
                    + "FROM sub_group \n"
                    + "where sub_group.name = '" + row + "' ";
            pst = conn.prepareStatement(sql);
            rs = pst.executeQuery(sql);
            while (rs.next()) {
                myTests_table.setModel(DbUtils.resultSetToTableModel(rs));
            }
        } else {
            JOptionPane.showMessageDialog(null, "Please Choose Test name!", "Error", JOptionPane.WARNING_MESSAGE);
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Error");
    }

Dears where is the error? Thanks

mKorbel
  • 109,525
  • 20
  • 134
  • 319

2 Answers2

1

Add a TreeSelectionListener to your JTree, as shown here. In the listener, update the TableModel of your JTable; the listening table will update itself accordingly, when your implementation of setValueAt() fires the relent TableModelEvent. Your table model should extend AbstractTableModel, as shown here, and contain a Set<Row>. Your Row class should hold the name and price. If Row implements Comparable<Row>, as shown in the example cited here, then Set<Row> will automatically exclude duplicates when you invoke add().

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
-1

if the issue is that the new TableModel is not being reflected in the UI, use tableModel.fireTableDataChanged().

shark
  • 117
  • 1
  • 5
  • 1
    A `TableModelEvent` should be fired _only_ from within the scope of the `TableModel` itself, not externally. – trashgod Mar 07 '16 at 23:40
  • could you point to any sources which say thats the best practice? there are other questions with same answers and they do say the same. ex: http://stackoverflow.com/questions/3179136/jtable-how-to-refresh-table-model-after-insert-delete-or-update-the-data – shark Mar 08 '16 at 21:24