簡體   English   中英

如何使 TreeView 中的 TreeItem 確認鼠標單擊事件?

[英]How do I make a mouse click event be acknowledged by a TreeItem in a TreeView?

fxml 文件如下(頭文件省略):

<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的根。 樹更新沒有問題。

我遇到的問題是我無法在視圖中的給定項目上觸發事件。 我嘗試使用簡單的 System.out.println() 添加了一個onMouseClicked事件,我可以看到正在觸發的事件,無論我在樹中單擊哪個項目。 但是我根本無法獲得在視圖中單擊的項目。

我怎么做?

使用單元工廠為每個樹單元注冊一個鼠標偵聽器。 我不知道您的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 ;
        });
    }

    // ... 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM