I've created a TableView in JavaFx. Everything works fine except that for some reason the table first row is automatically selected and I don't want this to happen.
My fxml file:
<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>
My data controller:
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);
}
}
DataClass:
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);
}
}
Can you please help me figure out what I'm doing wrong?
Thank you
This is a normal behaviour of JavaFX TableView. You need to clear the selection of the table, by using table.getSelectionModel().clearSelection();
This usually happens because the table gets focus on it. The final code that you are looking for is
peopleTable.focusedProperty().addListener((a,b,c) -> {
peopleTable.getSelectionModel().clearSelection();
});
For more information :
First Row Always Gets Selected When Focussing a TableView or TreeView in a JavaFX Application
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With