简体   繁体   English

JTree数据库节点在java中的textfield中选择和显示

[英]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 , 我有一个JTree填充了数据库中的任务列表,我正在尝试创建一个鼠标单击的侦听器,以便在单击节点时,id和任务显示在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 : 字符串应该在'nodeinfo'之间,所以你必须使用:

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

But you don't implement PreparedStatement correctly you can use this : 但是你没有正确实现PreparedStatement你可以使用它:

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. 首先,您需要检查是否使用Debug模式正确获取taskid ,或者只是将它们打印到控制台中。

I recomended you to test just this code in the `JTree1MouseClicked. 我建议你在`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 应该显示所选节点,这应该工作,然后你需要检查你的请求,我认为问题是存在的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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