setOnMouseEntered / Exited on ListView Cell - java

I'm trying to make a ListView in which each cell is composed of a Label and a Button. I want to make the Button appear when my mouse flies over the cell and disappear when it flies out. To do that I used the method setOnMouseEntered() on the ListCell object but the Button appears only for the first cell (the latest item added to the ObservableList)
My Custom ListCell class :
public class SubscribedTopicListCell extends ListCell<String> {
private final Label lSubscribedTopic = new Label();
private final Button btnUnsubscribe = new Button();
private static final ImageView ivBtnGraphic = new ImageView(new Image("resources/images/cross.png"));
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setGraphic(null);
if (!empty && item != null) {
lSubscribedTopic.setText(item);
btnUnsubscribe.setVisible(false);
btnUnsubscribe.setGraphic(ivBtnGraphic);
btnUnsubscribe.setBackground(Background.EMPTY);
btnUnsubscribe.setOnAction(e ->
MqttConnection.getInstance().unsubscribe(item)
);
this.setOnMouseEntered(e ->
btnUnsubscribe.setVisible(true)
);
this.setOnMouseExited(e ->
btnUnsubscribe.setVisible(false)
);
GridPane listCellPane = new GridPane();
listCellPane.add(lSubscribedTopic, 0, 0);
listCellPane.add(btnUnsubscribe, 1, 0);
ColumnConstraints col0 = new ColumnConstraints();
col0.setHalignment(HPos.LEFT);
ColumnConstraints col1 = new ColumnConstraints();
col1.setHalignment(HPos.RIGHT);
col1.setHgrow(Priority.ALWAYS);
listCellPane.getColumnConstraints().addAll(col0, col1);
setGraphic(listCellPane);
}
}
}
How can I make it work for each cells ?

Only one cell can ever have a button, because you have made the ImageView static. ImageView is a Node, and each node can only appear once in the scene graph. By making the ImageView static, you try to force the same ImageView into the scene graph in multiple places. When you call setGraphic(...) on a button, the image view effectively gets removed from the previous button in order to fulfill the rule that it can only be used once in the scene graph. (I suspect all the buttons are really there, but only one has a graphic: since there is no text and no background, the others are completely invisible, probably with zero dimension.)
The fix is to make the ImageView an instance variable. Note that Image is not a node, and multiple ImageViews can share the same Image, so you can avoid multiple copies of the image data in memory by making the Image static.
Finally, while it won't really change the functionality, it doesn't really make sense to re-register the listeners every time updateItem() is called; you can do this just once in the constructor. Similarly for the layout:
public class SubscribedTopicListCell extends ListCell<String> {
private final Label lSubscribedTopic = new Label();
private final Button btnUnsubscribe = new Button();
private static final Image image = new Image("resources/images/cross.png");
private final ImageView ivBtnGraphic = new ImageView(image);
private final GridPane listCellPane = new GridPane();
public SubscribedTopicListCell() {
btnUnsubscribe.setOnAction(e ->
MqttConnection.getInstance().unsubscribe(getItem())
);
this.setOnMouseEntered(e ->
btnUnsubscribe.setVisible(true)
);
this.setOnMouseExited(e ->
btnUnsubscribe.setVisible(false)
);
listCellPane.add(lSubscribedTopic, 0, 0);
listCellPane.add(btnUnsubscribe, 1, 0);
ColumnConstraints col0 = new ColumnConstraints();
col0.setHalignment(HPos.LEFT);
ColumnConstraints col1 = new ColumnConstraints();
col1.setHalignment(HPos.RIGHT);
col1.setHgrow(Priority.ALWAYS);
listCellPane.getColumnConstraints().addAll(col0, col1);
btnUnsubscribe.setVisible(false);
btnUnsubscribe.setGraphic(ivBtnGraphic);
btnUnsubscribe.setBackground(Background.EMPTY);
}
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setGraphic(null);
if (!empty && item != null) {
lSubscribedTopic.setText(item);
setGraphic(listCellPane);
}
}
}

Related

How to reserve space for the VirtualFlow scrollbars?

The current implementation of the VirtualFlow only makes scrollbars visible when view rect becomes less than control size. By control I mean ListView, TreeView and whatever standard virtualized controls. The problem is that vertical scrollbar appearance causes recalculation of the control width, namely it slightly shifts cell content to the left side. This is clearly noticeable and very uncomfortable movement.
I need to reserve some space for the vertical scrollbar beforehand, but none of controls provide API to manipulate VirtualFlow scrollbars behavior, which is very unfortunate API design. Not to mention that most of the implementations place scrollbars on top of the component, thus just overlapping the small part of it.
The question is, "Which is the best way to achieve this?". Paddings won't help, and JavaFX has no margins support. I could put control (e.g ListView) inside of ScrollPane, but I'd bet VirtualFlow won't continue to reuse cells in that case, so it's not a solution.
EXAMPLE:
Expand and collapse node2, it shifts lbRight content.
public class Launcher extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
TreeItem<UUID> root = new TreeItem<>(UUID.randomUUID());
TreeView<UUID> tree = new TreeView<>(root);
tree.setCellFactory(list -> new CustomCell());
TreeItem<UUID> node0 = new TreeItem<>(UUID.randomUUID());
TreeItem<UUID> node1 = new TreeItem<>(UUID.randomUUID());
TreeItem<UUID> node2 = new TreeItem<>(UUID.randomUUID());
IntStream.range(0, 100)
.mapToObj(index -> new TreeItem<>(UUID.randomUUID()))
.forEach(node2.getChildren()::add);
root.getChildren().setAll(node0, node1, node2);
root.setExpanded(true);
node2.setExpanded(true);
BorderPane pane = new BorderPane();
pane.setCenter(tree);
Scene scene = new Scene(pane, 600, 600);
primaryStage.setTitle("Demo");
primaryStage.setScene(scene);
primaryStage.setOnCloseRequest(t -> Platform.exit());
primaryStage.show();
}
static class CustomCell extends TreeCell<UUID> {
public HBox hBox;
public Label lbLeft;
public Label lbRight;
public CustomCell() {
hBox = new HBox();
lbLeft = new Label();
lbRight = new Label();
lbRight.setStyle("-fx-padding: 0 20 0 0");
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
hBox.getChildren().setAll(lbLeft, spacer, lbRight);
}
#Override
protected void updateItem(UUID uuid, boolean empty) {
super.updateItem(uuid, empty);
if (empty) {
setGraphic(null);
return;
}
String s = uuid.toString();
lbLeft.setText(s.substring(0, 6));
lbRight.setText(s.substring(6, 12));
setGraphic(hBox);
}
}
}
Reacting to
you can't just extend the VirtualFlow and override a method
certainly true if the method is deeply hidden by package/-private access (but even then: javafx is open source, checkout-edit-compile-distribute is also an option :). In this case we might get along with overriding public api as outlined below (not formally tested!).
VirtualFlow is the "layout" of cells and scrollBars: in particular, it has to cope with handling sizing/locating of all content w/out scrollBars being visible. There are options on how that can be done:
adjust cell width to always fill the viewport, increasing/decreasing when vertical scrollBar is hidden/visible
keep cell width constant such that there is always space left for the scrollBar, be it visible or not
keep cell width constant such that there is never space left the scrollBar, laying it out on top of cell
others ??
Default VirtualFlow implements the first with no option to switch to any other. (might be candidate for an RFE, feel free to report :).
Digging into the code reveals that the final sizing of the cells is done by calling cell.resize(..) (as already noted and exploited in the self-answer) near the end of the layout code. Overriding a custom cell's resize is perfectly valid and a good option .. but not the only one, IMO. An alternative is to
extend VirtualFlow and override layoutChildren to adjust cell width as needed
extend TreeViewSkin to use the custom flow
Example code (requires fx12++):
public static class XVirtualFlow<I extends IndexedCell> extends VirtualFlow<I> {
#Override
protected void layoutChildren() {
super.layoutChildren();
fitCellWidths();
}
/**
* Resizes cell width to accomodate for invisible vbar.
*/
private void fitCellWidths() {
if (!isVertical() || getVbar().isVisible()) return;
double width = getWidth() - getVbar().getWidth();
for (I cell : getCells()) {
cell.resize(width, cell.getHeight());
}
}
}
public static class XTreeViewSkin<T> extends TreeViewSkin<T>{
public XTreeViewSkin(TreeView<T> control) {
super(control);
}
#Override
protected VirtualFlow<TreeCell<T>> createVirtualFlow() {
return new XVirtualFlow<>();
}
}
On-the-fly usage:
TreeView<UUID> tree = new TreeView<>(root) {
#Override
protected Skin<?> createDefaultSkin() {
return new XTreeViewSkin<>(this);
}
};
Ok, this is summary based on #kleopatra comments and OpenJFX code exploration. There will be no code to solve the problem, but still maybe it will spare some time to someone.
As being said, it's VirtualFlow responsibility to manage virtualized control viewport size. All magic happens in the layoutChildren(). First it computes scrollbars visibility and then recalculates size of all children based on that knowledge. Here is the code which causes the problem.
Since all implementation details are private or package-private, you can't just extend the VirtualFlow and override method or two, you have to copy-paste and edit entire class (to remove one line, yes). Given that, changing internal components layout could be a better option.
Sometimes, I adore languages those have no encapsulation.
UPDATE:
I've solved the problem. There is no way no reserve space for vertical scrollbar without tweaking JavaFX internals, but we can limit cell width, so it would be always less than TreeView (or List View) width. Here is simple example.
public class Launcher extends Application {
public static final double SCENE_WIDTH = 500;
#Override
public void start(Stage primaryStage) {
TreeItem<UUID> root = new TreeItem<>(UUID.randomUUID());
TreeView<UUID> tree = new TreeView<>(root);
tree.setCellFactory(list -> new CustomCell(SCENE_WIDTH));
TreeItem<UUID> node0 = new TreeItem<>(UUID.randomUUID());
TreeItem<UUID> node1 = new TreeItem<>(UUID.randomUUID());
TreeItem<UUID> node2 = new TreeItem<>(UUID.randomUUID());
IntStream.range(0, 100)
.mapToObj(index -> new TreeItem<>(UUID.randomUUID()))
.forEach(node2.getChildren()::add);
root.getChildren().setAll(node0, node1, node2);
root.setExpanded(true);
node2.setExpanded(true);
BorderPane pane = new BorderPane();
pane.setCenter(tree);
Scene scene = new Scene(pane, SCENE_WIDTH, 600);
primaryStage.setTitle("Demo");
primaryStage.setScene(scene);
primaryStage.setOnCloseRequest(t -> Platform.exit());
primaryStage.show();
}
static class CustomCell extends TreeCell<UUID> {
public static final double RIGHT_PADDING = 40;
/*
this value depends on tree disclosure node width
in my case it's enforced via CSS, so I always know exact
value of this padding
*/
public static final double INDENT_PADDING = 14;
public HBox hBox;
public Label lbLeft;
public Label lbRight;
public double maxWidth;
public CustomCell(double maxWidth) {
this.maxWidth = maxWidth;
hBox = new HBox();
lbLeft = new Label();
lbRight = new Label();
lbRight.setPadding(new Insets(0, RIGHT_PADDING, 0, 0));
Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
hBox.getChildren().setAll(lbLeft, spacer, lbRight);
}
#Override
protected void updateItem(UUID uuid, boolean empty) {
super.updateItem(uuid, empty);
if (empty) {
setGraphic(null);
return;
}
String s = uuid.toString();
lbLeft.setText(s.substring(0, 6));
lbRight.setText(s.substring(6, 12));
setGraphic(hBox);
}
#Override
public void resize(double width, double height) {
// enforce item width
double maxCellWidth = getTreeView().getWidth() - RIGHT_PADDING;
double startLevel = getTreeView().isShowRoot() ? 0 : 1;
double itemLevel = getTreeView().getTreeItemLevel(getTreeItem());
if (itemLevel > startLevel) {
maxCellWidth = maxCellWidth - ((itemLevel - startLevel) * INDENT_PADDING);
}
hBox.setPrefWidth(maxCellWidth);
hBox.setMaxWidth(maxCellWidth);
super.resize(width, height);
}
}
}
It's far from perfect, but it works.

JavaFX - Positioning image with character input

I have a GUI that takes the input of an image name, and once the refresh button is pressed, its displayed in a fixed position. I want to be able to input a character 'A-G' which will change the X position of the image, and a character '0-6' that will change the Y position of the image. The name of the images are just "A1", "A2"..."A5". So, if the user inputs "A1B3", it will display the image A1 in X-Position 'B' and Y-Position '3'. So B could be 200, and 3 could be 300, which makes the (X,Y) coordinates (200,300).
This is my code that gets the users input for the image.
private void getImage(){
Image img = new Image("comp1110/ass2/gui/assets/" + textField.getText() + ".png", 100, 100, false, false);
ImageView image = new ImageView();
image.setImage(img);
image.setX(100);
image.setY(100);
pane.getChildren().add(image);
}
I think you should do something along the lines of this yes there is some cosmetic issues that you will need to fix. But its only to give you an idea of what to do. It uses a gridpane so you don't have to worry about getting exact coordinates I choose a vbox so I didn't have to worry about layout you can keep the Pane that you have it shouldn't make a difference.
public class Main extends Application {
private GridPane gridPane;
private TextField imageTextField = new TextField();
private HashMap<String,String> hashMap = new HashMap<>();
#Override
public void start(Stage primaryStage) {
fillHashMapValues();
gridPane = new GridPane();
gridPane.setGridLinesVisible(true);
for (int i = 0; i < 7; i++) {
RowConstraints rowConstraints = new RowConstraints();
rowConstraints.setPercentHeight(14);
gridPane.getRowConstraints().add(rowConstraints);
ColumnConstraints columnConstraints = new ColumnConstraints();
columnConstraints.setPercentWidth(14);
gridPane.getColumnConstraints().add(columnConstraints);
gridPane.addColumn(i);
gridPane.addRow(i);
}
imageTextField.setPromptText("Enter Image Letters?");
TextField textField = new TextField();
textField.setPromptText("Enter Coordinates");
Button button = new Button("Go!");
button.setOnAction(event -> {
addToGridPane(textField.getText());
});
VBox vBox = new VBox();
vBox.setPrefSize(300, 300);
vBox.setAlignment(Pos.TOP_CENTER);
vBox.getChildren().addAll(imageTextField, textField, button, gridPane);
primaryStage.setScene(new Scene(vBox));
primaryStage.show();
button.requestFocus();//This is only so you can see the prompt text its irrelevant
}
private void fillHashMapValues(){
hashMap.put("A", "1");
hashMap.put("B", "2");
hashMap.put("C", "3");
hashMap.put("D", "4");
hashMap.put("E", "5");
hashMap.put("F", "6");
hashMap.put("G", "7");
}
private void addToGridPane(String string){
char[] chars = string.toCharArray();
if(chars.length==2){//Do more data validation here
if(hashMap.containsKey(String.valueOf(chars[0]))) {
int xValue = Integer.parseInt(hashMap.get(String.valueOf(chars[0])));
int yValue = Integer.parseInt(String.valueOf(chars[1]));
ImageView image = getImage();
gridPane.add(image, xValue, yValue);
}
}
}
private ImageView getImage(){
Image image = new Image("comp1110/ass2/gui/assets/" + imageTextField.getText() + ".png", 100, 100, false, false);
ImageView imageView = new ImageView();
imageView.setImage(image);
//imageView.setX(100);
//imageView.setY(100);
//pane.getChildren().add(image);
return imageView;
}
public static void main(String[] args) { launch(args); }
}

Javafx listview disable horizontal scrolling

I'm trying to avoid horizontal scrolling in ListView. The ListView instance holds list of HBox items, each item has a different width.
So far I'm using such a cell factory:
public class ListViewCell extends ListCell<Data>
{
#Override
public void updateItem(Data data, boolean empty)
{
super.updateItem(data, empty);
if(empty || data == null){
setGraphic(null);
setText(null);
}
if(data != null)
{
Region region = createRow(data);
region.prefWidthProperty().bind(mListView.widthProperty().subtract(20));
region.maxWidthProperty().bind(mListView.widthProperty().subtract(20));
setGraphic(region);
}
}
}
Unfortunately it is not enough. Usually after adding several items ListView's horizontal scrollbar appears. Even if it seems to be unnecessary.
How can I assure, that ListViewCell will not exceed it's parent width and horizontal scrollbar will not appear?
There is a lot at play here that make customizing ListView horizontal scrollbar behavior difficult to deal with. In addition to that, common misunderstandings on how ListView works can cause other problems.
The main issue to address is that the width of the ListCells will not automatically adapt when the vertical scrollbar becomes visible. Therefore, the moment it is, suddenly the contents are too wide to fit between the left edge of the ListView and the left edge of the vertical scrollbar, triggering a horizontal scrollbar. There is also the default padding of a ListCell as well as the border widths of the ListView itself to consider when determining the proper binding to set.
The following class that extends ListView:
public class WidthBoundList extends ListView {
private final BooleanProperty vbarVisibleProperty = new SimpleBooleanProperty(false);
private final boolean bindPrefWidth;
private final double scrollbarThickness;
private final double sumBorderSides;
public WidthBoundList(double scrollbarThickness, double sumBorderSides, boolean bindPrefWidth) {
this.scrollbarThickness = scrollbarThickness;
this.sumBorderSides = sumBorderSides;
this.bindPrefWidth = bindPrefWidth;
Platform.runLater(()->{
findScroller();
});
}
private void findScroller() {
if (!this.getChildren().isEmpty()) {
VirtualFlow flow = (VirtualFlow)this.getChildren().get(0);
if (flow != null) {
List<Node> flowChildren = flow.getChildrenUnmodifiable();
int len = flowChildren .size();
for (int i = 0; i < len; i++) {
Node n = flowChildren .get(i);
if (n.getClass().equals(VirtualScrollBar.class)) {
final ScrollBar bar = (ScrollBar) n;
if (bar.getOrientation().equals(Orientation.VERTICAL)) {
vbarVisibleProperty.bind(bar.visibleProperty());
bar.setPrefWidth(scrollbarThickness);
bar.setMinWidth(scrollbarThickness);
bar.setMaxWidth(scrollbarThickness);
} else if (bar.getOrientation().equals(Orientation.HORIZONTAL)) {
bar.setPrefHeight(scrollbarThickness);
bar.setMinHeight(scrollbarThickness);
bar.setMaxHeight(scrollbarThickness);
}
}
}
} else {
Platform.runLater(()->{
findScroller();
});
}
} else {
Platform.runLater(()->{
findScroller();
});
}
}
public void bindWidthScrollCondition(Region node) {
node.maxWidthProperty().unbind();
node.prefWidthProperty().unbind();
node.maxWidthProperty().bind(
Bindings.when(vbarVisibleProperty)
.then(this.widthProperty().subtract(scrollbarThickness).subtract(sumBorderSides))
.otherwise(this.widthProperty().subtract(sumBorderSides))
);
if (bindPrefWidth) {
node.prefWidthProperty().bind(node.maxWidthProperty());
}
}
}
Regarding your code, your bindings could cause problems. A ListCell's updateItem() method is not only called when the ListCell is created. A ListView can contain a pretty large list of data, so to improve the performance only the ListCells scrolled into view (and possibly a few before and after) need their graphic rendered. The updateItem() method handles this. In your code, a Region is being created over and over again and each and every one of them is being bound to the width of your ListView. Instead, the ListCell itself should be bound.
The following class extends ListCell and the method to bind the HBox is called in the constructor:
public class BoundListCell extends ListCell<String> {
private final HBox hbox;
private final Label label;
public BoundListCell(WidthBoundList widthBoundList) {
this.setPadding(Insets.EMPTY);
hbox = new HBox();
label = new Label();
hbox.setPadding(new Insets(2, 4, 2, 4));
hbox.getChildren().add(label);
widthBoundList.bindWidthScrollCondition(this);
}
#Override
public void updateItem(String data, boolean empty) {
super.updateItem(data, empty);
if (empty || data == null) {
label.setText("");
setGraphic(null);
setText(null);
} else {
label.setText(data);
setGraphic(hbox);
}
}
}
The scrollbarThickness parameter of WidthBoundList constructor has been set to 12. The sumBorderSides parameter has been set to 2 because my WidthBoundList has a one pixel border on the right and left. The bindPrefWidth parameter has been set to true to prevent the horizontal scroller from showing at all (labels have ellipses, any non-text nodes that you might add to the hbox will simply be clipped). Set bindPrefWidth to false to allow a horizontal scrollbar, and with these proper bindings it should only show when needed. An implementation:
private final WidthBoundList myListView = new WidthBoundList(12, 2, true);
public static void main(final String... a) {
Application.launch(a);
}
#Override
public void start(final Stage primaryStage) throws Exception {
myListView.setCellFactory(c -> new BoundListCell(myListView));
VBox vBox = new VBox();
vBox.setFillWidth(true);
vBox.setAlignment(Pos.CENTER);
vBox.setSpacing(5);
Button button = new Button("APPEND");
button.setOnAction((e)->{
myListView.getItems().add("THIS IS LIST ITEM NUMBER " + myListView.getItems().size());
});
vBox.getChildren().addAll(myListView, button);
myListView.maxWidthProperty().bind(vBox.widthProperty().subtract(20));
myListView.prefHeightProperty().bind(vBox.heightProperty().subtract(20));
primaryStage.setScene(new Scene(vBox, 200, 400));
primaryStage.show();
}

how to add remove button in combobox

I would like to create a ComboBox with the remove button like the picture below:
The picture uses Java Swing, and I don't know how to do this with JavaFX. I would like to create two ComboBoxes (a,b). When I click the "cross" in ComboBox a, I would like to remove a's item and add this item to ComboBox b, and ComboBox b so on.
ComboBox a:
(1)click item then remove it from a and add on b
ComboBox b:
(1)click item then do something(ex:print item)
(2)click cross then remove it from b and add on a
package UnitTest;
import Peer.Peer_Manager;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.chart.XYChart;
import javafx.geometry.Insets;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
public class temp extends Application {
final int height = 200;
final int weight = 300;
final int offset = 5;
Peer_Manager p_management;
XYChart.Series series_hop;
XYChart.Series series_gd;
#Override
public void start(Stage primaryStage) {
VBox vbox = new VBox();
vbox.setPadding(new Insets(5, 5, 5, 5));
vbox.setStyle("-fx-background-color: CORNSILK;");
Scene scene = new Scene(vbox, weight, height);
primaryStage.setScene(scene);
HBox hbBtn = new HBox();
Text t1=new Text(" A:");
Text t2=new Text(" B:");
String[] filename = {"A","B","C"};//conf.load_all();
ComboBox<String> cb = new ComboBox<String>();
cb.setItems(FXCollections.observableArrayList(filename));
cb.setVisibleRowCount(10);
ComboBox<String> cb2 = new ComboBox<String>();
cb.setVisibleRowCount(10);
vbox.getChildren().add(hbBtn);
hbBtn.getChildren().add(t1);
hbBtn.getChildren().add(cb);
hbBtn.getChildren().add(t2);
hbBtn.getChildren().add(cb2);
cb.setOnAction(e -> {
try {
Object object = cb.getValue();
if (object != null) {
cb2.getItems().add(object);
cb.getSelectionModel().clearSelection();
cb.getItems().remove(object);
}
} catch (Exception e1) {
e1.printStackTrace();
}
});
//would like to do something(ex:print item),but don't remove
//add the "cross" beside items,click "cross" to remove item and add on cb
cb2.setOnAction(e -> {
try {
Object object = cb2.getValue();
System.out.println(object);
if (object != null) {
cb1.getItems().add(object);
cb2.getSelectionModel().clearSelection();
cb2.getItems().remove(object);
}
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
});
primaryStage.setTitle("SimulatorFX");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
The correct way is to use a CellFactory and create graphic nodes that contain the elements you wish to have. Here is an example:
public void start(Stage primaryStage) throws Exception {
ComboBox<String> cba = new ComboBox<>();
ComboBox<String> cbb = new ComboBox<>();
cba.getItems().addAll("A", "B", "C");
cbb.getItems().addAll("123", "456", "789");
// Set a cell factory for ComboBox A. A similar thing should be done for B.
cba.setCellFactory(lv ->
new ListCell<String>() {
// This is the node that will display the text and the cross.
// I chose a hyperlink, but you can change to button, image, etc.
private HBox graphic;
// this is the constructor for the anonymous class.
{
Label label = new Label();
// Bind the label text to the item property. If your ComboBox items are not Strings you should use a converter.
label.textProperty().bind(itemProperty());
// Set max width to infinity so the cross is all the way to the right.
label.setMaxWidth(Double.POSITIVE_INFINITY);
// We have to modify the hiding behavior of the ComboBox to allow clicking on the hyperlink,
// so we need to hide the ComboBox when the label is clicked (item selected).
label.setOnMouseClicked(event -> cba.hide());
Hyperlink cross = new Hyperlink("X");
cross.setVisited(true); // So it is black, and not blue.
cross.setOnAction(event ->
{
// Since the ListView reuses cells, we need to get the item first, before making changes.
String item = getItem();
System.out.println("Clicked cross on " + item);
if (isSelected()) {
// Not entirely sure if this is needed.
cba.getSelectionModel().select(null);
}
// Remove the item from A and add to B. You can add any additional logic in here.
cba.getItems().remove(item);
cbb.getItems().add(item);
}
);
// Arrange controls in a HBox, and set display to graphic only (the text is included in the graphic in this implementation).
graphic = new HBox(label, cross);
graphic.setHgrow(label, Priority.ALWAYS);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
} else {
setGraphic(graphic);
}
}
});
// We have to set a custom skin, otherwise the ComboBox disappears before the click on the Hyperlink is registered.
cba.setSkin(new ComboBoxListViewSkin<String>(cba) {
#Override
protected boolean isHideOnClickEnabled() {
return false;
}
});
VBox vb = new VBox(cba, cbb);
primaryStage.setScene(new Scene(vb));
primaryStage.show();
}

JavaFX ListView very slow

I'm making a chat application using JavaFX for the GUI. I display the chat content in a ListView, but I have one big problem - it's very very slow. When I add new items to the list and especially when I scroll the list up/down. I think maybe it has something to do with the fact that the list refreshes itsellf every time a new item is added (each cell in the list!) and also refreshes every time I scroll up/down.
Does someone know what can I do to solve this problem? TNX
I override ListCell's updateItem:
chatListView.setCellFactory(new Callback<ListView<UserInfo>, ListCell<UserInfo>>() {
#Override
public ListCell<UserInfo> call(ListView<UserInfo> p) {
ListCell<UserInfo> cell = new ListCell<UserInfo>() {
#Override
protected void updateItem(UserInfo item, boolean bln) {
super.updateItem(item, bln);
if (item != null) {
BorderPane borderPane = new BorderPane();
ImageView profileImage = new ImageView(new Image(item.getImageURL()));
profileImage.setFitHeight(32);
profileImage.setFitWidth(32);
Rectangle clip = new Rectangle(
profileImage.getFitWidth(), profileImage.getFitHeight()
);
clip.setArcWidth(30);
clip.setArcHeight(30);
profileImage.setClip(clip);
SnapshotParameters parameters = new SnapshotParameters();
parameters.setFill(Color.TRANSPARENT);
WritableImage image = profileImage.snapshot(parameters, null);
profileImage.setClip(null);
profileImage.setImage(image);
ImageView arrowImage = new ImageView(new Image("arrow1.png"));
ImageView arrowImage2 = new ImageView(new Image("arrow1.png"));
Label nameLabel = new Label(item.getUserName());
nameLabel.setStyle(" -fx-text-alignment: center; -fx-padding: 2;");
HBox hbox = null;
Label textLabel = new Label();
String messageText = splitTolines(item.getMessage());
textLabel.setText(messageText);
textLabel.setStyle("-fx-background-color: #a1f2cd; "
+ "-fx-padding: 10;\n"
+ "-fx-spacing: 5;");
hbox = new HBox(arrowImage, textLabel);
VBox vbox = new VBox(profileImage, nameLabel);
BorderPane.setMargin(vbox, new Insets(0, 10, 10, 10));
BorderPane.setMargin(hbox, new Insets(10, 0, 0, 0));
//Time
Date dNow = new Date();
SimpleDateFormat ft = new SimpleDateFormat("hh:mm a");
Label timeLabel = new Label(ft.format(dNow));
timeLabel.setStyle("-fx-font: 8px Tahoma; -fx-width: 100%");
HBox hbox2 = new HBox(arrowImage2, timeLabel);
arrowImage2.setVisible(false);
VBox vbox2 = new VBox(hbox, hbox2);
borderPane.setCenter(vbox2);
borderPane.setLeft(vbox);
setGraphic(borderPane);
}
}
};
return cell;
}
});
Never ever add (big) GUI Elements in updateItem() without checking if it is not already there.
updateItem() is called everytime for EVERY SINGLE ROW when you scroll, resize or change gui in any other way.
You should alway reset the graphic to null if you do not have an item or the second boolean of updateItem(item, empty) is false, because the second boolean is the EMPTY flag.
I recommend to you that you use a VBox instead of a ListView.
You must not build new instances of your components everytime the view gets updated.
Instanciate them one time initialy, then you reuse and change their attributes.
I just noticed that too. It's too slow even for a list containing only 5-10 items (with scaled images and text). Since I need no selection feature, I also rewrote the code to use VBox instead and the slowness is immediately gone!
To emulate the setItems, I have a helper function which you may find handy:
public static <S, T> void mapByValue(
ObservableList<S> sourceList,
ObservableList<T> targetList,
Function<S, T> mapper)
{
Objects.requireNonNull(sourceList);
Objects.requireNonNull(targetList);
Objects.requireNonNull(mapper);
targetList.clear();
Map<S, T> sourceToTargetMap = new HashMap<>();
// Populate targetList by sourceList and mapper
for (S s : sourceList)
{
T t = mapper.apply(s);
targetList.add(t);
sourceToTargetMap.put(s, t);
}
// Listen to changes in sourceList and update targetList accordingly
ListChangeListener<S> sourceListener = new ListChangeListener<S>()
{
#Override
public void onChanged(ListChangeListener.Change<? extends S> c)
{
while (c.next())
{
if (c.wasPermutated())
{
for (int i = c.getFrom(); i < c.getTo(); i++)
{
int j = c.getPermutation(i);
S s = sourceList.get(j);
T t = sourceToTargetMap.get2(s);
targetList.set(i, t);
}
}
else
{
for (S s : c.getRemoved())
{
T t = sourceToTargetMap.get2(s);
targetList.remove2(t);
sourceToTargetMap.remove2(s);
}
int i = c.getFrom();
for (S s : c.getAddedSubList())
{
T t = mapper.apply(s);
targetList.add(i, t);
sourceToTargetMap.put(s, t);
i += 1;
}
}
}
}
};
sourceList.addListener(new WeakListChangeListener<>(sourceListener));
// Store the listener in targetList to prevent GC
// The listener should be active as long as targetList exists
targetList.addListener((InvalidationListener) iv ->
{
Object[] refs = { sourceListener, };
Objects.requireNonNull(refs);
});
}
It can then be used like:
ObservableList<Bookmark> bookmarkList;
VBox bookmarkListVBox;
mapByValue(bookmarkList, bookmarkListVBox.getChildren(), bmk -> new Label(bmk.getName());
To automatically update the list (VBox's children) from observable list.
PS: other functions such as grouping are here => ObservableListHelper

Categories