2015-01-12 2 views
0

FXML файл выглядит следующим образом (заголовки опущены):Как сделать событие щелчка мыши признанным TreeItem в TreeView?

<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" 
    minWidth="-Infinity" prefHeight="600.0" prefWidth="800.0" 
    xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" 
    fx:id="pane" 
    fx:controller="com.github.parboiled1.grappa.debugger.mainwindow.MainWindowUi"> 
    <top> 
     <MenuBar BorderPane.alignment="CENTER"> 
      <Menu mnemonicParsing="false" text="File"> 
       <MenuItem fx:id="loadInput" mnemonicParsing="false" 
        text="Load file" onAction="#loadFileEvent"/> 
       <MenuItem fx:id="parse" mnemonicParsing="false" 
        text="Parse" onAction="#parseEvent"/> 
       <MenuItem fx:id="closeButton" mnemonicParsing="false" 
        text="Close" onAction="#closeWindowEvent"/> 
      </Menu> 
     </MenuBar> 
    </top> 
    <center> 
     <SplitPane dividerPositions="0.5" prefHeight="160.0" prefWidth="200.0" 
      BorderPane.alignment="CENTER"> 
      <SplitPane dividerPositions="0.5" orientation="VERTICAL"> 
       <TreeView fx:id="traceTree" prefHeight="200.0" 
        prefWidth="200.0" editable="false"/> 
       <TextArea fx:id="traceDetail" prefHeight="200.0" 
        prefWidth="200.0"/> 
      </SplitPane> 
      <TextArea fx:id="inputText" prefHeight="200.0" prefWidth="200.0"/> 
     </SplitPane> 
    </center> 
</BorderPane> 

Я могу установить корень TreeView без проблем вообще. Дерево обновляется без проблем.

Проблема, которая возникает у меня, заключается в том, что я не могу выполнить событие, выпущенное для данного элемента в представлении. Я попробовал и добавил событие onMouseClicked с простой System.out.println(), и я вижу, что событие запускается, в зависимости от того, какой элемент я нажимаю на дереве. Но я не могу получить элемент, который был нажат в представлении вообще.

Как это сделать?

ответ

2

Зарегистрируйте слушателя мыши с каждой ячейкой дерева, используя фабрику ячеек. Я не знаю тип данных, который у вас есть в вашем TreeView, но если он был String, он может выглядеть примерно так:

// Controller class: 
public class MainWindowUi { 

    @FXML 
    private TreeView<String> traceTree ; 

    // ... 

    public void initialize() { 
     traceTree.setCellFactory(tree -> { 
      TreeCell<String> cell = new TreeCell<String>() { 
       @Override 
       public void updateItem(String item, boolean empty) { 
        super.updateItem(item, empty) ; 
        if (empty) { 
         setText(null); 
        } else { 
         setText(item); 
        } 
       } 
      }; 
      cell.setOnMouseClicked(event -> { 
       if (! cell.isEmpty()) { 
        TreeItem<String> treeItem = cell.getTreeItem(); 
        // do whatever you need with the treeItem... 
       } 
      }); 
      return cell ; 
     }); 
    } 

    // ... 
} 
Смежные вопросы