coldflows coldflows - 13 days ago 9
Java Question

JTree database node select and display in textfield in java

I have a

JTree
populated with a list of tasks from a database, I am trying to create a mouse clicked listener so that when a node is clicked, the id and task are displayed into
JTextfields
,

below is my code

private void jTree1MouseClicked(java.awt.event.MouseEvent evt) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent();
Object nodeInfo = node.getUserObject();

try {
String query = "select * from Task where task=" + nodeInfo + "";
pst = con.prepareStatement(query);
rs = pst.executeQuery();
if (rs.next()) {
int id = rs.getInt("id");
String task = rs.getString("task");
parentIdTxt.setText("" + id);
childTxt.setText("" + task);
}
} catch (Exception e) {

}
}


My problem is that even tho my program runs without any issues, whenever I click the node nothing happens? any help in pointing out what I missed will be appreciated

Answer

In fact you get an error but you don't see it, because you don't print it, you can check the error using :

} catch (Exception e) {
    e.printStackTrace();
}

String should be between 'nodeinfo' so instead you have to use :

String query="select * from Task where task= '" + nodeInfo + "'";

But you don't implement PrepapredStatement correctly you can use this :

String query="select * from Task where task = ?";
insert.setString(1, nodeinfo);
rs = pst.executeQuery();
...