mouseevent not working in java fx [duplicate] - gradle

I am trying to make a tableview clickable, where it will return the text in the cell that is clicked. I am receiving two errors when trying to compile in Netbeans. All of the code was taken from "Example 12-11: Alternative Solution Of Cell Editing" official tableview tutorial & from this stackoverflow.com answer. Here are the errors:
type argument MouseEvent is not within bounds of type-variable T
cell.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler() {
where T is a type-variable:
T extends Event declared in interface EventHandler
method addEventFilter in class Node cannot be applied to given types;
cell.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler() {
required: EventType,EventHandler
found: int,>
reason: no instance(s) of type variable(s) T exist so that argument type int conforms to formal parameter type EventType
where T is a type-variable:
T extends Event declared in method addEventFilter(EventType,EventHandler)
import java.awt.event.MouseEvent;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.util.Callback;
public class TableViewSample extends Application {
private TableView<Person> table = new TableView<>();
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"));
final HBox hb = new HBox();
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(550);
final Label label = new Label("Address Book");
label.setFont(new Font("Arial", 20));
table.setEditable(false);
Callback<TableColumn, TableCell> cellFactory =
new Callback<TableColumn, TableCell>() {
public TableCell call(TableColumn p) {
TableCell cell = new TableCell<Person, String>() {
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(empty ? null : getString());
setGraphic(null);
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
};
cell.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.getClickCount() > 1) {
System.out.println("double clicked!");
TableCell c = (TableCell) event.getSource();
System.out.println("Cell text: " + c.getText());
}
}
});
return cell;
}
};
TableColumn firstNameCol = new TableColumn("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(
new PropertyValueFactory<Person, String>("firstName"));
firstNameCol.setCellFactory(cellFactory);
firstNameCol.setOnEditCommit(
new EventHandler<CellEditEvent<Person, String>>() {
#Override
public void handle(CellEditEvent<Person, String> t) {
((Person) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setFirstName(t.getNewValue());
}
}
);
TableColumn lastNameCol = new TableColumn("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(
new PropertyValueFactory<Person, String>("lastName"));
lastNameCol.setCellFactory(cellFactory);
lastNameCol.setOnEditCommit(
new EventHandler<CellEditEvent<Person, String>>() {
#Override
public void handle(CellEditEvent<Person, String> t) {
((Person) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setLastName(t.getNewValue());
}
}
);
TableColumn emailCol = new TableColumn("Email");
emailCol.setMinWidth(200);
emailCol.setCellValueFactory(
new PropertyValueFactory<Person, String>("email"));
emailCol.setCellFactory(cellFactory);
emailCol.setOnEditCommit(
new EventHandler<CellEditEvent<Person, String>>() {
#Override
public void handle(CellEditEvent<Person, String> t) {
((Person) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setEmail(t.getNewValue());
}
}
);
table.setItems(data);
table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
final TextField addFirstName = new TextField();
addFirstName.setPromptText("First Name");
addFirstName.setMaxWidth(firstNameCol.getPrefWidth());
final TextField addLastName = new TextField();
addLastName.setMaxWidth(lastNameCol.getPrefWidth());
addLastName.setPromptText("Last Name");
final TextField addEmail = new TextField();
addEmail.setMaxWidth(emailCol.getPrefWidth());
addEmail.setPromptText("Email");
final Button addButton = new Button("Add");
addButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
data.add(new Person(
addFirstName.getText(),
addLastName.getText(),
addEmail.getText()));
addFirstName.clear();
addLastName.clear();
addEmail.clear();
}
});
hb.getChildren().addAll(addFirstName, addLastName, addEmail, addButton);
hb.setSpacing(3);
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(label, table, hb);
((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);
}
}
class EditingCell extends TableCell<Person, String> {
private TextField textField;
public EditingCell() {
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
setGraphic(null);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
textField.focusedProperty().addListener(new ChangeListener<Boolean>(){
#Override
public void changed(ObservableValue<? extends Boolean> arg0,
Boolean arg1, Boolean arg2) {
if (!arg2) {
commitEdit(textField.getText());
}
}
});
}
private String getString() {
return getItem() == null ? "" : getItem();
}
}
}

You have the wrong import for MouseEvent. You need javafx.scene.input.MouseEvent, not the AWT version.

It is likely that when your IDE prompted you to import MouseEvent, the first option was java.awt.event.MouseEvent, rather than javafx.scene.input.MouseEvent.
Be careful while importing with JavaFX, as many of it's classes have the same names as classes in standard Java libraries.

Related

How to prevent event firing on drag and drop of columns in JavaFX TableView

In my Spring Boot JavaFX application I have multiple TableViews. The user is allowed to reorder the columns by using the default drag-and-drop functionality. I also have a listener to detect that another row in one of those TableViews is selected and take some action accordingly:
/*
* Processing when a selection in a table changes.
*/
getTableView().getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
this.detailsController.get().showDetails(newValue);
});
Problem is that this listener gets activated when a column is dragged and then dropped (on the drop part of the action). This has undesired side effects, since the variable newValue is 'null' in that case (which in itself is a valid value for processing, I just don't want to pass that value when dropping a column after dragging). Is there a way to bypass this listener when the column is dropped?
I have tried various ways to catch the drag-drop events, but to no avail...I was thinking I could deactivate the listener when the drag starts and reactivate after the drop is done.
Here is some sample code:
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class TestDragDrop extends Application {
#Override
public void start(Stage primaryStage) {
TableView<Person> table = new TableView<>();
table.getColumns().add(column("First Name", Person::firstNameProperty));
table.getColumns().add(column("Last Name", Person::lastNameProperty));
table.getColumns().add(column("Email", Person::emailProperty));
table.getItems().addAll(createData());
table.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if (newValue == null) {
System.out.println("===>>> Oops");
} else {
System.out.println("===>>> Hi there " + newValue.getFirstName());
}
});
VBox checkBoxes = new VBox(5);
checkBoxes.getStyleClass().add("controls");
BorderPane root = new BorderPane(table);
root.setTop(checkBoxes);
Scene scene = new Scene(root, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
private static <S, T> TableColumn<S, T> column(String text, Function<S, ObservableValue<T>> property) {
TableColumn<S, T> col = new TableColumn<>(text);
col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
return col;
}
private List<Person> createData() {
return Arrays.asList(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 class Person {
private final StringProperty firstName = new SimpleStringProperty();
private final StringProperty lastName = new SimpleStringProperty();
private final StringProperty email = new SimpleStringProperty();
public Person(String firstName, String lastName, String email) {
setFirstName(firstName);
setLastName(lastName);
setEmail(email);
}
public final StringProperty firstNameProperty() {
return this.firstName;
}
public final String getFirstName() {
return this.firstNameProperty().get();
}
public final void setFirstName(final String firstName) {
this.firstNameProperty().set(firstName);
}
public final StringProperty lastNameProperty() {
return this.lastName;
}
public final String getLastName() {
return this.lastNameProperty().get();
}
public final void setLastName(final String lastName) {
this.lastNameProperty().set(lastName);
}
public final StringProperty emailProperty() {
return this.email;
}
public final String getEmail() {
return this.emailProperty().get();
}
public final void setEmail(final String email) {
this.emailProperty().set(email);
}
}
public static void main(String[] args) {
launch(args);
}
}
Select a row in the table: ===>>> Hi there .... is output to the console. Now drag the first column to a different place in the table: ===>>> Oops is output to the console.
So one way to prevent this is by adding a buffer to prevent changes for a period of time once the column has been released.
In my case I used 50ms as the buffer because it will be hard for a person to finish dragging and click on a name in that time as it comes out to .05 Seconds in my testing this worked fine(No null were passed) but increase/decrease as you see fit
Here I initialize the PauseTransition which will fire after a given time
private final PauseTransition bufferReset = new PauseTransition(Duration.millis(50));
private boolean isBuffering = false;
Once initialized set the variable to flip back to no longer buffering
bufferReset.setOnFinished(event -> isBuffering = false);
The next block of code is where we flip the buffer variable after the column has been released and start the timer to flip the variable back
Platform.runLater(() -> {
for (Node header : table.lookupAll("TableHeaderRow")) {
if(header instanceof TableHeaderRow) {
header.addEventFilter(MouseEvent.MOUSE_RELEASED, event -> {
isBuffering = true;
bufferReset.play();
});
}
}
});
From there wrap your code in a isBuffering if statement
if(!isBuffering) {
if (newValue == null) {
System.out.println("===>>> Oops");
} else {
System.out.println("===>>> Hi there " + newValue.getFirstName());
}
}
Full Code(Not including the person class):
public class TestDragDrop extends Application {
private final PauseTransition bufferReset = new PauseTransition(Duration.millis(50));
private boolean isBuffering = false;
#Override
public void start(Stage primaryStage) {
TableView<Person> table = new TableView<>();
table.getColumns().add(column("First Name", Person::firstNameProperty));
table.getColumns().add(column("Last Name", Person::lastNameProperty));
table.getColumns().add(column("Email", Person::emailProperty));
table.getItems().addAll(createData());
table.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
if(!isBuffering) {
if (newValue == null) {
System.out.println("===>>> Oops");
} else {
System.out.println("===>>> Hi there " + newValue.getFirstName());
}
}
});
bufferReset.setOnFinished(event -> isBuffering = false);
Platform.runLater(() -> {
for (Node header : table.lookupAll("TableHeaderRow")) {
if(header instanceof TableHeaderRow) {
header.addEventFilter(MouseEvent.MOUSE_RELEASED, event -> {
isBuffering = true;
bufferReset.play();
});
}
}
});
VBox checkBoxes = new VBox(5);
checkBoxes.getStyleClass().add("controls");
BorderPane root = new BorderPane(table);
root.setTop(checkBoxes);
Scene scene = new Scene(root, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
private static <S, T> TableColumn<S, T> column(String text, Function<S, ObservableValue<T>> property) {
TableColumn<S, T> col = new TableColumn<>(text);
col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
return col;
}
private List<Person> createData() {
return Arrays.asList(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); }
}

Changing jfx TableView ShowHideColumnButton size with css

When using a jfx TableView and setting setTableMenuButtonVisible to true, a small button with a "+" sign appears at the top right corner of the table. The problem is that it's a narrow rectangle but I want it to be more square, I've tried padding etc but nothing works.
Also, the "+" sign in the button seems to be a "-fx-shape". Is there anyway I can change it to a png image from my desktop instead?
With css file:
TableViewStyling.class (your class file)
showHideColumnImage.png (image file you want to use instead of 'plus' sign
stylesheet.css (css file for styling tableView's TableMenuButton)
stylesheet.css content
.table-view .show-hide-column-image {
-fx-background-image: url("showHideColumnImage.png");
-fx-padding: 2em; /* play with here to make it square */
-fx-shape: null;
}
usage example
package so;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
public class TableViewStyling 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());
String css = this.getClass().getResource("stylesheet.css").toExternalForm();
scene.getStylesheets().add(css);
stage.setTitle("Table View Styling Sample");
stage.setWidth(450);
stage.setHeight(550);
TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
TableColumn<Person, String> emailCol = new TableColumn<>("Email");
emailCol.setMinWidth(200);
emailCol.setCellValueFactory(new PropertyValueFactory<Person, String>("email"));
table.setTableMenuButtonVisible(true);
table.setItems(data);
table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
((Group) scene.getRoot()).getChildren().addAll(table);
stage.setScene(scene);
stage.show();
}
public 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);
}
}
}
without css file:
lookup and find related node and apply css.
this way you can only lookup and find node after application show up (stage.show();)
package so;
import java.util.Set;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
public class TableViewStyling 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 Styling Sample 2");
stage.setWidth(450);
stage.setHeight(550);
TableColumn<Person, String> firstNameCol = new TableColumn<>("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
TableColumn<Person, String> lastNameCol = new TableColumn<>("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
TableColumn<Person, String> emailCol = new TableColumn<>("Email");
emailCol.setMinWidth(200);
emailCol.setCellValueFactory(new PropertyValueFactory<Person, String>("email"));
table.setTableMenuButtonVisible(true);
table.setItems(data);
table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
((Group) scene.getRoot()).getChildren().addAll(table);
stage.setScene(scene);
stage.show();
Set<Node> lookupAll = table.lookupAll(".show-hide-column-image");
lookupAll.forEach(n -> {
n.setStyle(""
+ "-fx-padding: 2em;"
+ "-fx-shape: null;"
+ "-fx-background-image: url(\""
+ TableViewStyling.class.getResource("showHideColumnImage.png").toExternalForm() + "\");");
});
}
public 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);
}
}
}

JavaFX - Disable Tab when invalid data entered in TableView

I have a TabPane where users enter/edit data on each tab and can freely switch between tabs without having to save changes before switching to a new tab. One tab has a TableView, and I'd like to prevent users from leaving that tab if they enter invalid data. My original approach was along the same lines as this question, which does not quite work - the tab is not reliably changed back. I liked James_D's answer and tried to implement something similar. However, most of the time the data being entered into a table is optional, so disabling other tabs until a user enters data is not an option.
What I ultimately did was extend TableColumn to add a BooleanProperty 'invalid' which I then bind to Tab's disableProperty. In that column's commit event, I validate the new value and, if it doesn't pass, set invalid = true, which disables the appropriate tab. This also does not quite work. I have custom table cells that commit edits on loss of focus. If focus is lost to clicking a different tab, the commit event is too late - the tab is first selected, then disabled. I've been wracking my brain for a workaround, but am out of ideas. If anyone has any suggestions, I would really appreciate it!
Short example (clear out any last name and click Tab 2):
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
import javafx.util.Callback;
public class TabPaneTableTest extends Application {
#Override
public void start(Stage primaryStage) {
TableView<Person> table = new TableView<>();
ObservableList<Person> data = FXCollections.observableArrayList();
table.setEditable(true);
MyTableColumn<Person, String> firstNameCol = new MyTableColumn<>("First Name");
firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
MyTableColumn<Person, String> lastNameCol = new MyTableColumn<>("Last Name");
lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
Callback<TableColumn<Person, String>, TableCell<Person, String>> cellFactory = (TableColumn<Person, String> p) -> new MyEditingCell<Person>();
firstNameCol.setCellFactory(cellFactory);
lastNameCol.setCellFactory(cellFactory);
firstNameCol.setOnEditCommit((CellEditEvent<Person, String> event) -> {
event.getRowValue().setFirstName(event.getNewValue());
});
lastNameCol.setOnEditCommit((CellEditEvent<Person, String> event) -> {
if(event.getNewValue().trim().isEmpty()) {
new Alert(AlertType.ERROR, "Last name must be filled out!", ButtonType.OK).showAndWait();
lastNameCol.setInvalid(true);
}
else {
event.getRowValue().setLastName(event.getNewValue());
lastNameCol.setInvalid(false);
}
});
table.getColumns().addAll(firstNameCol, lastNameCol);
table.setItems(data);
data.add(new Person("Luke", "Skywalker"));
data.add(new Person("Han", "Solo"));
data.add(new Person("R2", "D2"));
TabPane tabPane = new TabPane();
Tab tab1 = new Tab("Tab 1");
tab1.setClosable(false);
tab1.setContent(table);
Tab tab2 = new Tab("Tab 2");
tab2.setClosable(false);
tab2.disableProperty().bind(lastNameCol.invalidProperty());
tabPane.getTabs().addAll(tab1, tab2);
Scene scene = new Scene(tabPane, 400, 200);
primaryStage.setTitle("Tab Pane Table Validation Test");
primaryStage.setScene(scene);
primaryStage.show();
}
public class MyEditingCell<S> extends TableCell<S, String> {
private TextField editingField;
private void createEditingField() {
editingField = new TextField(getString());
editingField.focusedProperty().addListener((ov, oldValue, newValue) -> {
if(!newValue) {
commitEdit(editingField.getText());
}
});
}
#Override
public void startEdit() {
super.startEdit();
createEditingField();
setText(null);
setGraphic(editingField);
Platform.runLater(() -> {
editingField.requestFocus();
editingField.selectAll();
});
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText((String)getItem());
setGraphic(null);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if(empty) {
setText(null);
setGraphic(null);
}
else {
if(isEditing()) {
if(editingField != null) {
editingField.setText(getString());
}
setText(null);
setGraphic(editingField);
}
else {
setText(getString());
setGraphic(null);
}
}
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}
public class MyTableColumn<S, T> extends TableColumn<S, T> {
private BooleanProperty invalid = new SimpleBooleanProperty(false);
public MyTableColumn(String header) {
super(header);
setEditable(true);
}
public BooleanProperty invalidProperty() {
return invalid;
}
public boolean getInvalid() {
return invalid.get();
}
public void setInvalid(boolean value) {
invalid.set(value);
}
}
public class Person {
private StringProperty firstName;
private StringProperty lastName;
public Person(String first, String last) {
firstName = new SimpleStringProperty(this, "firstName", first);
lastName = new SimpleStringProperty(this, "lastName", last);
}
public void setFirstName(String value) {
firstNameProperty().set(value);
}
public String getFirstName() {
return firstNameProperty().get();
}
public StringProperty firstNameProperty() {
if(firstName == null)
firstName = new SimpleStringProperty(this, "firstName", "First");
return firstName;
}
public void setLastName(String value) {
lastNameProperty().set(value);
}
public String getLastName() {
return lastNameProperty().get();
}
public StringProperty lastNameProperty() {
if(lastName == null)
lastName = new SimpleStringProperty(this, "lastName", "Last");
return lastName;
}
}
public static void main(String[] args) {
launch(args);
}
}
If you create your observable list with an extractor, for example:
ObservableList<Person> data = FXCollections.observableArrayList(person ->
new Observable[] { person.lastNameProperty() });
then the list will fire update notifications any time any of the specified properties change in any of the elements (in this case, any time the lastName changes on anything in the list).
So now you can create a binding for invalid:
BooleanBinding invalid = Bindings.createBooleanBinding(
() -> data.stream().anyMatch(person -> person.getLastName().isEmpty()),
data);
And then you can just observe that binding:
invalid.addListener((obs, wasInvalid, isNowInvalid) -> {
if (isNowInvalid) {
// show alert, etc...
}
});
or disable a node by binding to it:
someNode.disableProperty().bind(invalid);
You could similarly bind this invalid property in your TableColumn subclass (if you still need that) to this binding.

How to sort column in TableView JavaFx?

I'm trying to sort the columns by clicking the column head. The problem is that he does not sort the column defined as Integer.
I wrote comparator for Integer but I think that this is not the way to sort column.
The code below belongs the client:
public class Client4 extends Application
{ // IO streams
private DataOutputStream toServer = null;
private DataInputStream fromServer = null;
private TableView<Student> tableView = new TableView<Student>();
private ObservableList<Student> data = FXCollections.observableArrayList();
private ComboBox<String> cboStudent = new ComboBox<>();
private ComboBox<String> cboLecturer = new ComboBox<>();
private ArrayList<TableColumn> tableCol = new ArrayList<TableColumn>();
private Callback<TableColumn<Student, String>, TableCell<Student, String>> cellFactory
= (TableColumn<Student, String> p) -> new EditingCell();
#Override // Override the start method in the Application class
public void start(Stage primaryStage) throws Exception
{ // Panel p to hold the label and text field
Button btAddRow = new Button("Add Student");
Button btDeleteRow = new Button("Delete Student");
Button btEdit = new Button("Edit");
Button btAddColumn = new Button("Add Column");
Button btDeleteColumn = new Button("Delete Column");
tableView.setItems(data);
//tableView.setEditable(true);
// Callback<TableColumn<Student, String>, TableCell<Student, String>> cellFactory
// = (TableColumn<Student, String> p) -> new EditingCell();
BorderPane pane = new BorderPane();
pane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5));
HBox hBox = new HBox(20);
hBox.getChildren().addAll(btAddRow, btDeleteRow,
btEdit, btAddColumn, btDeleteColumn);
pane.setTop(hBox);
try {
// #SuppressWarnings("resource")
Socket socket = new Socket("localhost", 8000);
// Create an input stream to receive data from the server
fromServer = new DataInputStream(socket.getInputStream());
// Create an output stream to send data to the server
toServer = new DataOutputStream(socket.getOutputStream());
ArrayList<String> lables = new ArrayList<String>();
int numberRecords=0;
numberRecords = fromServer.readInt();
System.out.println(numberRecords);
while (numberRecords>0)
{ String record =fromServer.readUTF();
lables.add(record);
cboStudent.getItems().add(record);
numberRecords--;
}
for(int i=0; i<lables.size();i++)
{
String lable = lables.get(i);
TableColumn<Student, String> string = new TableColumn<Student, String>(lable);
string.setMinWidth(100);
if (lable.equals("firstName") || lable.equals("lastName") || lable.equals("city") || lable.equals("street") || lable.equals("dept") )
{
string.setCellValueFactory(
new PropertyValueFactory<Student, String>(lable));
defineCell(string);
// ObservableList<String> cbValues = FXCollections.observableArrayList("1", "2", "3");
// string.setCellFactory(ComboBoxTableCell.forTableColumn(new DefaultStringConverter(), cbValues));
tableView.getColumns().add(string);
tableCol.add(string);
}
else if(lable.equals("birthDate"))
{
TableColumn<Student, Date> date = new TableColumn<Student, Date>(lable);
date.setCellValueFactory(
new PropertyValueFactory<Student, Date>(lable));
//defineCell(date);
tableView.getColumns().add(date);
tableCol.add(date);
}
else if(lable.equals("picture"))
{
TableColumn<Student, ImageView> pic = new TableColumn<Student, ImageView>(lable);
pic.setCellValueFactory(
new PropertyValueFactory<Student, ImageView>(lable));
tableView.getColumns().add(pic);
tableCol.add(pic);
}
else
{
TableColumn<Student, Integer> integer = new TableColumn<Student, Integer>(lable);
integer.setCellValueFactory(
new PropertyValueFactory<Student, Integer>(lable));
integer.setSortable(true);
integer.setComparator(new Comparator<Integer>() {
#Override
public int compare(Integer o1, Integer o2) {
if(o1<o2) return 1;
if(o1>o2)return -1;
return 0;
}
});
tableView.getColumns().add(integer);
tableCol.add(integer);
}
}
numberRecords=0;
numberRecords=fromServer.readInt();
while(numberRecords>0)
{ Student student = new Student();
student.setId(fromServer.readUTF());
student.setFirstName(fromServer.readUTF());
student.setLastName(fromServer.readUTF());
student.setCity(fromServer.readUTF());
student.setStreet(fromServer.readUTF());
student.setHouseNumber(fromServer.readUTF());
student.setZipCode(fromServer.readUTF());
student.setBirthDate(fromServer.readUTF());
student.setPicture(fromServer.readUTF());
student.setStartYear(fromServer.readUTF());
student.setDept(fromServer.readUTF());
student.setCredits(fromServer.readUTF());
student.setAverage(fromServer.readUTF());
student.setNumFailed(fromServer.readUTF());
student.setPlace(fromServer.readUTF());
System.out.println(student);
data.add(student);
numberRecords--;
}
tableView.setItems(data);
}
catch (IOException ex) {
}
btEdit.setOnAction(e -> {
editTable(btEdit.toString());
});
pane.setBottom(tableView);
Scene scene = new Scene(pane, 890, 400);
primaryStage.setTitle("ShowCombination"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
primaryStage.setAlwaysOnTop(true);
}
private void defineCell(TableColumn<Student, String> string) {
string.setCellFactory(cellFactory);
string.setOnEditCommit(
(CellEditEvent<Student, String> t) -> {
((Student) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setFirstName(t.getNewValue());
});
ObservableList<String> cbValues = FXCollections.observableArrayList("1", "2", "3");
string.setCellFactory(ComboBoxTableCell.forTableColumn(new DefaultStringConverter(), cbValues));
}
private void editTable(String string) {
tableView.setEditable(true);
Student student=(Student)tableView.getSelectionModel().getSelectedItem();
}
public static void main(String[] args)
{ launch(args);
}
class EditingCell extends TableCell<Student, String> {
private TextField textField;
public EditingCell() {
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
setGraphic(null);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
textField.focusedProperty().addListener(
(ObservableValue<? extends Boolean> arg0,
Boolean arg1, Boolean arg2) -> {
if (!arg2) {
commitEdit(textField.getText());
}
});
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}
}
You need to wrap your ObservableList holding the TableView data in a SortedList:
SortedList<Student> sortedItems = new SortedList<>(data);
tableView.setItems(sortedItems);
Next you need to link both together:
sortedItems.comparatorProperty().bind(tableView.comparatorProperty());
And as a friendly side note: Please consider posting a smaller code example showing only what is necessary to demonstrate your problem ;-)
As James_D says, cube root will sort in the same order, but here's a little example you can use to show what you're trying to do
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javafx.application.Application;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
public class TableSort extends Application {
#Override
public void start(Stage primaryStage) {
TableView tv = new TableView(FXCollections.observableArrayList(
IntStream.of(1,-2,3,-4,-5,6)
.map(n->{return (int)Math.pow(n, 3);})
.boxed().collect(Collectors.toList())));
TableColumn<Integer, Integer> numCol = new TableColumn("num");
numCol.setCellValueFactory((param) -> {
return new ReadOnlyObjectWrapper<>(param.getValue());
});
TableColumn<Integer, Integer> cbrtCol = new TableColumn("cube root");
cbrtCol.setCellValueFactory((param) -> {
return new ReadOnlyObjectWrapper<>((int)Math.cbrt(param.getValue()));
});
numCol.setComparator((Integer o1, Integer o2) -> {
return Double.compare(Math.cbrt(o1), Math.cbrt(o2));
});
tv.getColumns().addAll(numCol, cbrtCol);
Scene scene = new Scene(tv);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Multiple Components in one column of JavaFX TableView

I am working with JavaFx 2.2. I am having a problem that I am not able to place different components in a TableView Column. For example I have two columns
1) Answer
2) AnswerType
If AnswerType contains “Multiple Choice” then the corresponding cell in Answer Column should display a ComboBox else it should display a TextField.
I have a code example below but its displaying either ComboBox or TextField but not both in different cells of same column.
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.scene.control.cell.ComboBoxTableCell;
public class TableCellWithMultipleComponent extends Application {
#SuppressWarnings("rawtypes")
TableColumn answerTypeCol;
#SuppressWarnings("rawtypes")
TableColumn answerCol;
ObservableList<String> namesChoiceList;
public static void main(String[] args) {
launch(args);
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#Override
public void start(final Stage primaryStage) {
primaryStage.setTitle("Table Cell With Multiple Components");
TableView<Person> table = new TableView<Person>();
table.setEditable(true);
final ObservableList<Person> data =
FXCollections.observableArrayList(
new Person("A", "Multiple Choice"),
new Person("JOHN", "Free Text"),
new Person("123", "Free Text"),
new Person("D", "Multiple Choice")
);
GridPane gridpane = new GridPane();
gridpane.setPadding(new Insets(5));
gridpane.setHgap(5);
gridpane.setVgap(5);
namesChoiceList = FXCollections.observableArrayList("A", "B", "C", "D", "INVALID_ANSWER", "NO_ANSWER");
answerCol = new TableColumn();
answerCol.setText("Answers");
answerCol.setMinWidth(210);
answerCol.setEditable(true);
answerCol.setCellValueFactory(new PropertyValueFactory("answers"));
answerCol.setCellFactory( new Callback<TableColumn<String, String>, TableCell<String, String>>() {
#Override
public TableCell<String, String> call(TableColumn<String, String> arg0) {
return new anyMethod();
}
});
answerTypeCol = new TableColumn();
answerTypeCol.setText("Answers Type");
answerTypeCol.setMinWidth(210);
answerTypeCol.setEditable(true);
answerTypeCol.setCellValueFactory(new PropertyValueFactory("answersType"));
table.setItems(data);
table.getColumns().addAll(answerCol, answerTypeCol);
StackPane root = new StackPane();
Scene scene =new Scene(root, 500, 550);
gridpane.add(table, 1, 5,1,20 );
root.getChildren().addAll(gridpane);
primaryStage.setScene(scene);
primaryStage.show();
}
private class anyMethod extends TableCell <String, String>{
#SuppressWarnings("unchecked")
#Override
protected void updateItem(String item, boolean arg1) {
super.updateItem(item, arg1);
answerCol.setCellFactory(ComboBoxTableCell.<String, String>forTableColumn(namesChoiceList));
/**** I have to execute this commented code so that if the column cell has text "Multiple Choice" then
* it displays the comboBox otherwise it displays the text field in the Table View cell
if (item.equalsIgnoreCase("Multiple Choice")){
answerCol.setCellFactory(ComboBoxTableCell.<String, String>forTableColumn(namesChoiceList));
}
else{
//answerCol.setCellFactory(TextFieldTableCell.<String>forTableColumn());
}
****/
}
}
public static class Person {
private final SimpleStringProperty answers;
private final SimpleStringProperty answersType;
private Person(String answers, String answersType) {
this.answers = new SimpleStringProperty(answers);
this.answersType = new SimpleStringProperty(answersType);
}
public String getAnswers() {
return answers.get();
}
public void setAnswers(String answers) {
this.answers.set(answers);
}
public String getAnswersType() {
return answersType.get();
}
public void setAnswersType(String answersType) {
this.answersType.set(answersType);
}
}
}
Here is a sample for an EditingCell which renders a different control in the cell (TextEdit field or Checkbox) depending on the type of data represented by the Cell's backing field (String or Boolean). Complete executable code is available as a gist.
For your particular example, use the same concept except query the type for either a String => TextField or ObservableList => combobox. Also, for your particular sample, ChoiceBox may be a simpler control to use than ComboBox.
class EditingCell extends TableCell<NamedProperty, Object> {
private TextField textField;
private CheckBox checkBox;
public EditingCell() {}
#Override public void startEdit() {
if (!isEmpty()) {
super.startEdit();
if (getItem() instanceof Boolean) {
createCheckBox();
setText(null);
setGraphic(checkBox);
} else {
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
}
#Override public void cancelEdit() {
super.cancelEdit();
if (getItem() instanceof Boolean) {
setText(getItem().toString());
} else {
setText((String) getItem());
}
setGraphic(null);
}
#Override public void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (getItem() instanceof Boolean) {
if (checkBox != null) {
checkBox.setSelected(getBoolean());
}
setText(null);
setGraphic(checkBox);
} else {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
}
} else {
setText(getString());
setGraphic(null);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
textField.focusedProperty().addListener(new ChangeListener<Boolean>() {
#Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (!newValue) {
commitEdit(textField.getText());
}
}
});
}
private void createCheckBox() {
checkBox = new CheckBox();
checkBox.setSelected(getBoolean());
checkBox.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
checkBox.focusedProperty().addListener(new ChangeListener<Boolean>() {
#Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (!newValue) {
commitEdit(checkBox.isSelected());
}
}
});
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
private Boolean getBoolean() {
return getItem() == null ? false : (Boolean) getItem();
}
}
Bellow is the working code for my question. Thank jewelsea
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;
public class TableCellWithMultipleComponent extends Application {
#SuppressWarnings("rawtypes")
TableColumn answerTypeCol;
#SuppressWarnings("rawtypes")
TableColumn answerCol;
ObservableList<String> namesChoiceList;
#SuppressWarnings("rawtypes")
ComboBox comboBox;
TextField textField;
public static void main(String[] args) {
launch(args);
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#Override
public void start(final Stage primaryStage) {
primaryStage.setTitle("Table Cell With Multiple Components");
TableView<Person> table = new TableView<Person>();
table.setEditable(true);
final ObservableList<Person> data =
FXCollections.observableArrayList(
new Person("A", "Multiple Choice"),
new Person("JOHN", "Free Text"),
new Person("123", "Free Text"),
new Person("D", "Multiple Choice")
);
GridPane gridpane = new GridPane();
gridpane.setPadding(new Insets(5));
gridpane.setHgap(5);
gridpane.setVgap(5);
namesChoiceList = FXCollections.observableArrayList("A", "B", "C", "D", "INVALID_ANSWER", "NO_ANSWER");
answerCol = new TableColumn();
answerCol.setText("Answers");
answerCol.setMinWidth(210);
answerCol.setEditable(true);
answerCol.setCellValueFactory(new PropertyValueFactory("answers"));
answerCol.setCellFactory( new Callback<TableColumn<String, String>, TableCell<String, String>>() {
#Override
public TableCell<String, String> call(TableColumn<String, String> arg0) {
return new anyMethod();
}
});
answerTypeCol = new TableColumn();
answerTypeCol.setText("Answers Type");
answerTypeCol.setMinWidth(210);
answerTypeCol.setEditable(true);
answerTypeCol.setCellValueFactory(new PropertyValueFactory("answersType"));
table.setItems(data);
table.getColumns().addAll(answerCol, answerTypeCol);
StackPane root = new StackPane();
Scene scene =new Scene(root, 500, 550);
gridpane.add(table, 1, 5,1,20 );
root.getChildren().addAll(gridpane);
primaryStage.setScene(scene);
primaryStage.show();
}
private class anyMethod extends TableCell <String, String>{
#SuppressWarnings({ "unchecked", "rawtypes" })
public anyMethod(){
comboBox = new ComboBox();
textField = new TextField();
comboBox.setItems(namesChoiceList);
}
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
System.out.println("In empty");
} else {
if( getTableView().getColumns().get(1).getCellData(getIndex()).toString().startsWith("M")){
System.out.println("Making ComboBox");
setGraphic(comboBox);
}
else{
setGraphic(textField);
}
}
}
}
public static class Person {
private final SimpleStringProperty answers;
private final SimpleStringProperty answersType;
private Person(String answers, String answersType) {
this.answers = new SimpleStringProperty(answers);
this.answersType = new SimpleStringProperty(answersType);
}
public String getAnswers() {
return answers.get();
}
public void setAnswers(String answers) {
this.answers.set(answers);
}
public String getAnswersType() {
return answersType.get();
}
public void setAnswersType(String answersType) {
this.answersType.set(answersType);
}
}
}

Resources