简体   繁体   中英

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

You have to repaint the textfields or update their layout so they have enough space to show the contents. Try adding the following code after setting the contents of your textfields:

parentIdTxt.validate();
parentIdTxt.repaint();
childTxt.validate();
childTxt.repaint();

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 PreparedStatement correctly you can use this :

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

Firstly you need to check if you get the task and the id correctly using Debug mode or just by printing them into the console.

I recomended you to test just this code in the `JTree1MouseClicked.

 private void jTree1MouseClicked(java.awt.event.MouseEvent evt) {      
      childTxt.setText(jTree1.getLastSelectedPathComponent().toString());
}

that should display the selected node, that should work, then you need to check your request, I think that the problem is there

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