我在JavaFx中创建了一个TableView。一切正常,但由于某种原因,表格第一行是自动选择的,我不希望这种情况发生。
我的fxml文件:
<fx:root type="javafx.scene.layout.AnchorPane" id="rootPane"
xmlns:fx="http://javafx.com/fxml/1">
<TableView fx:id="myTable">
<columns>
<TableColumn fx:id="column1" maxWidth="5000.0"
minWidth="200.0" prefWidth="400.0" text="column1" />
<TableColumn fx:id="column2" maxWidth="5000.0"
minWidth="20.0" prefWidth="80.0" text="column2" />
</columns>
</TableView>
</fx:root>
我的数据控制器:
public class TableController extends AnchorPane{
@FXML private TableView<DataClass> myTable;
@FXML private TableColumn<DataClass, String> column1;
@FXML private TableColumn<DataClass, Integer> column2;
public TableController(){
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource(
"/fxml/Temp.fxml"));
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
try {
fxmlLoader.load();
initComponents();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
private void initComponents(){
column1.setCellValueFactory(
new PropertyValueFactory<DataClass, String>("column1"));
column2.setCellValueFactory(
new PropertyValueFactory<DataClass, Integer>("column2"));
ArrayList<DataClass> list = new ArrayList<DataClass>();
list.add(new DataClass("S1", 1));
list.add(new DataClass("S2", 2));
list.add(new DataClass("S3", 3));
ObservableList<DataClass> data = FXCollections.observableArrayList(list);
myTable.setItems(data);
}
}
数据类:
public class DataClass{
private StringProperty column1;
private IntegerProperty column2;
private DataClass(String column1, int column2){
this.column1 = new SimpleStringProperty(column1);
this.column2 = new SimpleIntegerProperty(column2);
}
public String getColumn1() {
return column1.get();
}
public void setColumn1(String column1) {
this.column1.set(column1);
}
public int getColumn2() {
return column2.get();
}
public void setColumn2(int column) {
this.column2.set(column);
}
}
你能帮我弄清楚我做错了吗?
谢谢
答案 0 :(得分:3)
这是JavaFX TableView的正常行为。您需要使用table.getSelectionModel().clearSelection();
这通常是因为表格集中于它。您正在寻找的最终代码是
peopleTable.focusedProperty().addListener((a,b,c) -> {
peopleTable.getSelectionModel().clearSelection();
});
有关详情:
First Row Always Gets Selected When Focussing a TableView or TreeView in a JavaFX Application