问题
I am writing a program with javafx and tableView feature.
My purpose is when I click on a row of this table,another window opens and shows something but I don't know how to define something like setOnMouseClicked feature for my table.
I searched a lot but I coudn't find a simple way
This is my existing code that define table columns and rows.(rows are defined with observable feature)
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;
}
}
回答1:
You actually have two options:
Method 1:
Implement a click listener on the TableView
and retrieve the item that was selected.
// 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());
}
});
Method 2:
Create your own RowFactory
for the TableView
and handle your logic there. (I prefer this method)
// 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;
});
Method #1 is the simplest approach and will work for most needs. You'll want to use method #2 for more complex needs, such as styling the individual rows, or to handle clicks on empty rows.
来源:https://stackoverflow.com/questions/56495943/how-to-define-setonaction-for-tableview-rows