i want after editing of tableview cell textfield ,when i type i want auto suggestion of word - javafx-8

this code contain basically how to edit the textfield of tableview column ,like tableview column is in textfield format and i need to edit it and when i will type i need auto suggestion but my auto suggestion code is not working ,so can anyone suggest me or help to overcome my auto suggestion of word problem with the same procedure ,in createfield after commitedit i called learnword function as well but that is not happening.
class EditingCell extends TableCell<File, String> {
Set<String> possibleWordSet= new HashSet<>();
private AutoCompletionBinding<String> autoCompletionBinding;
public TextField textField;
//private Object possibleWordSet;
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
System.out.println(textField.getCaretPosition() + "caret position");
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText(getItem());
setGraphic(null);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
System.out.println("I am in update function");
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(item);
}
setText(null);
setGraphic(textField);
} else {
setText(item);
setGraphic(null);
}
}
}
// Instantiates the text field.
public void createTextField() {
textField = new TextField(getItem());
System.out.println("hello i am inside the createtextfield");
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
autoCompletionBinding = TextFields.bindAutoCompletion(textField, possibleWordSet); /tion/for auto suuges
textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
commitEdit(textField.getText());//on enter event editing of textfield
learnword(textField.getText());//for auto suggestion call learnword method.
} else if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
}
}
});
textField.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
int caretPosition = textField.getCaretPosition();
GUIFXMLDocumentController fx = new GUIFXMLDocumentController();
fx.setCaretPos(caretPosition);
System.out.println(caretPosition + "caretPosition");
fx.setTextField(textField);
}
});
textField.focusedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> arg0, Boolean arg1, Boolean arg2) {
if (!arg2) {
System.out.println(textField.getText() + "Inside changeListener------------------");
GUIFXMLDocumentController.tv_new.getFocusModel().focusNext();
commitEdit(textField.getText());
learnword(textField.getText());
}
}
});
}
public void learnword(String text) {
possibleWordSet.add(text);
if(autoCompletionBinding!=null){
autoCompletionBinding.dispose();
}
autoCompletionBinding = TextFields.bindAutoCompletion(textField, possibleWordSet);
}
}
enter code here

Related

Can you Drag and Drop a JButton copy?

Found a neat sample that really helped with illustrating how DnD works when it drags a values from a list and places it on the panel.
This sample grabs a copy of the list value.
I have since modified the sample to add a JButton. I can DnD this onto the panel but it moves it instead of making a copy.
Is there something specific as to why the JButton was moved instead of copied?
What change is required to have the button copied instead of moved?
I even tried pressing the CTRL key as I dragged the button but it still moved it instead of copying.
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.io.IOException;
import javax.swing.*;
public class TestDnD {
public static void main(String[] args) {
new TestDnD();
}
public TestDnD() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JList list;
public TestPane() {
setLayout(new BorderLayout());
list = new JList();
DefaultListModel model = new DefaultListModel();
model.addElement(new User("Shaun"));
model.addElement(new User("Andy"));
model.addElement(new User("Luke"));
model.addElement(new User("Han"));
model.addElement(new User("Liea"));
model.addElement(new User("Yoda"));
list.setModel(model);
add(new JScrollPane(list), BorderLayout.WEST);
//Without this call, the application does NOT recognize a drag is happening on the LIST.
DragGestureRecognizer dgr = DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(
list,
DnDConstants.ACTION_COPY_OR_MOVE,
new DragGestureHandler(list)); ///DragGestureHandler - is defined below
///and really just implements DragGestureListener
///and the implemented method defines what is being transferred.
JPanel panel = new JPanel(new GridBagLayout());
add(panel);
//This registers the Target (PANEL) where the Drop is to occur.
DropTarget dt = new DropTarget(
panel,
DnDConstants.ACTION_COPY_OR_MOVE,
new DropTargetHandler(panel), ////DropTargetHandler - is defined below
true); ///and really just implements DropTargetListener
setupButtonTest();
}
private void setupButtonTest()
{
JButton myButton = new JButton("Drag Drop Me");
add(myButton, BorderLayout.NORTH);
DragGestureRecognizer dgr = DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(
myButton,
DnDConstants.ACTION_COPY, // ACTION_COPY_OR_MOVE,
new DragGestureHandler(myButton)); ///DragGestureHandler - is defined below
///and really just implements DragGestureListener
///and the implemented method defines what is being transferred.
}
}
public static class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return name;
}
}
////This Class handles the actual item or data being transferred (dragged).
public static class UserTransferable implements Transferable {
public static final DataFlavor JIMS_DATA_FLAVOR = new DataFlavor(User.class, "User");
private User user;
private JButton jbutton;
public UserTransferable(User user) {
this.user = user;
}
public UserTransferable(JButton user) {
this.jbutton = user;
}
#Override
public DataFlavor[] getTransferDataFlavors() {
//Executed as soon as the User Object is dragged.
System.out.println("UserTransferable : getTransferDataFlavors()");
return new DataFlavor[]{JIMS_DATA_FLAVOR};
}
#Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
//This is what is executed once the item is dragged into a JComponent that can accept it.
System.out.println("UserTransferable : isDataFlavorSupported()");
return JIMS_DATA_FLAVOR.equals(flavor);
}
#Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
//Once a Drop is done then this method provides the data to actually drop.
System.out.println("UserTransferable : getTransferData()");
Object value = null;
if (JIMS_DATA_FLAVOR.equals(flavor)) {
if (user != null)
value = user;
else if (jbutton != null)
value = jbutton;
} else {
throw new UnsupportedFlavorException(flavor);
}
return value;
}
}
protected class DragGestureHandler implements DragGestureListener {
private JList list;
private JButton button;
public DragGestureHandler(JList list) {
this.list = list;
}
public DragGestureHandler(JButton list) {
this.button = list;
}
#Override
public void dragGestureRecognized(DragGestureEvent dge) {
//This executes once the dragging starts.
System.out.println("DragGestureHandler : dragGesturRecognized()");
if (dge.getComponent() instanceof JList)
{
Object selectedValue = list.getSelectedValue();
if (selectedValue instanceof User) {
User user = (User) selectedValue;
Transferable t = new UserTransferable(user); ////This is where you define what is being transferred.
DragSource ds = dge.getDragSource();
ds.startDrag(
dge,
null,
t,
new DragSourceHandler());
}
}
else if (dge.getComponent() instanceof JButton)
{
Object selectedValue = dge.getComponent();
if (selectedValue instanceof JButton) {
JButton jb = button;
Transferable t = new UserTransferable(jb); ////This is where you define what is being transferred.
DragSource ds = dge.getDragSource();
ds.startDrag(
dge,
null,
t,
new DragSourceHandler());
}
}
}
}
protected class DragSourceHandler implements DragSourceListener {
public void dragEnter(DragSourceDragEvent dsde) {
//This means you have entered a possible Target.
System.out.println("DragSourceHandler : DragEnter()");
}
public void dragOver(DragSourceDragEvent dsde) {
//Continually executes while the DRAG is hovering over an potential TARGET.
System.out.println("DragSourceHandler : DragOver()");
}
public void dropActionChanged(DragSourceDragEvent dsde) {
}
public void dragExit(DragSourceEvent dse) {
//Executes once the potential target has been exited.
System.out.println("DragSourceHandler : DragExit()");
}
public void dragDropEnd(DragSourceDropEvent dsde) {
//Once the mouse button is lifted to do the drop.
//Executes against any potential drop.
System.out.println("DragSourceHandler : dragDropEnd()");
}
}
protected class DropTargetHandler implements DropTargetListener {
////THESE ARE EXECUTED ONLY WHEN THE MOUSE AND DRAGGED ITEM IS OVER THE TARGET.
private JPanel panel;
public DropTargetHandler(JPanel panel) {
this.panel = panel;
}
public void dragEnter(DropTargetDragEvent dtde) {
System.out.println("DropTargetHandler : dragEnter()");
if (dtde.getTransferable().isDataFlavorSupported(UserTransferable.JIMS_DATA_FLAVOR)) {
//This shows the outline within the TARGET to indicate it will accept the DROP.
System.out.println(" Accept...");
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
} else {
//If an item is not registered to accept a certain drop this is executed.
System.out.println(" DropTargetHandler : DragEnter() - Else");
dtde.rejectDrag();
}
}
public void dragOver(DropTargetDragEvent dtde) {
//Active while the item is being Dragged over the Target
System.out.println("DropTargetHandler : dragOver()");
}
public void dropActionChanged(DropTargetDragEvent dtde) {
System.out.println("DropTargetHandler : dropActionChanged()");
}
public void dragExit(DropTargetEvent dte) {
//Once the dragged item is taken out of the Target area.
System.out.println("DropTargetHandler : dragExit()");
}
public void drop(DropTargetDropEvent dtde) {
//Once the mouse button is released to do the Drop then this is executed.
System.out.println("DropTargetHandler : drop()");
if (dtde.getTransferable().isDataFlavorSupported(UserTransferable.JIMS_DATA_FLAVOR)) {
Transferable t = dtde.getTransferable();
if (t.isDataFlavorSupported(UserTransferable.JIMS_DATA_FLAVOR)) {
try {
Object transferData = t.getTransferData(UserTransferable.JIMS_DATA_FLAVOR);
if (transferData instanceof User) {
User user = (User) transferData;
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
panel.add(new JLabel(user.getName()));
panel.revalidate();
panel.repaint();
}
else if (transferData instanceof JButton) {
JButton jb = (JButton) transferData;
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
panel.add(jb);
panel.revalidate();
panel.repaint();
}
else {
dtde.rejectDrop();
}
} catch (UnsupportedFlavorException ex) {
ex.printStackTrace();
dtde.rejectDrop();
} catch (IOException ex) {
ex.printStackTrace();
dtde.rejectDrop();
}
} else {
dtde.rejectDrop();
}
}
}
}
}

JavaFX TableView with Custom Cell Datepicker "OnEditCommit" is not invoked

Hi everyone !!
I'm working with JavaFX and the JDK 8.
I got a TableView filled by a database with the use of a JavaFX POJO Class "Inputs". I've implemented TexField cells, ComboBoxes cells and Checkbox cells succesfully.
But I am not able to make it working with DatePicker Control: the event on the "setOnEditComit" is never invoked...
Hre is my code:
Declarations for TableColumn:
#FXML
private TableColumn<Inputs,LocalDate> colDate = new TableColumn<Inputs,LocalDate>();
[...]
colDate.setCellValueFactory(
new PropertyValueFactory<Inputs,LocalDate>("localdate"));
Callback<TableColumn<Inputs, LocalDate>, TableCell<Inputs, LocalDate>> dateCellFactory =
new Callback<TableColumn<Inputs, LocalDate>, TableCell<Inputs, LocalDate>>() {
public TableCell call(TableColumn p) {
return new EditingDatePickerCell();
}
};
[...]
colDate.setOnEditCommit(
new EventHandler<CellEditEvent<Inputs, LocalDate>>() {
#Override
public void handle(CellEditEvent<Inputs, LocalDate> event) {
System.out.println("EVENT!!!!");
((Inputs) event.getTableView().getItems().get(
event.getTablePosition().getRow())
).setDatePicker(event.getNewValue());
}
}
);
With these JavaFX POJO Objects declarations:
public ObjectProperty<LocalDate> localdate;
[...]
this.localdate = new SimpleObjectProperty<LocalDate>(localdate);
[...]
public LocalDate getDatePicker() {
return localdate.getValue();
}
[...]
public void setDatePicker(LocalDate value) {
System.out.println("EVENT!!!!");
localdate.setValue(value);
}
[...]
public ObjectProperty<LocalDate> localdateProperty() {
return localdate;
}
EditingDatePickerCell class:
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import com.desktop.newapp.utils.Inputs;
public class EditingDatePickerCell <Inputs, LocalDate> extends TableCell<Inputs, LocalDate> {
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createDatePicker();
setText(null);
setGraphic(datePicker);
datePicker.requestFocus();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
datePicker.setValue((java.time.LocalDate) getItem());
setGraphic(null);
setContentDisplay(ContentDisplay.TEXT_ONLY);
}
private DatePicker datePicker;
public EditingDatePickerCell() {
if (datePicker == null) {
createDatePicker();
}
setGraphic(datePicker);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
Platform.runLater(new Runnable() {
#Override
public void run() {
datePicker.requestFocus();
}
});
}
#Override
public void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (datePicker != null && item != null) {
datePicker.setValue((java.time.LocalDate) getLocalDate());
commitEdit(getLocalDate());
}
setGraphic(datePicker);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
}
private void createDatePicker() {
datePicker = new DatePicker();
datePicker.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
setGraphic(datePicker);
datePicker.addEventFilter(KeyEvent.KEY_PRESSED,new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
commitEdit(getLocalDate());
} else if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
} else if (t.getCode() == KeyCode.TAB) {
commitEdit(getLocalDate());;
}
}
});
setAlignment(Pos.CENTER);
}
private LocalDate getLocalDate() {
return getItem();
///return datePicker.getValue() != null ? datePicker.getValue() : getItem();
}
}
I've been Googling a lot and I didn't find any correct implementation of the Java8 DatePicker Editing capabilities in a JavaFX TableView. Any help would be very appreciate !!
Without Stackoverflow I'll never could done the quarter of the whole job so long life to Stackoverflow !!
Regards.
You need to put the table in editing mode (for the current row) when the user interacts with the picker. That can be achieved with an onShowingHandler like this (example is also with a color picker):
this.colorPicker.setOnShowing(event -> {
final TableView<T> tableView = getTableView();
tableView.getSelectionModel().select(getTableRow().getIndex());
tableView.edit(tableView.getSelectionModel().getSelectedIndex(), column);
});
then watch the valueProperty of the picker like this:
this.colorPicker.valueProperty().addListener((observable, oldValue, newValue) -> {
if(isEditing()) {
commitEdit(newValue);
}
});
For more explanation have a look at my blog post: Custom editor components in JavaFX TableCells.
Full Class:
public class ColorTableCell<T> extends TableCell<T, Color> {
private final ColorPicker colorPicker;
public ColorTableCell(TableColumn<T, Color> column) {
this.colorPicker = new ColorPicker();
this.colorPicker.editableProperty().bind(column.editableProperty());
this.colorPicker.disableProperty().bind(column.editableProperty().not());
this.colorPicker.setOnShowing(event -> {
final TableView<T> tableView = getTableView();
tableView.getSelectionModel().select(getTableRow().getIndex());
tableView.edit(tableView.getSelectionModel().getSelectedIndex(), column);
});
this.colorPicker.valueProperty().addListener((observable, oldValue, newValue) -> {
if(isEditing()) {
commitEdit(newValue);
}
});
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
#Override
protected void updateItem(Color item, boolean empty) {
super.updateItem(item, empty);
setText(null);
if(empty) {
setGraphic(null);
} else {
this.colorPicker.setValue(item);
this.setGraphic(this.colorPicker);
}
}
}
I was having the same issues but i ended up solving it with this post. JavaFX8 – Render a DatePicker Cell in a TableView.
The outcome is illustrated in the image below.
Your Model object is a bit strange. The setDatePicker and getDatePicker methods should be called setLocaldate and getLocaldate, to be consistent with the localdateProperty() method and (possibly importantly) the parameter passed to the PropertyValueFactory.
I don't think that would cause the problem you observe, though, and I can't see what else is wrong.
This example works for me.
Have a look and see if you can see what I did that's different...
here is a datapicker cell edit when pressing tab key and go to the next cell
datePicker.setOnKeyPressed /EventHandler doesnot work with tab
datePicker.EventFilter get called twice
to work arround this you need to add a listner to tableview cell and get date text as string and cast it to localdate
addEventFilter to TableCell deduction object is a sample
=> addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler() {...}
public class DatePickerCell extends TableCell<Deduction, LocalDate> {
private DatePicker datePicker;
private TableColumn column;
// private TableCell cell;
public DatePickerCell(TableColumn column) { //
super();
this.column = column;
this.datePicker = new DatePicker(getDate());
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createDatePicker();
setText(null);
setGraphic(datePicker);
Platform.runLater(new Runnable() {
#Override
public void run() {
datePicker.requestFocus();
}
});
//Platform.runLater(datePicker::requestFocus);
}
}
#Override
public void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
// SimpleDateFormat smp = new SimpleDateFormat("dd/MM/yyyy");
/* if (null == this.datePicker) {
System.out.println("datePicker is NULL");
}*/ //TO be reviewed
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (datePicker != null) {
datePicker.setValue(getItem());
}
setText(null);
setGraphic(datePicker);
} else {
setText(getItem().toString());
setGraphic(null);
}
}
}
private LocalDate getDate() {
return getItem() == null ? LocalDate.now() : getItem();
}
private void createDatePicker() {
this.datePicker = new DatePicker(getDate());
datePicker.setMinWidth(this.getWidth() - this.getGraphicTextGap() * 2);
this.datePicker.editableProperty().bind(column.editableProperty());
this.datePicker.disableProperty().bind(column.editableProperty().not());
this.datePicker.setOnShowing(event -> {
final TableView tableView = getTableView();
tableView.getSelectionModel().select(getTableRow().getIndex());
tableView.edit(tableView.getSelectionModel().getSelectedIndex(), column);
});
datePicker.setOnAction((e) -> {
commitEdit(datePicker.getValue());
TableColumn nextColumn = getNextColumn(true);
if (nextColumn != null) {
getTableView().edit(getTableRow().getIndex(),
nextColumn);
}
});
datePicker.focusedProperty().addListener(
new ChangeListener<Boolean>() {
#Override
public void changed(
ObservableValue<? extends Boolean> arg0,
Boolean arg1, Boolean arg2) {
if (!arg2) {
commitEdit(datePicker.getValue());
}
}
});
datePicker.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent t) {
// System.out.println("setOnKeyPressed datapicker get value ...." + t.getCode());
/* if (t.getCode() == KeyCode.ENTER) {
commitEdit(datePicker.getValue());
System.out.println("Enter datapicker get value " + datePicker.getValue());
} else */if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
} else if (t.getCode() == KeyCode.ENTER){
commitEdit(datePicker.getValue());
// System.out.println("Tab datapicker get value " + datePicker.getValue());
TableColumn nextColumn = getNextColumn(!t.isShiftDown());
// System.out.println("nextColumn datapicker get value " + nextColumn.getId());
if (nextColumn != null) {
getTableView().edit(getTableRow().getIndex(),
nextColumn);
}
}
}
});
addEventFilter(KeyEvent.KEY_PRESSED, new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if (event.getCode() == KeyCode.TAB) {
commitEdit(LocalDate.parse(datePicker.getEditor().getText(), DateTimeFormatter.ofPattern("dd/MM/yyyy")));
TableColumn nextColumn = getNextColumn(true);
if (nextColumn != null) {
getTableView().edit(getTableRow().getIndex(),
nextColumn);
}
}
}
});
//
// // setAlignment(Pos.CENTER);
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText(getItem().toString());
setGraphic(null);
}
public DatePicker getDatePicker() {
return datePicker;
}
public void setDatePicker(DatePicker datePicker) {
this.datePicker = datePicker;
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
private TableColumn<Deduction, ?> getNextColumn(boolean forward) {
List<TableColumn<Deduction, ?>> columns = new ArrayList<>();
for (TableColumn<Deduction, ?> column : getTableView().getColumns()) {
columns.addAll(getLeaves(column));
}
// There is no other column that supports editing.
if (columns.size() < 2) {
return null;
}
int currentIndex = columns.indexOf(getTableColumn());
int nextIndex = currentIndex;
if (forward) {
nextIndex++;
if (nextIndex > columns.size() - 1) {
nextIndex = 0;
}
} else {
nextIndex--;
if (nextIndex < 0) {
nextIndex = columns.size() - 1;
}
}
return columns.get(nextIndex);
}
private List<TableColumn<Deduction, ?>> getLeaves(
TableColumn<Deduction, ?> root) {
List<TableColumn<Deduction, ?>> columns = new ArrayList<>();
if (root.getColumns().isEmpty()) {
// We only want the leaves that are editable.
if (root.isEditable()) {
columns.add(root);
}
return columns;
} else {
for (TableColumn<Deduction, ?> column : root.getColumns()) {
columns.addAll(getLeaves(column));
}
return columns;
}
}
}
in your class with the tableview
Callback cellFactoryDate
= new Callback<TableColumn, TableCell>() {
public TableCell call(TableColumn p) {
return new DatePickerCell(p);//DatePickerTest(p) //DatePickerTest2 //EditingCellDate
}
};
dateColumn.setCellValueFactory(new PropertyValueFactory<>("date"));
// dateColumn.setCellFactory(cellFactoryTest);//cellFactoryDate
dateColumn.setCellFactory(cellFactoryDate);
dateColumn.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Deduction, LocalDate>>() {
#Override
public void handle(TableColumn.CellEditEvent<Deduction, LocalDate> t) {
((Deduction) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setDate(t.getNewValue());
}
}
);
Here is a solution acceptable for all custom controls; this example use a ColorPicker control:
So finnaly I deal it like that: on the events of the controls I get back the POJO objects in use by the "((Inputs)getTableView().getItems().get(getTableRow().getIndex()" and I update similary like is it done in the OnEditCommit method...
So for me it's look like this (update the color):
((Inputs) getTableView().getItems().get(
getTableRow().getIndex())
).setColor(cp.getValue());
Here is example with ColorPickerCell
:
public class ColorPickerTableCell<Inputs> extends TableCell<Inputs, Color>{
private ColorPicker cp;
public ColorPickerTableCell(){
cp = new ColorPicker();
cp.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
commitEdit(cp.getValue());
updateItem(cp.getValue(), isEmpty());
((Inputs) getTableView().getItems().get(
getTableRow().getIndex())
).setColor(cp.getValue());
}
});
setGraphic(cp);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
setEditable(true);
}
#Override
protected void updateItem(Color item, boolean empty) {
super.updateItem(item, empty);
cp.setVisible(!empty);
this.setItem(item);
cp.setValue(item);
}
}
With this simple JavaFX's POJO:
public ObjectProperty<Color> color = new SimpleObjectProperty<Color>();
this.color = new SimpleObjectProperty(color);
public ObjectProperty<Color> colorProperty() {
return color;
}
public void setColor(Color color2) {
color.set(color2);
}
I do not know if it's a good way to achive that but it worked for me... Note that the JavaFX's POJO is only accessible within an "ActionEvent" request (combobox, datepicker, colorpicker, etc..)
Regards,

GWTP + Gxt: Exception when using same presenter widget at two separate slots of page

I have a page with border layout and slots defined for each of the regions of the border layout (for eg. EAST, WEST, NORTH, CENTER...).
I wish to reuse a presenter widget by displaying it at two of the above slots on the page.
I was successfully able to display the presenter widget on one of the slots but whenever I try to add the presenter widget at two separate slots I get this error:
Exception caught: notifyReveal() called on a visible Presenter!
Can anyone show me how it is to be done.
Below is my code.
HomeView.java
#UiField
ContentPanel centerPanel;
#UiField
ContentPanel westPanel;
#Override
public void setInSlot(Object slot, Widget content) {
if (slot == HomePresenter.SLOT_EAST) {
if (content != null) {
eastPanel.add(content);
}
} else if (slot == HomePresenter.SLOT_WEST) {
if (content != null) {
westPanel.add(content);
}
} else if (slot == HomePresenter.SLOT_CENTER) {
if (content != null) {
centerPanel.add(content);
}
} else {
super.setInSlot(slot, content);
}
}
#Override
public void addToSlot(Object slot, Widget content) {
if (slot == HomePresenter.SLOT_EAST) {
if (content != null) {
eastPanel.add(content);
}
} else if (slot == HomePresenter.SLOT_WEST) {
if (content != null) {
westPanel.add(content);
}
} else if (slot == HomePresenter.SLOT_CENTER) {
if (content != null) {
centerPanel.add(content);
}
} else {
super.addToSlot(slot, content);
}
}
HomePresenter.java:
public static final Object SLOT_WEST = new Object();
public static final Object SLOT_CENTER = new Object();
#Override
protected void revealInParent() {
RevealRootContentEvent.fire(this, this); //Getting error over here
}
#Override
protected void onReset() {
super.onReset();
setInSlot(SLOT_WEST, null);
setInSlot(SLOT_CENTER, null);
indirectProvider.get(new AsyncCallback<LeftPanelPresenter>() {
#Override
public void onSuccess(LeftPanelPresenter result) {
addToSlot(SLOT_WEST, result);
addToSlot(SLOT_CENTER, result);
}
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
System.out.println("Not added to the slot");
}
});
}
The point of the provider is to create a new instance of each PresenterWidget for each place you want to put it.
I think calling addToSlot() twice with the same result object is causing the error, because that instance has already been revealed.
You can use a loop to make a new instance for each slot:
// create an array of the slots
List<Object> slots = new ArrayList<Object>();
slots.add(SLOT_WEST);
slots.add(SLOT_CENTER);
// call provider.get() on each slot in turn
for(Object slot : slots)
{
indirectProvider.get(new AsyncCallback<LeftPanelPresenter>()
{
#Override
public void onSuccess(LeftPanelPresenter result)
{
addToSlot(slot, result);
}
#Override
public void onFailure(Throwable caught)
{
// TODO Auto-generated method stub
System.out.println("Not added to the slot");
}
});
}

Google Maps API v3 - Buttons and TextBoxes inside InfoWindow?

I'm using the new maps v3 API from gwt-google-apis.
Is it possible to capture events from GWT widgets that are inside InfoWindow? Am I missing something?
Tried code above (button.addClickHandler) and it doesn't show the alert:
Marker m = Marker.create();
m.setIcon(MarkerImage.create(icone));
m.setPosition(LatLng.create(posicao.lat(), posicao.lng()));
m.setMap(map);
m.addClickHandler(new ClickHandler() {
#Override
public void handle(MouseEvent event) {
InfoWindow info = InfoWindow.create();
Button button = new Button("Desativar");
button.addClickHandler(new com.google.gwt.event.dom.client.ClickHandler() {
#Override
public void onClick(ClickEvent event) {
Window.alert("click");
}
});
final HTMLPanel html = new HTMLPanel(("<div id='button'></div>"));
html.add(button, "button");
info.setContent(html.getElement());
info.setPosition(posicao);
info.open(map);
}
});
Thanks.
The problem is result of a broken hierarchy between the widgets, the normal way to do it is by attach / detach widget. You do it by setting of the widget's element. This is also matter of Google Maps API.
This can be resolved by using fake panel which will be part of the InfoWindow, so when you make setContent(Widget widget) the fake panel will be updated and the element of the widget will be set to the content (as previous).
Please take a look at this class:
public class MyInfoWindow extends InfoWindow {
static class FakePanel extends ComplexPanel {
public FakePanel(Widget w) {
w.removeFromParent();
getChildren().add(w);
adopt(w);
}
#Override
public boolean isAttached() {
return true;
}
public void detachWidget() {
this.remove(0);
}
}
private IsWidget widgetContent = null;
FakePanel widgetAttacher;
public MyInfoWindow() {
super(InfoWindowImpl.impl.construct());
}
private void detachWidget() {
if (this.widgetAttacher != null) {
this.widgetAttacher.detachWidget();
this.widgetAttacher = null;
}
}
public void close() {
super.close();
detachWidget();
}
public void setContent(String content) {
this.widgetContent = null;
this.detachWidget();
super.setContent(content);
}
/** */
public void setContent(Widget value) {
this.widgetContent = value;
setContent(value.getElement());
if (this.widgetAttacher == null) {
addListener(getJso(), "closeclick", new Runnable() {
#Override
public void run() {
detachWidget();
}
});
this.widgetAttacher = new FakePanel(value);
} else if (this.widgetAttacher.getWidget(0) != value) {
this.widgetAttacher.detachWidget();
this.widgetAttacher = new FakePanel(value);
}
}
private void setContent(Element element) {
InfoWindowImpl.impl.setContent(getJso(), element);
}
public IsWidget getContentWidget() {
return widgetContent;
}
public final native void addListener(JavaScriptObject jso, String whichEvent, Runnable handler)
/*-{
var that = jso;
$wnd.google.maps.event.addListener(jso, whichEvent, function() {
handler.#java.lang.Runnable::run()();
});
}-*/;
}
I had to build a wrapper over InfoWindow to make it work.
public class NXInfoWindow {
static class FakePanel extends ComplexPanel {
public FakePanel(Widget w) {
w.removeFromParent();
getChildren().add(w);
adopt(w);
}
#Override
public boolean isAttached() {
return true;
}
public void detachWidget() {
this.remove(0);
}
}
private InfoWindow info;
private IsWidget widgetContent = null;
private Long id;
FakePanel widgetAttacher;
public static NXInfoWindow create(Long id){
NXInfoWindow myInfo = new NXInfoWindow();
myInfo.info = InfoWindow.create();
myInfo.id = id;
return myInfo;
};
private void detachWidget() {
if (this.widgetAttacher != null) {
this.widgetAttacher.detachWidget();
this.widgetAttacher = null;
}
}
public void close() {
info.close();
detachWidget();
}
public void setPosition(LatLng posicao) {
info.setPosition(posicao);
}
public void open(GoogleMap map) {
info.open(map);
}
public void setContent(Widget value) {
this.widgetContent = value;
info.setContent(value.getElement());
if (this.widgetAttacher == null) {
addListener(info, "closeclick", new Runnable() {
#Override
public void run() {
detachWidget();
}
});
this.widgetAttacher = new FakePanel(value);
} else if (this.widgetAttacher.getWidget(0) != value) {
this.widgetAttacher.detachWidget();
this.widgetAttacher = new FakePanel(value);
}
}
private void setContent(Element element) {
this.setContent(element);
}
public IsWidget getContentWidget() {
return widgetContent;
}
public final native void addListener(JavaScriptObject jso, String whichEvent, Runnable handler)
/*-{
var that = jso;
$wnd.google.maps.event.addListener(jso, whichEvent, function() {
handler.#java.lang.Runnable::run()();
});
}-*/;
}

Disable ButtonCell in a celltable

In my CellTable, One column has ButtonCells. So I need to disable theses ButtonCells by clicking on a button which is located outside the CellTable.
You could create your own Button Cell class. For example:
import com.google.gwt.cell.client.AbstractSafeHtmlCell;
import com.google.gwt.cell.client.Cell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.EventTarget;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.text.shared.SafeHtmlRenderer;
import com.google.gwt.text.shared.SimpleSafeHtmlRenderer;
/**
* A {#link Cell} used to render a button.
*/
public class StyledButtonCell extends AbstractSafeHtmlCell<String> {
private String disabledString = "";
private boolean disabled = false;
/**
* Construct a new ButtonCell that will use a {#link SimpleSafeHtmlRenderer}.
*/
public StyledButtonCell() {
this(SimpleSafeHtmlRenderer.getInstance());
}
/**
* Construct a new ButtonCell that will use a given {#link SafeHtmlRenderer}.
*
* #param renderer a {#link SafeHtmlRenderer SafeHtmlRenderer<String>} instance
*/
public StyledButtonCell(SafeHtmlRenderer<String> renderer) {
super(renderer, "click", "keydown");
}
#Override
public void onBrowserEvent(Context context, Element parent, String value,
NativeEvent event, ValueUpdater<String> valueUpdater) {
super.onBrowserEvent(context, parent, value, event, valueUpdater);
if ("click".equals(event.getType())) {
EventTarget eventTarget = event.getEventTarget();
if (!Element.is(eventTarget)) {
return;
}
if (parent.getFirstChildElement().isOrHasChild(Element.as(eventTarget))) {
// Ignore clicks that occur outside of the main element.
onEnterKeyDown(context, parent, value, event, valueUpdater);
}
}
}
#Override
public void render(Context context, SafeHtml data, SafeHtmlBuilder sb) {
sb.appendHtmlConstant("<button type=\"button\" tabindex=\"-1\"" + disabledString + ">");
if (data != null) {
sb.append(data);
}
sb.appendHtmlConstant("</button>");
}
#Override
protected void onEnterKeyDown(Context context, Element parent, String value,
NativeEvent event, ValueUpdater<String> valueUpdater) {
if (valueUpdater != null) {
valueUpdater.update(value);
}
}
public boolean isDisabled() {
return disabled;
}
public void setDisabled(boolean disabled) {
this.disabled = disabled;
if (disabled) {
disabledString = "disabled=\"disabled\"";
} else {
disabledString = "";
}
}
}
Then use this with your cell table:
final StyledButtonCell buttonCell = new StyledButtonCell();
buttonColumn = new Column<SomeItem, String>(buttonCell) {
public String getValue(SomeItem object) {
// The value to display in the button.
return "Go";
}
};
To disable the button, simply call:
buttonCell.setDisabled(true);
table.redraw();
If you don't need to "rename" your button, you can also create your own based on Boolean abstract cell:
public class CustomButtonCell extends AbstractEditableCell<Boolean, Boolean> {
private static final SafeHtml ENABLED = SafeHtmlUtils.fromSafeConstant("<button type=\"button\" tabindex=\"-1\">");
private static final SafeHtml DISABLED = SafeHtmlUtils.fromSafeConstant("<button type=\"button\" tabindex=\"-1\" disabled=\"disabled\">");
private static final SafeHtml CLOSE_BRACKET = SafeHtmlUtils.fromSafeConstant("</button>");
private final boolean dependsOnSelection;
private final boolean handlesSelection;
private final String text;
public CustomButtonCell(final String text) {
this(false, false, text);
}
public CustomButtonCell(boolean dependsOnSelection, boolean handlesSelection, String text) {
super(BrowserEvents.CHANGE, BrowserEvents.CLICK, BrowserEvents.KEYDOWN);
this.dependsOnSelection = dependsOnSelection;
this.handlesSelection = handlesSelection;
this.text = text;
}
#Override
public boolean dependsOnSelection() {
return dependsOnSelection;
}
#Override
public boolean handlesSelection() {
return handlesSelection;
}
#Override
public boolean isEditing(Context context, Element parent, Boolean value) {
return false;
}
/**
* Based on CheckboxCell
*/
#Override
public void onBrowserEvent(Context context, Element parent, Boolean value,
NativeEvent event, ValueUpdater<Boolean> valueUpdater) {
String type = event.getType();
boolean enterPressed = BrowserEvents.KEYDOWN.equals(type)
&& event.getKeyCode() == KeyCodes.KEY_ENTER;
if (BrowserEvents.CHANGE.equals(type) || BrowserEvents.CLICK.equals(type) || enterPressed) {
InputElement input = parent.getFirstChild().cast();
Boolean isChecked = input.isChecked();
if (enterPressed && (handlesSelection() || !dependsOnSelection())) {
isChecked = !isChecked;
input.setChecked(isChecked);
}
if (value != isChecked && !dependsOnSelection()) {
setViewData(context.getKey(), isChecked);
} else {
clearViewData(context.getKey());
}
if (valueUpdater != null) {
valueUpdater.update(isChecked);
}
}
}
#Override
public void render(Context context, Boolean value, SafeHtmlBuilder sb) {
// Get the view data.
Object key = context.getKey();
Boolean viewData = getViewData(key);
if (viewData != null && viewData.equals(value)) {
clearViewData(key);
viewData = null;
}
if (value != null && ((viewData != null) ? viewData : value)) {
sb.append(ENABLED);
} else {
sb.append(DISABLED);
}
sb.append(SafeHtmlUtils.fromString(text));
sb.append(CLOSE_BRACKET);
}
}
and edit it by its "get value" mechanisme
Column<TestJSO, Boolean> revokeColumn = CellTableUtils.createColumn(new CustomButtonCell("Test"),
new GetValue<TestJSO, Boolean>() {
#Override
public Boolean getValue(TestJSO value) {
return value.isEnabled();
}
});
Good morning,
that was a nice little example to do early in the morning. Here you have my solution, I'm not saying, its the best but its working!
public class _57_DisableAllButtons implements EntryPoint {
boolean enable = false;
#Override
public void onModuleLoad() {
Button b1 = new Button("Button1");
Button b2 = new Button("Button2");
Button b3 = new Button("Button3");
RootPanel.get("nameFieldContainer").add(b1);
RootPanel.get("nameFieldContainer").add(b2);
RootPanel.get("nameFieldContainer").add(b3);
Button disableAll = new Button("Disabale all");
RootPanel.get("sendButtonContainer").add(disableAll);
disableAll.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
final RootPanel rootpannel = RootPanel.get("nameFieldContainer");
int widgetcount = rootpannel.getWidgetCount();
for (int i = 0; i < widgetcount; i++) {
Widget w = rootpannel.getWidget(i);
if(w instanceof Button){
((Button) w).setEnabled(enable);
}
}
enable = !enable;
}
});
}
}