1

I need to perform the following task: On selection of a single tree item in a treeViewer, relevant data is supposed to display in the tableViewer. I have retrieved data from MySQL, using the rs.getString() method, and added the obtained string array into the tree item using the setText() method. I need to select one of the string values displayed in the treeViewer that has been dynamically generated.

On using a selection event for the tree, all generated elements get selected. How can I obtain a single selection? Is there any method similar to getSelectedItem() for a treeViewer? This is the code i used to generate the tree items:

Tree tree_1 = treeViewer.getTree();
tree_1.setBounds(316, 205, 244, 446);
try {
    Class.forName("com.mysql.cj.jdbc.Driver");  
    Connection con2 = DriverManager.getConnection("jdbc:mysql://localhost:3306/project","xxxx","xxxx");   
    Statement stmt2 = con2.createStatement();  
    String query2="select DISTINCT xxx FROM xxxxx";
    ResultSet rs2=stmt2.executeQuery(query2);  
    while(rs2.next()) {
        String executive=rs2.getString("xxxx");
        TreeItem item4=new TreeItem(tree_1,SWT.NONE);
        item4.setText(executive);
        item4.setFont(SWTResourceManager.getFont("Times New Roman", 12, SWT.NORMAL));
    }
}
        
Elikill58
  • 4,050
  • 24
  • 23
  • 45
Vt0613
  • 11
  • 1
  • You cannot add TreeItems like this to a tree managed by TreeViewer - the viewer is in charge of the items and you must not add them directly. Instead update the elements in your content provider and use TreeViewer.add or refresh – greg-449 Mar 30 '22 at 06:36
  • When I tried using the content provider, all values from the database were not displayed, only a single item gets displayed. If you have any links or samples for the same please do link it, thank you – Vt0613 Mar 30 '22 at 07:09
  • [This article](https://www.eclipse.org/articles/Article-TreeViewer/TreeViewerArticle.htm) covers all aspects of using TreeViewer including adding new items. As I already said you **must** use the content provider for additions. – greg-449 Mar 30 '22 at 07:21
  • How can I add children dynamically? I need to obtain values from a database and display them in the treeViewer. – Vt0613 Mar 30 '22 at 07:57
  • You update the data in your content provider and then use TreeViewer add, remove, update or refresh depending on exactly what you need to do. – greg-449 Mar 30 '22 at 10:09

0 Answers0