当前位置: 动力学知识库 > 问答 > 编程问答 >

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

网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: