java - 如何检测双击 JavaFx 中的 TextFieldTableCell?

标签 java javafx

我有下面的表格列

TableColumn<TradePurchaseOrderManifest, Double> netweightCol = createColumn("netWeight", "Net Wgt",
                Double.class);

和 createColumn 方法

public static <T> TableColumn<TradePurchaseOrderManifest, T> createColumn(String name, String columHeading,
            Class<T> type) {
        TableColumn<TradePurchaseOrderManifest, T> column = new TableColumn<>(columHeading);
        column.setCellValueFactory(new PropertyValueFactory<>(name));
        column.setResizable(true);
        return column;
    }

此表还有其他列,它们都是 ComboBoxTableCell 等类型。我希望在此 TextFieldTableCell 上有一个双击处理程序,并且仅在此列上。我现在能够实现的是在 tableview(row) 上有一个 doubleClick 处理程序。

当我单击此单元格时,它会转换为 TextFieldTableCell,然后不响应双击,即使我正在检查它是否是 TextFieldTableCell 的实例也是如此

        tableView.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {

            @Override
            public void handle(MouseEvent event) {
                if (event.getClickCount() == 2) {
                    if (event.getTarget() instanceof TableCell<?,?>) {
                        System.out.println("dblCLick tableCell");
                    } else if (event.getTarget() instanceof TextFieldTableCell<?,?>) {
                        System.out.println("dblCLick textfield");
                    }
                }
            }
        });

有关如何仅在此列上应用双击处理程序以及何时它是 TextFieldTableCell 的任何建议。

最佳答案

这是我使用的解决方法。我使用 ContextMenus 来处理类似的情况。

import java.util.Arrays;
import java.util.Optional;
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.TextInputDialog;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

/**
 * Sedrick (SedJ601)
 * Uses code from https://gist.github.com/james-d/7758918, https://code.makery.ch/blog/javafx-dialogs-official/ and https://stackoverflow.com/questions/21009377/context-menu-on-a-row-of-tableview
 */
public class App extends Application {
    private TableView<Person> table = new TableView<Person>();
    private final ObservableList<Person> data =
        FXCollections.observableArrayList(
            new Person("Jacob", "Smith", "jacob.smith@example.com"),
            new Person("Isabella", "Johnson", "isabella.johnson@example.com"),
            new Person("Ethan", "Williams", "ethan.williams@example.com"),
            new Person("Emma", "Jones", "emma.jones@example.com"),
            new Person("Michael", "Brown", "michael.brown@example.com")
        );

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

    @Override
    public void start(Stage stage) {
        Scene scene = new Scene(new Group());
        stage.setTitle("Table View Sample");
        stage.setWidth(450);
        stage.setHeight(500);

        final Label label = new Label("Address Book");
        label.setFont(new Font("Arial", 20));

        table.setEditable(true);

        TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
        firstNameCol.setMinWidth(100);
        firstNameCol.setCellValueFactory(
                new PropertyValueFactory<>("firstName"));

        TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
        lastNameCol.setMinWidth(100);
        lastNameCol.setCellValueFactory(
                new PropertyValueFactory<>("lastName"));

        TableColumn<Person, String> emailCol = new TableColumn<>("Email");
        emailCol.setMinWidth(200);
        emailCol.setCellValueFactory(
                new PropertyValueFactory<>("email"));

        table.setItems(data);
        table.getColumns().addAll(Arrays.asList(firstNameCol, lastNameCol, emailCol));

        table.setRowFactory((TableView<Person> tableView) -> {
            final TableRow<Person> row = new TableRow<>();

            final ContextMenu contextMenu = new ContextMenu();
            final MenuItem removeMenuItem = new MenuItem("Change last name");
            removeMenuItem.setOnAction((ActionEvent event) -> {
                Person tempPerson = table.getSelectionModel().getSelectedItem();
                int rowIndex = table.getSelectionModel().getSelectedIndex();

                TextInputDialog dialog = new TextInputDialog(tempPerson.getLastName());
                dialog.setTitle("Text Input Dialog");
                dialog.setHeaderText("Look, a Text Input Dialog");
                dialog.setContentText("Please enter a last name:");

                // Traditional way to get the response value.
                Optional<String> result = dialog.showAndWait();
                if (result.isPresent()){
                    tempPerson.setLastName(result.get());
                    tableView.getItems().set(rowIndex, tempPerson);
                }
            });
            contextMenu.getItems().add(removeMenuItem);
            // Set context menu on row, but use a binding to make it only show for non-empty rows:
            row.contextMenuProperty().bind(
                    Bindings.when(row.emptyProperty())
                            .then((ContextMenu)null)
                            .otherwise(contextMenu)
            );
            return row ;  
        });  

        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().addAll(label, table);

        ((Group) scene.getRoot()).getChildren().addAll(vbox);

        stage.setScene(scene);
        stage.show();
    }

    public static class Person {

        private final SimpleStringProperty firstName;
        private final SimpleStringProperty lastName;
        private final SimpleStringProperty email;

        private Person(String fName, String lName, String email) {
            this.firstName = new SimpleStringProperty(fName);
            this.lastName = new SimpleStringProperty(lName);
            this.email = new SimpleStringProperty(email);
        }

        public String getFirstName() {
            return firstName.get();
        }

        public void setFirstName(String fName) {
            firstName.set(fName);
        }

        public String getLastName() {
            return lastName.get();
        }

        public void setLastName(String fName) {
            lastName.set(fName);
        }

        public String getEmail() {
            return email.get();
        }

        public void setEmail(String fName) {
            email.set(fName);
        }
    }
} 

关于java - 如何检测双击 JavaFx 中的 TextFieldTableCell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59162062/

相关文章:

java - 通过队列发送大文件时 Activemq 内存不足

java - 使用 Vaadin 14 的 RTL 支持

JavaFX - 圆形和矩形之间的交互

java - setStroke() 和 setFill() 产生不同的像素颜色

JavaFX TableView 动态列和数据值

Java序列化: Any solution if serialVersionUID is updated wrong and already released.

java - Java 的 NSData 类型?

java - 谓词<? super X>.and(Predicate<? super X>) 不适用于参数 Predicate<? super X>

javafx 通过代码点击按钮

java - java中如何对列表中的列表进行排序