自定义回调<tableview <t>,TableRow <t>&gt;在javafx中双击执行回调

时间:2015-05-22 10:13:34

标签: java javafx

我有以下实现:

class CustomTableRow<T> implements CallBack <Tableview<T> TableRow<T>>{
    private T selectedItem;

    public CustomTableRow(T selectedItem){
        this.selectedItem = selectedItem;
    }

    @Override
    public TableRow<T> call(TableView<T> param){
        TableRow<T> row = new TableRow<>΄
        row.setOnMouseClicked(event ->{
            if (!row.isEmpty()){
                try{
                    //Using BeanUtils.copyProperties();
                }catch (Exception e){
                }
            }
        });
    }
}

我有一个使用此CustomTableRow的类

class SomeClass{

    private Tableview myTableView;
    private MyCustomModelClass selectedItem;

    private setUpTableView(){
        selectedItem = new MyCustomModelClass();
        tableView.setRowFactory(new CustomTableRow<MyCustomModelClass>(selectedItem));    
    }


    private thisNeedsToBeExecutedOnRowDoubleClick(){
    }
}

为了使事情变得更糟,这个CustomTableRow被其他不需要实现双击功能的TableView使用。

我应该创建两个不同的CustomTableRow类,还是可以在检测到双击并且selectedItem属于MyCustomModelClass类型时传递回调函数(如javascript)来执行?我使用的是java版本8 Update 45。

1 个答案:

答案 0 :(得分:0)

定义CustomTableRowConsumer<T>作为参数,并在双击时调用该对象的accept(...)方法。这是基本的想法(我将CustomTableRow重命名为DoubleClickTableRowFactory,因为我认为它更好地描述了它的作用):

public class MouseClickTableRowFactory<T> 
  implements Callback<TableView<T>, TableRow<T>> {

    private final Consumer<T> doubleClickHandler ;
    private final int numClicks ;

    public MouseClickTableRowFactory(Consumer<T> doubleClickHandler, int numClicks) {
        this.doubleClickHandler = doubleClickHandler ;
        this.numClicks = numClicks ;
    }

    public MouseClickTableRowFactory(Consumer<T> doubleClickHandler) {
        // default to double-click...
        this(doubleClickHandler, 2);
    }

    @Override
    public TableRow<T> call(TableView<T> tv) {

        TableRow<T> row = new TableRow<>();
        row.addEventHandler(MouseEvent.MOUSE_CLICKED, event -> {
            if (event.getClickCount() == numClicks && ! row.isEmpty()) {
                doubleClickHandler.accept(row.getItem());
            }
        });
        return row ;
    }
}

现在你可以做到

public class SomeClass {

    private TableView<MyCustomModelClass> myTableView ;

    // ...

    private void setupTable() {
        myTableView.setRowFactory(
          // invokes rowDoubleClicked when user double-clicks on a row:
          new MouseClickTableRowFactory<>(this::rowDoubleClicked));

        // for single click, do
        // myTableView.setRowFactory(
        //  new MouseClickTableRowFactory(item -> { ... }, 1));
        // ...
    }

    private void rowDoubleClicked(MyCustomModelClass item) {
        // handle double-click on row displaying item
    }
}