JavaFX datepicker - how to update date in a second datepicker object? - javafx

Problem:
I've two datepicker object checkIn_date and checkOut_date in the same scene.
There is a way to change automatically the date field in the second datepicker object?
For example : checkIn_date is set with 2015-08-10 and checkOut_date is set with 2015-08-11. If I change the date field in checkIn_date i.e. 2015-08-22, checkOut_date update automatically to 2015-08-23.
Thanks for any advices.

You can achieve this by adding a listener to your check-in DatePicker, fetch the new value, add the no of days you want to it and update the new value to the check-out DatePicker.
Here is a MCVE to give more idea on what I meant :
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
private final int noOfDaysToAdd = 2;
#Override
public void start(Stage primaryStage) throws Exception {
VBox root = new VBox(10);
root.setAlignment(Pos.CENTER);
Label checkInLabel = new Label("Check In : ");
Label checkOutLabel = new Label("Check Out : ");
DatePicker picker1 = new DatePicker();
DatePicker picker2 = new DatePicker();
// Listener for updating the checkout date w.r.t check in date
picker1.valueProperty().addListener((ov, oldValue, newValue) -> {
picker2.setValue(newValue.plusDays(noOfDaysToAdd));
});
HBox checkInBox = new HBox(10, checkInLabel, picker1);
HBox checkOutBox = new HBox(10, checkOutLabel, picker2);
checkInBox.setAlignment(Pos.CENTER);
checkOutBox.setAlignment(Pos.CENTER);
root.getChildren().addAll(checkInBox, checkOutBox);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Output:
Update
You can re-write the snippet
picker1.valueProperty().addListener((ov, oldValue, newValue) -> {
picker2.setValue(newValue.plusDays(noOfDaysToAdd));
});
without the lambda as :
picker1.valueProperty().addListener(new ChangeListener<LocalDate>() {
#Override
public void changed(ObservableValue<? extends LocalDate> observable, LocalDate oldValue, LocalDate newValue) {
picker2.setValue(newValue.plusDays(noOfDaysToAdd));
}
});

First thanks for the help!
I've fixed my problem from another point of view.
When scene/view has been loaded either datepicker are set to current date for check-in and the day after the curent day for check-out date.
For check-in day I've disabled the selection of days before the current date and after check-out date.
For check-out day I've disabled the selection of days before check-out date.
Unfortunately I can't post any image because my reputation is not 10!
But this is the code for the controller class:
import java.time.LocalDate;
import javafx.fxml.FXML;
import javafx.scene.control.DatePicker;
import com.main.controller.checker.DateChecker;
import com.main.controller.datautil.DataFetch;
import com.main.controller.datautil.DataStore;
import com.main.controller.util.Initilizable;
public class SearchCtrl implements Initilizable{
#FXML
private DatePicker check_in;
#FXML
private DatePicker check_out;
#Override
public void init() {
check_in.setValue(LocalDate.now());
check_out.setValue(check_in.getValue().plusDays(1));
DateChecker.setBeginDateBounds(check_in, check_out.getValue());
DateChecker.setEndDateBounds(check_out, check_in.getValue());
check_in.setOnAction( (event) -> {DateChecker.setEndDateBounds(check_out, check_in.getValue());});
datafine.setOnAction( (event) -> {DateChecker.setBeginDateBounds(check_in, check_out.getValue());});
}
This is the DateChecker class:
import java.time.LocalDate;
import javafx.scene.control.DateCell;
import javafx.scene.control.DatePicker;
import javafx.util.Callback;
public class DateChecker {
private DateChecker(){
}
public static void setBeginDateBounds(DatePicker begin_date, LocalDate end_date ){
final Callback<DatePicker, DateCell> dayCellFactory = new Callback<DatePicker, DateCell>() {
#Override
public DateCell call(final DatePicker datePicker) {
return new DateCell() {
#Override
public void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
boolean cond = (item.isBefore(LocalDate.now()) || !item.isBefore(end_date));
if (cond){
setDisable(true);
setStyle("-fx-background-color: #d3d3d3;");
}else{
setDisable(false);
setStyle("-fx-background-color: #CCFFFF;");
setStyle("-fx-font-fill: black;");
}
}
};
}
};
begin_date.setDayCellFactory(dayCellFactory);
}
public static void setEndDateBounds(DatePicker end_date, LocalDate begin_date ){
final Callback<DatePicker, DateCell> dayCellFactory = new Callback<DatePicker, DateCell>() {
#Override
public DateCell call(final DatePicker datePicker) {
return new DateCell() {
#Override
public void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
boolean cond = (item.isBefore(LocalDate.now()) || !item.isAfter(begin_date));
if (cond){
setDisable(true);
setStyle("-fx-background-color: #d3d3d3;");
}else{
setDisable(false);
setStyle("-fx-background-color: #CCFFFF;");
setStyle("-fx-font-fill: black;");
}
}
};
}
};
end_date.setDayCellFactory(dayCellFactory);
}
}
I hope this will help!

Related

JavaFx Tableview checkbox requires focus

I implemented boolean representation in my tableView as checkbox. It works fine in general but very irritating fact is that it requires row to be focused (editing) to apply change of checkbox value. It means I first have to double click on the field and then click checkbox.
How to make checkbox change perform onEditCommit right away?
public class BooleanCell<T> extends TableCell<T, Boolean> {
private CheckBox checkBox;
public BooleanCell() {
checkBox = new CheckBox();
checkBox.selectedProperty().addListener(new ChangeListener<Boolean>() {
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (isEditing())
commitEdit(newValue == null ? false : newValue);
}
});
setAlignment(Pos.CENTER);
this.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
this.setEditable(true);
}
#Override
public void updateItem(Boolean item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
checkBox.setSelected(item);
setGraphic(checkBox);
}
}
}
I'm not sure about the rest of your implementation, but I assume you do not have your TableView set to editable:
tableView.setEditable(true);
On a side note, you could easily use a CheckBoxTableCell instead of implementing your own (BooleanCell).
Here is a very simple application you can run to see how this works. Each CheckBox may be clicked without first focusing the row and its value updates your underlying model as well (which you can see by clicking the "Print List" button).
import javafx.application.Application;
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.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class CheckBoxTableViewSample extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
// Simple interface
VBox root = new VBox(5);
root.setPadding(new Insets(10));
root.setAlignment(Pos.CENTER);
// List of sample items
ObservableList<MyItem> myItems = FXCollections.observableArrayList();
myItems.addAll(
new MyItem(false, "Item 1"),
new MyItem(false, "Item 2"),
new MyItem(true, "Item 3"),
new MyItem(false, "Item 4"),
new MyItem(false, "Item 5")
);
// Create TableView
TableView<MyItem> tableView = new TableView<MyItem>();
// We need the TableView to be editable in order to allow each CheckBox to be selectable
tableView.setEditable(true);
// Create our table Columns
TableColumn<MyItem, Boolean> colSelected = new TableColumn<>("Selected");
TableColumn<MyItem, String> colName = new TableColumn<>("Name");
// Bind the columns with our model's properties
colSelected.setCellValueFactory(f -> f.getValue().selectedProperty());
colName.setCellValueFactory(f -> f.getValue().nameProperty());
// Set the CellFactory to use a CheckBoxTableCell
colSelected.setCellFactory(param -> {
return new CheckBoxTableCell<MyItem, Boolean>();
});
// Add our columns to the TableView
tableView.getColumns().addAll(colSelected, colName);
// Set our items to the TableView
tableView.setItems(myItems);
// Create a button to print out our list of items
Button btnPrint = new Button("Print List");
btnPrint.setOnAction(event -> {
System.out.println("-------------");
for (MyItem item : myItems) {
System.out.println(item.getName() + " = " + item.isSelected());
}
});
root.getChildren().addAll(tableView, btnPrint);
// Show the Stage
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
/**
* Just a simple sample class to display in our TableView
*/
final class MyItem {
// This property will be bound to the CheckBoxTableCell
private final BooleanProperty selected = new SimpleBooleanProperty();
// The name of our Item
private final StringProperty name = new SimpleStringProperty();
public MyItem(boolean selected, String name) {
this.selected.setValue(selected);
this.name.set(name);
}
public boolean isSelected() {
return selected.get();
}
public BooleanProperty selectedProperty() {
return selected;
}
public void setSelected(boolean selected) {
this.selected.set(selected);
}
public String getName() {
return name.get();
}
public StringProperty nameProperty() {
return name;
}
public void setName(String name) {
this.name.set(name);
}
}

How to set the editability of a TextFieldTableCell based on whether or not a CheckBoxTableCell is selected in a JavaFX8 TableView?

I'm trying to set the editability of a TextFieldTableCell depending on whether or not a CheckBoxTableCell (that's in the same row) is ticked. So, for example, if the check box in the second row is ticked as shown below, the text at "B" should be editable. If the check box is unticked, "B" should not be editable.
My plan is to set the TextFieldTableCell's editability in the "selected" listener in the CheckBoxTableCell's setCellFactory. Alternatively, I could set it in the TableView's ListChangeListener.
However, either way, I first have to get the TextFieldTableCell object that's in the same row as the clicked CheckBoxTableCell.
How do I do that? I've been stuck for a couple of days trying to figure it out.
Here's a code snippet for the CheckBoxTableCell's "selected" listener that shows what I'm trying to do and where I'm stuck:
selected.addListener((ObservableValue<? extends Boolean> obs, Boolean wasSelected, Boolean isSelected) -> {
olTestModel.get(cbCell.getIndex()).setCheckbox(isSelected);
//=>TextFieldTableCell theTextFieldInThisRow = <HOW_DO_I_GET_THIS?>
theTextFieldInThisRow.setEditable(isSelected);
});
I've read and experimented with Make individual cell editable in JavaFX tableview, Javafx, get the object referenced by a TableCell and Tableview make specific cell or row editable. While I think I understand them, I haven't been able to adapt them to do what I'm trying to do.
Here is the MVCE for the example shown above.
I'm using JavaFX8 (JDK1.8.0_181), NetBeans 8.2 and Scene Builder 8.3.
package test24;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.beans.Observable;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.util.Callback;
public class Test24 extends Application {
private Parent createContent() {
//********************************************************************************************
//Declare the TableView and its underlying ObservableList and change listener
TableView<TestModel> table = new TableView<>();
ObservableList<TestModel> olTestModel = FXCollections.observableArrayList(testmodel -> new Observable[] {
testmodel.checkboxProperty()
});
olTestModel.addListener((ListChangeListener.Change<? extends TestModel > c) -> {
while (c.next()) {
if (c.wasUpdated()) {
boolean checkBoxIsSelected = olTestModel.get(c.getFrom()).getCheckbox().booleanValue();
//PLAN A: Set editability here
//==>TextFieldTableCell theTextFieldInThisRow = <HOW_DO_I_GET_THIS?>
//theTextFieldInThisRow.setEditable(checkBoxIsSelected);
}
}
});
olTestModel.add(new TestModel(false, "A"));
olTestModel.add(new TestModel(false, "B"));
olTestModel.add(new TestModel(false, "C"));
table.setItems(olTestModel);
//********************************************************************************************
//Declare the text column whose editability needs to change depending on whether or
//not the CheckBox is ticked
TableColumn<TestModel, String> colText = new TableColumn<>("text");
colText.setCellValueFactory(cellData -> cellData.getValue().textProperty());
colText.setCellFactory(TextFieldTableCell.<TestModel>forTableColumn());
colText.setEditable(false);
//********************************************************************************************
//Declare the CheckBox column
TableColumn<TestModel, Boolean> colCheckbox = new TableColumn<>("checkbox");
colCheckbox.setCellValueFactory(cellData -> cellData.getValue().checkboxProperty());
colCheckbox.setCellFactory((TableColumn<TestModel, Boolean> cb) -> {
final CheckBoxTableCell cbCell = new CheckBoxTableCell<>();
final BooleanProperty selected = new SimpleBooleanProperty();
cbCell.setSelectedStateCallback(new Callback<Integer, ObservableValue<Boolean>>() {
#Override
public ObservableValue<Boolean> call(Integer index) {
return selected;
}
});
selected.addListener((ObservableValue<? extends Boolean> obs, Boolean wasSelected, Boolean isSelected) -> {
//Set the value in the data model
olTestModel.get(cbCell.getIndex()).setCheckbox(isSelected);
//PLAN B: Set editability here
//Set the editability for the text field in this row
//==> TextFieldTableCell theTextFieldInThisRow = <HOW_DO_I_GET_THIS?>
//theTextFieldInThisRow.setEditable(isSelected);
});
return cbCell;
});
//********************************************************************************************
//Column to show what's actually in the TableView's data model for the checkbox
TableColumn<TestModel, Boolean> colDMVal = new TableColumn<>("data model value");
colDMVal.setCellValueFactory(cb -> cb.getValue().checkboxProperty());
colDMVal.setEditable(false);
table.getSelectionModel().setCellSelectionEnabled(true);
table.setEditable(true);
table.getColumns().add(colCheckbox);
table.getColumns().add(colDMVal);
table.getColumns().add(colText);
BorderPane content = new BorderPane(table);
return content;
}
public class TestModel {
private BooleanProperty checkbox;
private StringProperty text;
public TestModel() {
this(false, "");
}
public TestModel(
boolean checkbox,
String text
) {
this.checkbox = new SimpleBooleanProperty(checkbox);
this.text = new SimpleStringProperty(text);
}
public Boolean getCheckbox() {
return checkbox.get();
}
public void setCheckbox(boolean checkbox) {
this.checkbox.set(checkbox);
}
public BooleanProperty checkboxProperty() {
return checkbox;
}
public String getText() {
return text.get();
}
public void setText(String text) {
this.text.set(text);
}
public StringProperty textProperty() {
return text;
}
}
#Override
public void start(Stage stage) throws Exception {
stage.setScene(new Scene(createContent()));
stage.setTitle("Test");
stage.setWidth(500);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
After applying user kleopatra's suggestions, I was able to get this working.
The easiest solution is to simply ignore edits if the CheckBoxTableCell isn't ticked. This is described in the accepted answer here TreeTableView : setting a row not editable and is what I've used in the MVCE below.
Alternatively, the TextFieldTableCell's editability can be set by binding its editableProperty() to the CheckBoxTableCell's value. Following the accepted answer here JavaFX weird (Key)EventBehavior, the code looks like this:
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
doUpdate(item, getIndex(), empty);
}
#Override
public void updateIndex(int index) {
super.updateIndex(index);
doUpdate(getItem(), index, isEmpty());
}
private void doUpdate(String item, int index, boolean empty) {
if ( empty || index == getTableView().getItems().size() ) {
setText(null);
} else {
BooleanProperty checkboxProperty = getTableView().getItems().get(getIndex()).checkboxProperty();
editableProperty().bind(checkboxProperty);
}
}
While the solution is not based on getting the TextFieldTableCell's object (which was what I thought I needed to do), it does do exactly what I need (to set a text field's editability based on a checkbox value). Thank you kleopatra for pointing me in the right direction.
Here is the MVCE that demonstrates the solution.
package test24;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.beans.Observable;
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.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.util.converter.DefaultStringConverter;
public class Test24 extends Application {
private Parent createContent() {
//********************************************************************************************
//Declare the TableView and its underlying ObservableList and change listener
TableView<TestModel> table = new TableView<>();
ObservableList<TestModel> olTestModel = FXCollections.observableArrayList(testmodel -> new Observable[] {
testmodel.checkboxProperty()
});
olTestModel.addListener((ListChangeListener.Change<? extends TestModel > c) -> {
while (c.next()) {
if (c.wasUpdated()) {
//...
}
}
});
olTestModel.add(new TestModel(false, "A"));
olTestModel.add(new TestModel(false, "B"));
olTestModel.add(new TestModel(false, "C"));
table.setItems(olTestModel);
//********************************************************************************************
//Declare the CheckBox column
TableColumn<TestModel, Boolean> colCheckbox = new TableColumn<>("checkbox");
colCheckbox.setCellValueFactory(cellData -> cellData.getValue().checkboxProperty());
colCheckbox.setCellFactory(CheckBoxTableCell.forTableColumn(colCheckbox));
//********************************************************************************************
//Declare the text column whose editability needs to change depending on whether or
//not the CheckBox is ticked
TableColumn<TestModel, String> colText = new TableColumn<>("text");
colText.setCellValueFactory(cellData -> cellData.getValue().textProperty());
//Don't setEditable() to false here, otherwise updateItem(), updateIndex() and startEdit() won't fire
colText.setEditable(true);
colText.setCellFactory(cb -> {
DefaultStringConverter converter = new DefaultStringConverter();
TableCell<TestModel, String> cell = new TextFieldTableCell<TestModel, String>(converter) {
#Override
public void startEdit() {
boolean checkbox = getTableView().getItems().get(getIndex()).getCheckbox();
if ( checkbox == true ) {
super.startEdit();
}
}
};
return cell;
});
//********************************************************************************************
//Column to show what's actually in the TableView's data model for the checkbox
TableColumn<TestModel, Boolean> colDMVal = new TableColumn<>("data model value");
colDMVal.setCellValueFactory(cb -> cb.getValue().checkboxProperty());
colDMVal.setEditable(false);
table.getSelectionModel().setCellSelectionEnabled(true);
table.setEditable(true);
table.getColumns().add(colCheckbox);
table.getColumns().add(colDMVal);
table.getColumns().add(colText);
BorderPane content = new BorderPane(table);
return content;
}
public class TestModel {
private BooleanProperty checkbox;
private StringProperty text;
public TestModel() {
this(false, "");
}
public TestModel(
boolean checkbox,
String text
) {
this.checkbox = new SimpleBooleanProperty(checkbox);
this.text = new SimpleStringProperty(text);
}
public Boolean getCheckbox() {
return checkbox.get();
}
public void setCheckbox(boolean checkbox) {
this.checkbox.set(checkbox);
}
public BooleanProperty checkboxProperty() {
return checkbox;
}
public String getText() {
return text.get();
}
public void setText(String text) {
this.text.set(text);
}
public StringProperty textProperty() {
return text;
}
}
#Override
public void start(Stage stage) throws Exception {
stage.setScene(new Scene(createContent()));
stage.setTitle("Test");
stage.setWidth(500);
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}

JavaFX Disable TableColumn based on checkbox state

Am looking to disable a TableColumn<CustomObject, String> tableColumn based on a field value in the CustomObject only when the TableColumn<CustomObject, Boolean> tableColumnTwo checkbox is checked. I can disable the textbox inside public void updateItem(String s, boolean empty) however not sure how to check the state of checkbox inside updateItem
Below is the relevant code snippet, would highly appreciate if anyone can shed light on this
#FXML
private TableColumn<CustomObject, Boolean> tableColumnTwo;
#FXML
private TableColumn<CustomObject, String> tableColumn;
tableColumn.setCellFactory(
new Callback<TableColumn<CustomObject, String>, TableCell<CustomObject, String>>() {
#Override
public TableCell<CustomObject, String> call(TableColumn<CustomObject, String> paramTableColumn) {
return new TextFieldTableCell<CustomObject, String>(new DefaultStringConverter()) {
#Override
public void updateItem(String s, boolean empty) {
super.updateItem(s, empty);
TableRow<CustomObject> currentRow = getTableRow();
if(currentRow.getItem() != null && !empty) {
if (currentRow.getItem().getPetrified() == false) { // Need to check if checkbox is checked or not
setDisable(true);
setEditable(false);
this.setStyle("-fx-background-color: red");
} else {
setDisable(false);
setEditable(true);
setStyle("");
}
}
}
};
}
});
You can add a listener on the checkbox, which when checked will cause the table refresh.
data = FXCollections.observableArrayList(new Callback<CustomObject, Observable[]>() {
#Override
public Observable[] call(CustomObject param) {
return new Observable[]{param.petrifiedProperty()};
}
});
data.addListener(new ListChangeListener<CustomObject>() {
#Override
public void onChanged(ListChangeListener.Change<? extends CustomObject> c) {
while (c.next()) {
if (c.wasUpdated()) {
tableView.setItems(null);
tableView.layout();
tableView.setItems(FXCollections.observableList(data));
}
}
}
});
Your cellFactory would remain the same and would get called when a checkbox is checked/unchecked.
Usually, we expect cells being updated whenever they are notified about a change in the underlying data. To make certain that a notification is fired by the data on changing a property of an item, we need a list with an extractor on the properties that we are interested in, something like:
ObservableList<CustomObject> data = FXCollections.observableArrayList(
c -> new Observable[] {c.petrifiedProperty()}
);
With that in place the list fires a list change of type update whenever the pretified property changes.
Unfortunately, that's not enough due to a bug in fx: cells are not updated when receiving a listChange of type update from the underlying items. A dirty way around (read: don't use once the bug is fixed, it's using emergency api!) is to install a listener on the items and call table.refresh() when receiving an update.
An example:
import java.util.logging.Logger;
//import de.swingempire.fx.util.FXUtils;
import javafx.application.Application;
import javafx.beans.Observable;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.CheckBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.util.converter.DefaultStringConverter;
/**
* CheckBoxTableCell: update editable state of one column based of
* the boolean in another column
* https://stackoverflow.com/q/46290417/203657
*
* Bug in skins: cell not updated on listChange.wasUpdated
*
* reported as
* https://bugs.openjdk.java.net/browse/JDK-8187665
*/
#SuppressWarnings({ "rawtypes", "unchecked" })
public class TableViewUpdateBug extends Application {
/**
* TableCell that updates state based on another value in the row.
*/
public static class DisableTextFieldTableCel extends TextFieldTableCell {
public DisableTextFieldTableCel() {
super(new DefaultStringConverter());
}
/**
* Just to see whether or not this is called on update notification
* from the items (it's not)
*/
#Override
public void updateIndex(int index) {
super.updateIndex(index);
// LOG.info("called? " + index);
}
/**
* Implemented to change background based on
* visible property of row item.
*/
#Override
public void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
TableRow<TableColumn> currentRow = getTableRow();
boolean editable = false;
if (!empty && currentRow != null) {
TableColumn column = currentRow.getItem();
if (column != null) {
editable = column.isVisible();
}
}
if (!empty) {
setDisable(!editable);
setEditable(editable);
if (editable) {
this.setStyle("-fx-background-color: red");
} else {
this.setStyle("-fx-background-color: green");
}
} else {
setStyle("-fx-background-color: null");
}
}
}
#Override
public void start(Stage primaryStage) {
// data: list of tableColumns with extractor on visible property
ObservableList<TableColumn> data = FXCollections.observableArrayList(
c -> new Observable[] {c.visibleProperty()});
data.addAll(new TableColumn("first"), new TableColumn("second"));
TableView<TableColumn> table = new TableView<>(data);
table.setEditable(true);
// hack-around: call refresh
data.addListener((ListChangeListener) c -> {
boolean wasUpdated = false;
boolean otherChange = false;
while(c.next()) {
if (c.wasUpdated()) {
wasUpdated = true;
} else {
otherChange = true;
}
}
if (wasUpdated && !otherChange) {
table.refresh();
}
//FXUtils.prettyPrint(c);
});
TableColumn<TableColumn, String> text = new TableColumn<>("Text");
text.setCellFactory(c -> new DisableTextFieldTableCel());
text.setCellValueFactory(new PropertyValueFactory<>("text"));
TableColumn<TableColumn, Boolean> visible = new TableColumn<>("Visible");
visible.setCellValueFactory(new PropertyValueFactory<>("visible"));
visible.setCellFactory(CheckBoxTableCell.forTableColumn(visible));
table.getColumns().addAll(text, visible);
BorderPane root = new BorderPane(table);
Scene scene = new Scene(root, 300, 150);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
#SuppressWarnings("unused")
private static final Logger LOG = Logger
.getLogger(TableViewUpdateBug.class.getName());
}

Allow user to only select Mondays in DatePicker

I am working on a javafx project and I have included a DatePicker. I want to make the user only be able to select Mondays
DatePicker startDate = new DatePicker();
Any Ideas if it's possible?
There are two things you need to do:
Veto the change if the user changes the date in the text field to a date that is not a Monday. You can do this with the converter property of the DatePicker.
Disable all the cells in the popup that are not Mondays. You can do this with the dayCellFactory.
Simple example:
import java.time.DayOfWeek;
import java.time.LocalDate;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.DateCell;
import javafx.scene.control.DatePicker;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.StringConverter;
public class DatePickerMondaysOnly extends Application {
#Override
public void start(Stage primaryStage) {
DatePicker datePicker = new DatePicker();
StringConverter<LocalDate> defaultConverter = datePicker.getConverter();
datePicker.setConverter(new StringConverter<LocalDate>() {
#Override
public String toString(LocalDate object) {
return defaultConverter.toString(object);
}
#Override
public LocalDate fromString(String string) {
LocalDate date = defaultConverter.fromString(string);
if (date.getDayOfWeek() == DayOfWeek.MONDAY) {
return date ;
} else {
// not a Monday. Revert to previous value.
// You could also, e.g., return the closest Monday here.
return datePicker.getValue();
}
}
});
datePicker.setDayCellFactory(dp -> new DateCell() {
#Override
public void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
setDisable(empty || item.getDayOfWeek() != DayOfWeek.MONDAY);
}
});
// Just for debugging: make sure we only see Mondays:
datePicker.valueProperty().addListener((obs, oldDate, newDate) -> {
if (newDate.getDayOfWeek() != DayOfWeek.MONDAY) {
System.out.println("WARNING: date chosen was not a Monday");
}
System.out.println(newDate + " (" + newDate.getDayOfWeek()+")");
});
StackPane root = new StackPane(datePicker);
root.setPadding(new Insets(20));
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

How to fetch value of selected item in choice box from a table view coloumn in javafx

How can i fetch the value of the selected choice from the choce box in the following table.
column3 has 13 choice box nodes populated using following code.I want to fetch the selected item.
final ObservableList LogLevelList=FXCollections.observableArrayList("FATAL", "ERROR", "WARN", "INFO", "INOUT", "DEBUG");
column3.setCellFactory(new Callback<TableColumn<Feature,String>,TableCell<Feature,String>>(){
#Override
public TableCell<Feature,String> call(TableColumn<Feature,String> param) {
TableCell<Feature,String> cell = new TableCell<Feature,String>(){
#Override
public void updateItem(String item, boolean empty) {
System.out.println("Inside UpdateItem");
ChoiceBox choice = new ChoiceBox(LogLevelList);
choice.getSelectionModel().select(LogLevelList.indexOf(item));
//SETTING ALL THE GRAPHICS COMPONENT FOR CELL
setGraphic(choice);
}
};
return cell;
}
});
Does the predefined ChoiceBoxTableCell do what you need?
column3.setCellFactory(ChoiceBoxTableCell.forTableColumn(logLevelList));
See if this helps:
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javafx.application.Application;
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.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.ChoiceBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class TableChoiceBoxTest extends Application {
#Override
public void start(Stage primaryStage) {
final TableView<Feature> table = new TableView<>();
table.setEditable(true);
final TableColumn<Feature, String> nameCol = new TableColumn<>("Name");
nameCol.setCellValueFactory(new PropertyValueFactory<>("name"));
final TableColumn<Feature, String> logLevelCol = new TableColumn<>("Log level");
logLevelCol.setCellValueFactory(new PropertyValueFactory<>("logLevel"));
logLevelCol.setPrefWidth(150);
final ObservableList<String> logLevelList = FXCollections.observableArrayList("FATAL", "ERROR", "WARN", "INFO", "INOUT", "DEBUG");
logLevelCol.setCellFactory(ChoiceBoxTableCell.forTableColumn(logLevelList));
table.getColumns().addAll(nameCol, logLevelCol);
table.getItems().setAll(
IntStream.rangeClosed(1, 20)
.mapToObj(i -> new Feature("Item "+i, "FATAL"))
.collect(Collectors.toList())
);
Button showDataButton = new Button("Dump data");
showDataButton.setOnAction(event -> table.getItems().forEach(System.out::println));
BorderPane root = new BorderPane();
root.setCenter(table);
root.setBottom(showDataButton);
Scene scene = new Scene(root, 400, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
public static class Feature {
private final StringProperty name ;
private final StringProperty logLevel ;
public Feature(String name, String logLevel) {
this.name = new SimpleStringProperty(this, "name", name);
this.logLevel = new SimpleStringProperty(this, "logLevel", logLevel);
}
public StringProperty nameProperty() {
return name ;
}
public final String getName() {
return name.get();
}
public final void setName(String name) {
this.name.set(name);
}
public StringProperty logLevelProperty() {
return logLevel ;
}
public final String getLogLevel() {
return logLevel.get();
}
public final void setLogLevel(String logLevel) {
this.logLevel.set(logLevel);
}
#Override
public String toString() {
return getName() + ": " + getLogLevel();
}
}
public static void main(String[] args) {
launch(args);
}
}
The provided ChoiceBoxTableCell updates the property of the associated item for you, so there's never any need to get the value from the ChoiceBox; you can just get the value from your model object.
I think there are mistakes in your code. You do not want to display your Choice box in each and every cell of that column (i.e Emptied Row's Cell) and Also you should call super class function.
Now for getting the selected value of ChoiceBox , instead of just displaying your choicebox with the values you will have to save them in some ArrayList or Map or best options is to save inside your Feature class. So that you can finally use
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item,empty);
if(item != null){
ChoiceBox choice = new ChoiceBox(LogLevelList);
choice.getSelectionModel().select(LogLevelList.indexOf(item));
choice.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> ov, String t, String t1) {
//either use : myMap.put(getIndex(),t1);
//or : item.setChoice(t1);
}
});
//SETTING ALL THE GRAPHICS COMPONENT FOR CELL
setGraphic(choice);
}
}
Also for demo of ChoiceBox in TableView there is one blog post for you :http://blog.ngopal.com.np/2011/10/01/tableview-cell-modifiy-in-javafx/

Resources