How to add a listener in a particular cell in a grid in GXT - grid

I would like to add a listener when I am clicking the cell for categories only.
this is the declaration of my columnConfig
ColumnConfig<UserRights, Boolean> unlockConfig = new ColumnConfig<UserRights, Boolean>(properties.hasUnlock(), 50);
unlockConfig.setHeader("Unlock");
cfgs.add(unlockConfig);
ColumnConfig<UserRights, String> catConfig = new ColumnConfig<UserRights, String>(properties.categories(), 150);
catConfig.setHeader("Categories");
cfgs.add(catConfig);
cm = new ColumnModel<UserRights>(cfgs);
grid = new Grid<UserRights>(store, cm);
grid.getView().setAutoFill(true);
grid.addStyleName("margin-10");
grid.setLayoutData(new VerticalLayoutContainer.VerticalLayoutData(1, 1));
grid.addRowClickHandler(new RowClickEvent.RowClickHandler() {
#Override
public void onRowClick(RowClickEvent event) {
index = event.getRowIndex();
}
});
rowEditing = new GridRowEditing<UserRights>(grid);
rowEditing.addEditor(unlockConfig, new CheckBox());
how could I add a listener in the category column?
Thanks in advance.

There is nothing in your categories cell that prompts a user to click, it just contains text. What you should be doing is using the columnConfig.setCell(Cell cell) method to specify a cell that contains an interactive component.
You could still try something along these lines:
columnConfig.setCell(new SimpleSafeHtmlCell<String>(SimpleSafeHtmlRenderer.getInstance(), "click") {
#Override
public void onBrowserEvent(Context context, Element parent, String value, NativeEvent event, ValueUpdater<String> valueUpdater) {
super.onBrowserEvent(context, parent, value, event, valueUpdater);
if (event.getType().equals("click")) {
}
}
});

Related

How to bind to a property within a ObservableMap in JavaFX?

I am trying to automatically update a JavaFX ListView when a change occurs on a Property located within an ObservableMap.
Below is my model, where I have a Project, containing a list of Seats, and each Seat in turn contains a Map of type <Layer, ObjectProperty<Category>>.
What I am trying to achieve is to bind an ui element to that ObjectProperty<Category> within the Map.
Here is the Model:
public class Seat {
private final DoubleProperty positionX;
private final DoubleProperty positionY;
private final MapProperty<Layer, ObjectProperty<Category>> categoryMap;
public Seat() {
this.positionX = new SimpleDoubleProperty();
this.positionY = new SimpleDoubleProperty();
this.categoryMap = new SimpleMapProperty(FXCollections.observableHashMap());
}
}
public class Project {
private ObservableList<Seat> seatList;
public Project() {
seatList = FXCollections.observableArrayList(
new Callback<Seat, Observable[]>() {
#Override
public Observable[] call(Seat seat) {
return new Observable[]{
seat.categoryMapProperty()
};
}
}
);
}
The UI element I want to bind is a ListView with a custom cell as follows:
public class CategoryCell extends ListCell<Category>{
private ToggleButton viewButton;
private Rectangle colorRect;
private Label name;
private Label count;
private GridPane pane;
public CategoryCell(ObservableList<Seat> seatList) {
super();
buildGui();
itemProperty().addListener((list, oldValue, newValue) -> {
if (newValue != null) {
//Bind color
colorRect.fillProperty().bind(newValue.colorProperty());
//Bind category name
name.textProperty().bind(newValue.nameProperty());
//Bind number of seats assigned to this category
LongBinding categorySeatNumProperty = Bindings.createLongBinding(() ->
seatList.stream().filter(seat -> seat.getCategory(newValue.getLayer()).equals(newValue)).count(), seatList);
count.textProperty().bind(categorySeatNumProperty.asString());
}
if (oldValue != null) {
name.textProperty().unbind();
count.textProperty().unbind();
colorRect.fillProperty().unbind();
}
});
}
private void buildGui() {
FontIcon hidden = new FontIcon("mdi-eye-off");
viewButton = new ToggleButton("");
viewButton.setGraphic(hidden);
viewButton.selectedProperty().addListener((observable,oldValue, newValue) -> {
Category category = itemProperty().get();
if (newValue == true) {
category.shownColorProperty().unbind();
category.setShownColor(Color.TRANSPARENT);
}else {
category.shownColorProperty().bind(category.colorProperty());
}
});
colorRect = new Rectangle(30,30);
name = new Label();
name.setMaxWidth(120);
pane = new GridPane();
count = new Label();
count.setPadding(new Insets(0,0,0,10));
ColumnConstraints nameCol = new ColumnConstraints();
nameCol.setHgrow( Priority.ALWAYS );
pane.getColumnConstraints().addAll(
new ColumnConstraints(40),
new ColumnConstraints(40),
nameCol,
new ColumnConstraints(40));
pane.addColumn(0, viewButton);
pane.addColumn(1, colorRect);
pane.addColumn(2, name );
pane.addColumn(3, count);
this.setText(null);
name.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.getClickCount()==2) {
//launch the category editor TODO
}
}
});
}
The problem is that the code below is not triggered when I change the Category value of a CategoryProperty within the MapProperty of a Seat.
//Bind number of seats assigned to this category
LongBinding categorySeatNumProperty = Bindings.createLongBinding(() ->
seatList.stream().filter(seat -> seat.getCategory(newValue.getLayer()).equals(newValue)).count(), seatList);
count.textProperty().bind(categorySeatNumProperty.asString());
}
Any advice on how to achieve this?
===== Clarifications following James_D comment ====
1) About the model: I have actually thought and hesitated quite a bit about this. I want to allocate categories to seats in concert halls, and do this on multiple "layers/levels". Say for example a price "layer" where I could have four price tag categories, and "selling company" layer where I would have 3 companies, etc... In order to model this in my Seat class I have a Map<Layer, Category> which looks like a good choice as a seat should only be assigned to one unique category per layer. Then my Project class keeps track of Layers and their respective Categories, which is not really needed but handy to keep their user-specified display order.
2) Thank you for spotting that bug in the CategoryCell! The order of if (oldValue != null) and if (newValue != null) should indeed be reversed.
3) Now what I need to answer my initial question is a way to trigger a notification when the categoryProperty in the Map of the Seat class is modified.
Actually, just refreshing the listview whenever I make a change to my Map solves the issue, but it kinds of defeat the purpose of having a Observable property...
Answering myself now that I understand a little more.
1) How to bind to a property within a ObservableMap?
By using the valueAt() method of a MapProperty.
Instead of using ObservableMap<Layer, ObjectProperty<Category>>, use
MapProperty<Layer, Category>.
2) How to trigger a notification when the objectProperty in the ObservableMap is modified?
Since we are now using a MapProperty where the value is the object and not the property wrapping it, we can just use the addListener() method of the MapProperty.

Context menu on TableRow<Object> does not show up on first right click

So I followed this example on using context menu with TableViews from here. I noticed that using this code
row.contextMenuProperty().bind(Bindings.when(Bindings.isNotNull(row.itemProperty()))
.then(rowMenu)
.otherwise((ContextMenu)null));
does not show up on first right click on a row with values. I need to right click on that row again for the context menu to show up. I also tried this code(which is my first approach, but not using it anymore because I've read somewhere that that guide is the best/good practice for anything related about context menu and tableview), and it displays the context menu immediately
if (row.getItem() != null) {
rowMenu.show(row, event.getScreenX(), event.getScreenY());
}
else {
// do nothing
}
but my problem with this code is it throws a NullPointerException whenever i try to right click on a row that has no data.
What could I possibly do to prevent NullPointerException while having the context menu show up immediately after a right click? In my code, I also have a code that a certain menu item in the context menu will be disabled based on the property of the myObject binded to row, that's why i need the context menu to pop up right away.
I noticed this too with the first block of code. Even if the property of myObject has already changed, it still has a menu item enabled/disabled unless I right click on that row again. I hope that you could help me. Thank you!
Here is a MCVE:
public class MCVE_TableView extends Application{
#Override
public void start(Stage primaryStage) throws Exception {
BorderPane myBorderPane = new BorderPane();
TableView<People> myTable = new TableView<>();
TableColumn<People, String> nameColumn = new TableColumn<>();
TableColumn<People, Integer> ageColumn = new TableColumn<>();
ContextMenu rowMenu = new ContextMenu();
ObservableList<People> peopleList = FXCollections.observableArrayList();
peopleList.add(new People("John Doe", 23));
nameColumn.setMinWidth(100);
nameColumn.setCellValueFactory(
new PropertyValueFactory<>("Name"));
ageColumn.setMinWidth(100);
ageColumn.setCellValueFactory(
new PropertyValueFactory<>("Age"));
myTable.setItems(peopleList);
myTable.getColumns().addAll(nameColumn, ageColumn);
myTable.setRowFactory(tv -> {
TableRow<People> row = new TableRow<>();
row.setOnContextMenuRequested((event) -> {
People selectedRow = row.getItem();
rowMenu.getItems().clear();
MenuItem sampleMenuItem = new MenuItem("Sample Button");
if (selectedRow != null) {
if (selectedRow.getAge() > 100) {
sampleMenuItem.setDisable(true);
}
rowMenu.getItems().add(sampleMenuItem);
}
else {
event.consume();
}
/*if (row.getItem() != null) { // this block comment displays the context menu instantly
rowMenu.show(row, event.getScreenX(), event.getScreenY());
}
else {
// do nothing
}*/
// this requires the row to be right clicked 2 times before displaying the context menu
row.contextMenuProperty().bind(Bindings.when(Bindings.isNotNull(row.itemProperty()))
.then(rowMenu)
.otherwise((ContextMenu)null));
});
return row;
});
myBorderPane.setCenter(myTable);
Scene scene = new Scene(myBorderPane, 500, 500);
primaryStage.setTitle("MCVE");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main (String[] args) {
launch(args);
}
}
Here is the People Class
public class People {
SimpleStringProperty name;
SimpleIntegerProperty age;
public People(String name, int age) {
this.name = new SimpleStringProperty(name);
this.age = new SimpleIntegerProperty(age);
}
public SimpleStringProperty NameProperty() {
return this.name;
}
public SimpleIntegerProperty AgeProperty() {
return this.age;
}
public String getName() {
return this.name.get();
}
public int getAge() {
return this.age.get();
}
}
Edit: MCVE added
Edit2: Updated the MCVE. Still requires to be right-clicked twice before the contextMenu pops up
Below's a code snippet as a quick demonstration of how-to/where-to instantiate and configure a per-row ContextMenu. It
creates a ContextMenu/MenuItem for each TableRow at the row's instantiation time
creates a conditional binding that binds the menu to the row's contextMenuProperty if not empty (just the same as you did)
configures the contextMenu in an onShowing handler, depending on the current item (note: no need for a guard against null, because the conditional binding will implicitly guarantee to not show the the menu in that case)
The snippet:
myTable.setRowFactory(tv -> {
TableRow<People> row = new TableRow<>() {
ContextMenu rowMenu = new ContextMenu();
MenuItem sampleMenuItem = new MenuItem("Sample Button");
{
rowMenu.getItems().addAll(sampleMenuItem);
contextMenuProperty()
.bind(Bindings
.when(Bindings.isNotNull(itemProperty()))
.then(rowMenu).otherwise((ContextMenu) null));
rowMenu.setOnShowing(e -> {
People selectedRow = getItem();
sampleMenuItem.setDisable(selectedRow.getAge() > 100);
});
}
};
return row;
});

javafx: How to bind disable button with dynamic created checkboxes?

I want to bind the disable of a button with dynamically created checkboxes. The Button should be enabled if a checkbox is selected.
This is my code
public class DietTabPageController {
#FXML
private FlowPane parent;
#FXML
private Button okButton;
private ObservableList<CheckBox> checkBoxes=FXCollections.observableArrayList();
#FXML
private void initialize() {
ObservableList<Diet> diets = DietDAO.getDiets();
diets.forEach(diet -> checkBoxes.add(new CheckBox(diet.getName())));
//checkboxes added in parent Flowpane
parent.getChildren().addAll(checkBoxes);
}
}
Any suggestions? Thanks
You can use JavaFX's really nice Bindings-class!
Try this:
okButton.disableProperty().bind(
Bindings.createBooleanBinding(
()->!checkBoxes.stream().anyMatch(CheckBox::isSelected),
checkBoxes.stream().map(x->x.selectedProperty()).toArray(Observable[]::new)
)
);
This creates a new Binding, which will listen on every checkbox and then call the given function to calculate the value of your property.
Additional reading here: Bindings
Regarding your comment:
I don't know how much you can edit your Diet class, but if you can, there is a very simple way to display your checkboxes and add the button-binding. Take a look at the following sample:
ListView<Diet> dietsView = new ListView<>(diets);
dietsView.setCellFactory(CheckBoxListCell.forListView(diet ->
diet.selectedProperty()));
btn.disableProperty().bind(
Bindings.createBooleanBinding(
() -> !diets.stream().anyMatch(diet->diet.isSelected()),
diets.stream().map(x->x.selectedProperty())
.toArray(Observable[]::new)
)
);
add this to Diet class:
private final BooleanProperty selected = new SimpleBooleanProperty();
public final BooleanProperty selectedProperty() {
return this.selected;
}
public final boolean isSelected() {
return this.selectedProperty().get();
}
public final void setSelected(final boolean on) {
this.selectedProperty().set(on);
}
You need to add listeners to all the selected properties of the CheckBoxes. Every time one of the property changes, modify the Button's disable property, if necessary. BTW: Making checkBoxes observable doesn't seem necessary:
private List<CheckBox> checkBoxes;
#FXML
private void initialize() {
ObservableList<Diet> diets = DietDAO.getDiets();
checkBoxes = new ArrayList<>(diets.size());
ChangeListener<Boolean> listener = (o, oldValue, newValue) -> {
if (newValue) {
// activate button since at least one CheckBox is selected
okButton.setDisable(false);
} else {
// disable button, if the last CheckBox was unselected
for (CheckBox cb : checkBoxes) {
if (cb.isSelected()) {
return; // don't do anything, if there still is a selected CheckBox
}
}
okButton.setDisable(true);
}
};
for (Diet diet : diets) {
CheckBox cb = new CheckBox(diet.getName());
cb.selectedProperty().addListener(listener);
checkBoxes.add(cb);
}
//checkboxes added in parent Flowpane
parent.getChildren().addAll(checkBoxes);
}

JavaFX copying over a object from one tableview to another with a button

So I´m building a warband calculator for a tabletop game and currently it looks like this
What I wanna do is that when I click on a "add" button it copies that unit/creature over to the tableview on the right side(So if I click on the "add" button on the Zombie row, a zombie gets copied over the tableview on the right).
The problem is I can only make it work if you select the row THEN click the button, but I want to be able to rely solely on the button. I think the problem is that I use "getSelectionModel().getSelectedItem()" in the button class to get the object to be copied over, But I cant find any other way to do it.
The relevant code parts from the main class
//Creates the lists
ObservableList<Unit> rightSideList = FXCollections.observableArrayList();
ObservableList<Unit> leftSideList = FXCollections.observableArrayList();
// Puts some test data in the lists
public Main() {
rightSideList.add(new Unit("Skeleton",5,4,9,4,1,6,9));
rightSideList.add(new Unit("Ghoul",6,4,010,4,1,6,7));
rightSideList.add(new Unit("Zombie",4,5,1,3,1,6,5));
rightSideList.add(new Unit("Wraith",4,5,19,3,1,6,5));
rightSideList.add(new Unit("Spectre",4,5,1,3,1,6,5));
leftSideList.add(new Unit("Skeleton",5,4,0,4,1,6,9));
}
//Creates the tables
final TableView<Unit> table1 = new TableView<>(
rightSideList
);
final TableView<Unit> table2 = new TableView<>(
leftSideList
);
//Defines the table columns
//Columns for table 1
TableColumn<Unit,String> unitNameCol = new TableColumn<>("Unit");
unitNameCol.setCellValueFactory(new PropertyValueFactory("unitName"));
unitNameCol.setMinWidth(100);
TableColumn<Unit,Integer> speedCol = new TableColumn<>("Spd");
speedCol.setCellValueFactory(new PropertyValueFactory("speed"));
TableColumn<Unit,Integer> meleeCol = new TableColumn<>("Me");
meleeCol.setCellValueFactory(new PropertyValueFactory("melee"));
TableColumn<Unit,Integer> rangedCol = new TableColumn<>("Ra");
rangedCol.setCellValueFactory(new PropertyValueFactory("ranged"));
TableColumn<Unit,Integer> defenseCol = new TableColumn<>("Def");
defenseCol.setCellValueFactory(new PropertyValueFactory("defense"));
TableColumn<Unit,Integer> attackCol = new TableColumn<>("Att");
attackCol.setCellValueFactory(new PropertyValueFactory("attack"));
TableColumn<Unit,Integer> toughnessCol = new TableColumn<>("To");
toughnessCol.setCellValueFactory(new PropertyValueFactory("toughness"));
TableColumn<Unit,Integer> costCol = new TableColumn<>("Cost");
costCol.setCellValueFactory(new PropertyValueFactory("cost"));
TableColumn<Unit, Boolean> actionCol = new TableColumn<>("Action");
actionCol.setSortable(false);
actionCol.setMinWidth(35);
// define a simple boolean cell value for the action column so that the column will only be shown for non-empty rows for table 1
actionCol.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Unit, Boolean>, ObservableValue<Boolean>>() {
#Override public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<Unit, Boolean> features) {
return new SimpleBooleanProperty(features.getValue() != null);
}
});
// create a cell value factory with an add button for each row in the table for table 1
actionCol.setCellFactory(new Callback<TableColumn<Unit, Boolean>, TableCell<Unit, Boolean>>() {
#Override public TableCell<Unit, Boolean> call(TableColumn<Unit, Boolean> unitBooleanTableColumn) {
return new AddUnitCell(mainStage, table1);
}
});
And here is the button class
/** A table cell containing a button for adding a unit */
private class AddUnitCell extends TableCell<Unit, Boolean> {
// a button for adding a new Unit.
final Button addButton = new Button("Add");
// pads and centers the add button in the cell.
final StackPane paddedButton = new StackPane();
/**
* AddUnitCell constructor
* #param stage the stage in which the table is placed.
* #param table the table to which a unit can be added.
*/
AddUnitCell(final Stage stage, final TableView<Unit> table) {
paddedButton.setPadding(new Insets(3));
paddedButton.getChildren().add(addButton);
addButton.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent actionEvent) {
Unit selectedUnit = table.getSelectionModel().getSelectedItem();
leftSideList.add(selectedUnit);
}
});
}
/** places an add button in the row only if the row is not empty. */
#Override protected void updateItem(Boolean item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
setGraphic(paddedButton);
} else {
setGraphic(null);
}
}
}
If you need to check in detail here is a link to the projects repository
https://github.com/MagnusLindstrom88/Star-Struck-City-Warband-Calculator/blob/master/src/application/Main.java
Instead of
Unit selectedUnit = table.getSelectionModel().getSelectedItem();
in the button event handler's handle() method, do
Unit selectedUnit = table.getItems().get(getIndex());
Instead of relying on the selection model to get the item, you should get the item from the TableRow:
Unit selectedUnit = (Unit) getTableRow().getItem();

vaadin] how to Showing extra data for Grid rows

I used grid component, and added row details..
However grid doesn't show details..
It's my code.
====
Grid grid = new Grid("Plain Grid");
grid.setDetailsGenerator(new DetailsGenerator() {
#Override
public Component getDetails(RowReference rowReference) {
// Find the bean to generate details for
final TrainingMemberVo bean = (TrainingMemberVo) rowReference.getItemId();
// A basic label with bean data
Label label = new Label("Extra data for " + bean.getMemberName());
// A button just for the sake of the example
Button button = new Button("Click me", new Button.ClickListener() {
#Override
public void buttonClick(ClickEvent event) {
Notification.show("Button clicked for " + bean.getMemberName());
}
});
// Wrap up all the parts into a vertical layout
VerticalLayout layout = new VerticalLayout(label, button);
layout.setSpacing(true);
layout.setMargin(true);
return layout;
}
});
grid.addItemClickListener(new ItemClickListener() {
#Override
public void itemClick(ItemClickEvent event) {
if (event.isDoubleClick()) {
Object itemId = event.getItemId();
grid.setDetailsVisible(itemId, !grid.isDetailsVisible(itemId));
}
}
});
===
double clicked row, noting shows details..
Works for me without any issues. Have you checked if the event in the itemClick() is correctly fired? I. e. remove the boolean check for event.isDoubleClick() to see if it gets executed.

Resources