本文介绍了如何通过从JavaFX 2中的ListView中选择项来执行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在javafx 2中从 listview 中选择一个项目时执行操作。
我使用Netbeans JavaFX fxml应用程序和SceneBuilder。
SceneBuilder中的 OnMouseClicked 方法不起作用。它给了我一个错误,它无法找到我已经声明的方法。

I would like to have an action performed when I select an item from my listview in javafx 2.I use a Netbeans JavaFX fxml application and SceneBuilder.The OnMouseClicked method in SceneBuilder did not work. It gave me back an error that it can't find the method that I have already declared.

有人能告诉我他们是如何设法让它工作的吗?

Can someone tell me how they managed to get it to work?

推荐答案

你不能单独在FXML文件中这样做。

定义相应的listView(假设 fx:id =myListView(FXML):

You cannot do it in FXML file alone.
Define the corresponding listView (assuming fx:id="myListView" in FXML) in Controller class of the FXML file:

@FXML
private ListView<MyDataModel> myListView;

在init / start方法中添加监听器,它将监听列表视图项的变化:

Add listener in init/start method which will listen to the list view item changes:

myListView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<MyDataModel>() {

    @Override
    public void changed(ObservableValue<? extends MyDataModel> observable, MyDataModel oldValue, MyDataModel newValue) {
        // Your action here
        System.out.println("Selected item: " + newValue);
    }
});

MyDataModel 可以是您自己的数据结构模型类或只是字符串

对于字符串示例,

MyDataModel can be your own data structure model class or simply a String.
For String example,

@FXML
private ListView<String> myListView;

...
...

ObservableList<String> data = FXCollections.observableArrayList("chocolate", "blue");
myListView.setItems(data);

myListView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
    @Override
    public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
        // Your action here
        System.out.println("Selected item: " + newValue);
    }
});

这篇关于如何通过从JavaFX 2中的ListView中选择项来执行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 18:06