2013-10-21 17 views

回答

9

下面的代码这一要求工作它调用对象select

tableView.setRowFactory(new Callback<TableView<Person>, TableRow<Person>>() { 
     @Override 
     public TableRow<Person> call(TableView<Person> tableView2) { 
      final TableRow<Person> row = new TableRow<>(); 
      row.addEventFilter(MouseEvent.MOUSE_PRESSED, new EventHandler<MouseEvent>() { 
       @Override 
       public void handle(MouseEvent event) { 
        final int index = row.getIndex(); 
        if (index >= 0 && index < tableView.getItems().size() && tableView.getSelectionModel().isSelected(index) ) { 
         tableView.getSelectionModel().clearSelection(); 
         event.consume(); 
        } 
       } 
      }); 
      return row; 
     } 
    }); 

从oracle的表视图示例中使用相同的Person类。在oracle的论坛中,@James_D给出了最初的答案。

+0

该实现取消选择所有选定的项目。要取消选择只有一个项目,请使用'tableView.getSelectionModel()。clearSelection(index);' – Ravvy

0

基本上你可以选择任何东西作为索引无效。通常-1优选

table.getSelectionModel().select(-1); 

它调用INT select。替代方案:

table.getSelectionModel().select(null); 

,如果你想看到使用整个代码/确认本

public class Main extends Application { 
    @SuppressWarnings("unchecked") 
    @Override 
    public void start(Stage stage) {   
     Scene scene = new Scene(new Group()); 
     TableView<Person> table = new TableView<Person>(); 
     stage.setTitle("Table View Sample"); 
     stage.setWidth(300); 
     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<Person, String>("Test Name"); 
     firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("name")); 

     table.getColumns().addAll(firstNameCol); 

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

     table.itemsProperty().get().add(new Person("Hans")); 
     table.itemsProperty().get().add(new Person("Dieter")); 

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

     table.getSelectionModel().select(-1); 

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

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

    public class Person { 
     final StringProperty name = new SimpleStringProperty(); 

     Person(String name) { 
      this.name.set(name); 
     } 

     public StringProperty nameProperty() { return this.name; } 
    } 
} 
+0

这将是很好,如果你可以改善与提'getSelectionModel()。clearAndSelect(INT指数)'和实施“做点击所选项目取消选择”为OP请求你的答案。 –

+0

@thatslch我试过了你的一段代码。如果再次点击它,它不会取消选择之前选定的行。 – Dil

+0

@Dil missunderstood you question:我想如何清楚是你的问题。 – thatsIch

相关问题