简体   繁体   中英

Set the selected Jtree Node to JTable

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

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() .

如果问题是新的TableModel没有反映在UI中,请使用tableModel.fireTableDataChanged()。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM