Checkbox cell factory + Tableview on JavaFX - java

I'm writing a JavaFX client for my soap service, and of my fxml pages must contain a fully-editable TableView, which consists of Product-class entities.My table consists now of 2 text columns and one, which consists of Double values.I want to add a selection column with CheckBox items in it cells.Using a Ensemble demo app I extended a Cell class for using a CheckBoxes :
public class CheckBoxCell<S, T> extends TableCell<S, T> {
private final CheckBox checkBox;
private ObservableValue<T> ov;
public CheckBoxCell() {
this.checkBox = new CheckBox();
this.checkBox.setAlignment(Pos.CENTER);
setAlignment(Pos.CENTER);
setGraphic(checkBox);
}
#Override
public void updateItem(T item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
setGraphic(checkBox);
if (ov instanceof BooleanProperty) {
checkBox.selectedProperty().unbindBidirectional((BooleanProperty) ov);
}
ov = getTableColumn().getCellObservableValue(getIndex());
if (ov instanceof BooleanProperty) {
checkBox.selectedProperty().bindBidirectional((BooleanProperty) ov);
}
}
}
#Override
public void startEdit() {
super.startEdit();
if (isEmpty()) {
return;
}
checkBox.setDisable(false);
checkBox.requestFocus();
}
#Override
public void cancelEdit() {
super.cancelEdit();
checkBox.setDisable(true);
}
}
Then in fxml view controller class I set a cellFactory for requed TableColumn :
private Callback<TableColumn, TableCell> createCheckBoxCellFactory() {
Callback<TableColumn, TableCell> cellFactory = new Callback<TableColumn, TableCell> () {
#Override
public TableCell call(TableColumn p) {
return new CheckBoxCell();
}
};
return cellFactory;
}
...
products_table_remove.setCellFactory(createCheckBoxCellFactory());
My question is :
1) how to fill this column with unchecked CheckBoxes using PropertyValueFactory if i have
private final ObservableList <Boolean> productsToRemove= FXCollections.observableArrayList();
consists of Boolean.FALSE values then view is created. (TableView consists of Product class that does'nt have a Boolean property (only 3 String and one Double property)) ?
2) Can i get acess to Product object, which contain selected row using EventHandler :
private void setProductDescColumnCellHandler() {
products_table_remove.setOnEditCommit(new EventHandler() {
#Override
public void handle(CellEditEvent t) {
...
I saw a lot of examples with Entites, which have a Boolean field.In my case, i dont want to add boolean field to jax-ws generated classes.

1) Predefined class javafx.scene.control.cell.CheckBoxTableCell may be used in place of yours.
2) To add information to an existing instance, I suggest inheritance + delegation, for each data instance, instantiate a view instance which may be used to feed the TableView :
class ProductV extends Product {
ProductV( Product product ) {
this.product = product;
}
final Product product;
final BooleanProperty delected = new SimpleBooleanProperty( false );
}

Related

Remove Datepicker rendering from a TableView cell (JavaFX8)

I have a TableView with 2 columns “Date” (LocalDate) and “FX” (Double). I have enabled the cell editing and following an example I found here (http://physalix.com/javafx8-render-a-datepicker-cell-in-a-tableview/) I have created a custom CellFactory that displays a DatePicker for the cells of column “Date”. This solution though renders the DatePciker immediately, so I changed my code to show the DatePicker only when the user double clicks on any of the (non-empty) Date cells. So far so good…
How do I “go back” and remove the DatePicker rendering from the cell after the user has changed the date or cancelled the input? See the pictures as reference. Pic 1 is the initial state of the list. Pic 2 is after double click. How do I go back to Pic 1 status? Let me know if you need to see my specific code.
Reference pictures
This is the code that checks for the double click and then creates the CellFactory
fxTable.getSelectionModel().setCellSelectionEnabled(true);
fxTable.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.getClickCount() == 2) {
TablePosition pos = fxTable.getSelectionModel().getSelectedCells().get(0);
int col = pos.getColumn();
if (col == 0) {
//The code below creates the DatePicker in the cell using the DatePickerCell class that I created following the example in the code I found
tblDateFX.setCellFactory(new Callback<TableColumn<Map.Entry<LocalDate, Double>, String>, TableCell<Map.Entry<LocalDate, Double>, String>>() {
#Override
public TableCell<Map.Entry<LocalDate, Double>, String> call(TableColumn<Map.Entry<LocalDate, Double>, String> param) {
ObservableMap<LocalDate, Double> items = FXCollections.observableMap(myBasket.getEnrtriesCur(curName));
DatePickerCell datePick = new DatePickerCell(items);
return datePick;
}
});
}
}
}
});
This is the DatePickerCell Class
public class DatePickerCell<S, T> extends TableCell<Map.Entry<LocalDate,Double>, String> {
private DatePicker datePicker;
private ObservableMap<LocalDate,Double> curEntries;
public DatePickerCell(ObservableMap<LocalDate,Double> curEntries) {
super();
this.curEntries = curEntries;
if (datePicker == null) {
createDatePicker();
}
setGraphic(datePicker);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
Platform.runLater(new Runnable() {
#Override
public void run() {
datePicker.requestFocus();
}
});
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (null == this.datePicker) {
System.out.println("datePicker is NULL");
}
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
setContentDisplay(ContentDisplay.TEXT_ONLY);
} else {
datePicker.setValue(LocalDate.parse(item,df));
setGraphic(this.datePicker);
setText(item);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
}
}
#Override
public void startEdit() {
super.startEdit();
}
#Override
public void cancelEdit() {
super.cancelEdit();
setContentDisplay(ContentDisplay.TEXT_ONLY);
setGraphic(null);
}
private void createDatePicker() {
this.datePicker = new DatePicker();
datePicker.setEditable(true);
datePicker.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
setGraphic(datePicker);
setText(df.format(datePicker.getValue()));
}
});
datePicker.setOnAction(new EventHandler() {
public void handle(Event t) {
LocalDate date = datePicker.getValue();
int index = getIndex();
commitEdit(df.format(date));
if (null != getCurEntries()) {
System.out.println("Modify value");
}
}
});
setAlignment(Pos.CENTER);
}
Have you tried the function setOnEditCommit to do reverse of your code?
column.setOnEditCommit((TableColumn.CellEditEvent<MyObject, Date> t) -> {
//modify the rendering of you cell to normal
});
After some research I found out that the default rendering of a cell in a TableView is a label. So I tweaked the DatePickerCell class to render a label in the "updateItem" method and render the DatePicker only when the label is clicked (meaning that the user wants to edit the date in the cell).
In terms of "going back" I added a listener for "ESC keypressed" on the DatePicker so when that key is pressed (during the edit) a label is rendered and the edit is therefore cancelled. That works quite well!
I'm still trying to figure out how to do the same when the user tries to cancel the edit by clicking somewhere else on the screen.
--
So here's my stab at the DatePickerEdit class.
This is doing what I need. Renders the cells normally at first, only when the user clicks on the date cell the datepicker is rendered. If the user clicks away from the cell, the cell goes back to its initial rendering (same happens when "ESC" is pressed whilst editing or indeed a new date is picked).
Note that I am passing to the class the Observable list that contains the values shown in the TableView. In this way I can update the value in the list directly in the class. Not sure if this is a good practice or not, this was a "forced solution" though. Originally I used the "setOnEditCommit" method for the TableColumn but after some testing I noticed that this event is not always called after the cell is updated (i.e. the commitEdit() method is called for the cell). Not sure if this is a bug or there's something wrong in my code. For sure it does not always happen. On multiple runs, I would say that 1 out of 3 showed this bugged behaviour.
Here's the code, not sure if it's a "good" code or not. I would appreciate any advice in merit.
public class DatePickerCell<S, T> extends TableCell<FX, String> {
private DatePicker datePicker;
private Label lbl;
private ObservableList<FX> currencies;
public DatePickerCell(ObservableList<FX> list) {
super();
lbl=new Label();
this.currencies=list;
if (datePicker == null) {
createDatePicker();
}
}
#Override
public void updateItem(String item, boolean empty) {
// This section here manages the graphic rendering of each cell
// As I don't want to generate the datepicker graphics immediately I just render a label
super.updateItem(item, empty);
if (empty || item == null) {
setText(null);
setGraphic(null);
} else {
createLabel(item);
}
}
#Override
public void startEdit() {
super.startEdit();
}
#Override
public void cancelEdit() {
super.cancelEdit();
}
private void createDatePicker() {
this.datePicker = new DatePicker();
datePicker.setEditable(true);
// when the user clicks on the label the DatePicker graphics is generated
lbl.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
datePicker.setValue(LocalDate.parse(lbl.getText(),df));
setGraphic(datePicker);
setText(lbl.getText());
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
datePicker.requestFocus();
}
});
// This listener manages the "lost focus" on the picker
datePicker.focusedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
// This combination of OldValue NewValue is generated whenever there is a click outside the DatePicker "graphic area"
// i.e. the calendar (when open), the text filed, the calendar icon OR when a NEW date is selected in the calendar.
// This last case generates the "OnAction" event as well that is managed below.
if (oldValue && !newValue) {
createLabel(df.format(datePicker.getValue()));
}
}
});
// This is generated when a NEW date is picked
// it simply commits the new date and changes the graphics back to a label
datePicker.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
LocalDate date = datePicker.getValue();
int index=getIndex();
if (date!=null) {
commitEdit(df.format(date));
getCurrencies().get(index).setDate(date);
createLabel(df.format(date));
}
}
});
// added this listener in case the user wants to cancel pressing "ESC"
// when this happens the label graphics is rendered
datePicker.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
LocalDate date = datePicker.getValue();
if (event.getCode()== KeyCode.ESCAPE) {
createLabel(df.format(date));
}
}
});
setAlignment(Pos.CENTER_LEFT);
}
private void createLabel(String item) {
lbl.setMinWidth(getWidth());
setGraphic(lbl);
lbl.setText(item);
}
public ObservableList<FX> getCurrencies() {
return currencies;
}
}

"Cannot find symbol constructor, EventHandler does not take parameters" when setting the action for a button in JavaFX

I am creating a program in JavaFX which lists tasks from a data base and displays a button for each row with allows a user to register the task as claimed in the database. I used the code on this link to help me with the buttons for each row: https://gist.github.com/jewelsea/3081826.
However, after changing the code to fit my program, i am getting an error in relation to setting the action of the cellButton variable. I have also added the class that calls this method, just in case.
CANNOT FIND SYMBOL CONSTRUCTOR, EVENTHANDLER DOES NOT TAKE PARAMETERS..
& METHOD DOES NOT OVERRIDE OR IMPLEMENT A METHOD FROM A SUPERTYPE (I am guessing this error is as a result of the first two errors).
//Define the button cell
private class ButtonCell extends TableCell<task, Boolean> {
final Button cellButton = new Button("Claim");
ButtonCell(){
//Action when the button is pressed
cellButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
// get Selected Item
task currentPerson = (task) ButtonCell.this.getTableView().getItems().get(ButtonCell.this.getIndex());
//remove selected item from the table list
newMan.claimTask(currentPerson.getTaskID());
}
});
}
//Display button if the row is not empty
#Override
protected void updateItem(Boolean t, boolean empty) {
super.updateItem(t, empty);
if(!empty){
setGraphic(cellButton);
}
}
}
x
private TableView createTasksTable() {
TableView tableView = new TableView();
TableColumn<task,String> firstNameCol = new TableColumn<>("Task");
firstNameCol.setCellValueFactory(new Callback<CellDataFeatures<task, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(CellDataFeatures<task, String> p) {
// p.getValue() returns the Person instance for a particular TableView row
return new SimpleStringProperty(p.getValue().getName());
}
});
//Insert Button
TableColumn col_action = new TableColumn<>("Action");
tableView.getColumns().add(col_action);
col_action.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<task, Boolean>,
ObservableValue<Boolean>>() {
#Override
public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<task, Boolean> p) {
return new SimpleBooleanProperty(p.getValue() != null);
}
});
//Adding the Button to the cell
col_action.setCellFactory(
new Callback<TableColumn<task, Boolean>, TableCell<task, Boolean>>() {
#Override
public TableCell<task, Boolean> call(TableColumn<task, Boolean> p) {
return new ButtonCell();
} });
tableView.getColumns().addAll(firstNameCol);
return tableView;
}
You have probably imported the wrong EventHandler. Make sure you have
import javafx.event.EventHandler ;
and not something from awt.

JavaFX: Add UI control to TreeTableView

Let's say i have 2 columns in a TreeTableView and now i want to add a string/Label in the first column and a ProgressBar in the other one. How would i accomplish something like this?
Really appreciate any help!
As correctly pointed out by James_D, you can use ProgressBarTreeTableCell for a column with ProgressBars. There is internal supports for some other UI controls such as TextField, CheckBox etc.
For other UI controls you can create a Custom TreeTableCell
as shown:
private class ProgressCell extends TreeTableCell<Employee, String> {
final ProgressBar progress = new ProgressBar();
ProgressCell() {
}
#Override
protected void updateItem(String t, boolean empty) {
super.updateItem(t, empty);
if (!empty) {
setGraphic(progress);
}
}
}
and then assign a CellFactory to the second column
secondCol.setCellFactory(
new Callback<TreeTableColumn<Employee, String>, TreeTableCell<Employee, String>>() {
#Override
public TreeTableCell<Employee, String> call(
TreeTableColumn<Employee, String> param) {
return new ProgressCell();
}
});
where Employee is the POJO class on which the TreeTableView is built

how to add tooltip to the label which is then added to the celltable column?

I have a celltable. I want to add multiple labels with some tooltip assigned to each in one column of a celltable. what i have tried so far -
TextColumn<C> detailsColumn = new TextColumn<C>() {
#Override
public String getValue(C c) {
List<String[]> cList = c.getChngd();
if (cList == null || cList.size() == 0) {
return null;
}
Label lbl;
HorizontalPanel hpanel=new HorizontalPanel();
for (Iterator<String[]> itr =List.iterator(); itr.hasNext();) {
String[] detail = itr.next();
lbl=new Label();
lbl.setText(detail[0]);
lbl.addMouseOverHandler(new MouseOverHandler() {
#Override
public void onMouseOver(MouseOverEvent event) {
Widget source = (Widget)event.getSource();
source.setTitle("tooltip");
}
});
hpanel.add(lbl);
}
return hpanel.getElement().getInnerText();
}
};
Its not working. Any solutions for the same?
I'd move the tooltip logic into the Cell, rather than into the getCell() method of the Column, which is used only to retrieve the underlying data the cell is going to render.
If you want a simple title-based cell, the following should work. It creates a text cell with the data value wrapped in a div with a title.
public class TooltipTextCell extends TextCell {
public interface Template extends SafeHtmlTemplates {
#Template("<div title=\"{1}\" />{0}</div>")
SafeHtml label(SafeHtml text, String title);
}
private static Template template;
public TooltipTextCell() {
super();
if (template == null) {
template = GWT.create(Template.class);
}
}
#Override
public void render(Context context, SafeHtml value, SafeHtmlBuilder sb) {
if (value != null) {
sb.append(template.label(value, value.asString()));
}
}
}
If you want to create a column in which each cell can contain multiple of such TooltipTextCell, you have to use a CompositeCell.

Context Menu visibility in TableView JavaFX

I am creating TableView in JavaFX. In which I want to show Context Menu in right click of mouse in tableView. So I am adding an EventHandler on table as given below :
TableView tableView=new TableView();
EventHandler event = new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent me) {
if (me.getButton() == MouseButton.SECONDARY) {
tableView.getContextMenu().show(tableView, me.getSceneX(), me.getSceneY());
}
}
};
tableView.addEventHandler(MouseEvent.MOUSE_CLICKED, event);
But my problem is that Context Menu is visible wherever I right click on any part of table.
I want to do that Context Menu should be only visible if I clicked on any rows in TableView.
i.e. How would I get row number in TableView at specific point, So that my Context Menu should be only visible, if I clicked on any row of TableView.
The best solution I found was to check if the y coordinate is outside of the bounds of the column header and then to explicitly show the menu.
ContextMenu visibleMenu = null;
tableView.setOnMouseClicked((MouseEvent e) -> {
if (visibleMenu !=null) {
visibleMenu.hide();
visibleMenu = null;
}
if (e.getButton()==MouseButton.SECONDARY) {
double columnHeaderHeight = tableView.lookup(".column-header-background").getBoundsInLocal().getHeight();
if (e.getY()>columnHeaderHeight) {
visibleMenu = getContextMenu(); // build on the fly or use a prebuild menu
visibleMenu.show(tableView, e.getScreenX(), e.getScreenY());
} else {
// you could show a header specific context menu here
}
}
});
The added benefit is that you can build the context menu on the fly with context sensitive items (that for example only appear if a certain type of cell is selected), or just reuse a prebuild contextmenu as setContextMenu does, up to you.
Add context menu to the specific cells using CellFactory not to the whole table.
E.g. using Table from Oracle tutorial:
TableColumn firstNameCol = new TableColumn();
firstNameCol.setText("First");
firstNameCol.setCellValueFactory(new PropertyValueFactory("firstName"));
firstNameCol.setCellFactory(new Callback<TableColumn, TableCell>() {
#Override
public TableCell call(final TableColumn param) {
final TableCell cell = new TableCell() {
#Override
public void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
} else {
if (isEditing()) {
setText(null);
} else {
setText(getItem().toString());
setGraphic(null);
}
}
}
};
// This way I will have context menu only for specific column
cell.setContextMenu(ContextMenuBuilder.create().items(MenuItemBuilder.create().text("menu").build()).build());
return cell;
}
});
may be the older question. There is a solution, like getting the target of the mouse event of the table and check for instance for class TableCellSkin and display the context menu as,
table.addEventHandler(MouseEvent.MOUSE_CLICKED,
new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent e) {
if (e.getButton() == MouseButton.SECONDARY
&& !isRowEmpty) {
EventTarget target = e.getTarget();
if (target instanceof TableCellSkin
|| ((Node) target).getParent() instanceof TableCellSkin) {
// do your stuff. Context menu will be displayed by default
} else {
// hide the context menu when click event is outside table row
table.getContextMenu().hide();
}
}
}
});
#FXML
void tableContextMenuRequested(ContextMenuEvent event) {
if (tableview.getSelectionModel().getSelectedItems().size() == 0) {
tableContextMenu.hide();
}
}

Categories

Resources