如何为 tableView 行定义 setOnAction?

2023-12-11

我正在编写一个具有 javafx 和 tableView 功能的程序。

我的目的是当我单击此表的一行时,会打开另一个窗口并显示一些内容,但我不知道如何为我的表定义类似 setOnMouseClicked 功能的内容。

我搜索了很多,但找不到简单的方法

这是我定义表列和行的现有代码。(行是用可观察的功能定义的)

package sample;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

public static void main(String[] args) {
    launch(args);
}

@Override
public void start(Stage primaryStage) {

    TableView tableView = new TableView();

    TableColumn<String, Account> column1 = new TableColumn<>("UserName");
    column1.setCellValueFactory(new PropertyValueFactory<>("userName"));
    column1.setMinWidth(100);

    TableColumn<String, Account> column2 = new TableColumn<>("PassWord");
    column2.setCellValueFactory(new PropertyValueFactory<>("passWord"));
    column2.setMinWidth(100);


    tableView.getColumns().add(column1);
    tableView.getColumns().add(column2);
    tableView.setItems(getAllAccounts());



    VBox vbox = new VBox(tableView);

    Scene scene = new Scene(vbox,200,200);
    Stage window ;

    window = primaryStage;

    window.setScene(scene);
    window.show();
}
private ObservableList<Account> getAllAccounts(){
ObservableList<Account> accounts= FXCollections.observableArrayList(Account.getAccounts());
return accounts;

}


}

你实际上有两个选择:

方法一:

实现一个点击监听器TableView并检索所选的项目。

// Listen for a mouse click and access the selectedItem property
tblAccounts.setOnMouseClicked(event -> {
    // Make sure the user clicked on a populated item
    if (tblAccounts.getSelectionModel().getSelectedItem() != null) {
        System.out.println("You clicked on " + tblAccounts.getSelectionModel().getSelectedItem().getUsername());
    }
});

方法二:

创建您自己的RowFactory为了TableView并在那里处理你的逻辑。(我比较喜欢这个方法)

// Create a new RowFactory to handle actions
tblAccounts.setRowFactory(tv -> {

    // Define our new TableRow
    TableRow<Account> row = new TableRow<>();
    row.setOnMouseClicked(event -> {
        System.out.println("Do your stuff here!");
    });
    return row;
});

方法#1 是最简单的方法,可以满足大多数需求。您将需要使用方法 #2 来满足更复杂的需求,例如设置各个行的样式,或处理空行上的点击。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何为 tableView 行定义 setOnAction? 的相关文章

随机推荐