I have a problem with context menus. The items in the context menu can be styled, but it doesn't work dynamic. I mean for example at the initialize I add a styleclass to the MenuItem
and by an event I remove it, but the style still remains there. How can it be solved?
Here is a simple example to play with it:
Controller.java
:
public class Controller implements Initializable {
private static final String STYLED = "styled";
@FXML
private ListView<String> listView;
@FXML
private Button change;
@Override
public void initialize(URL location, ResourceBundle resources) {
ContextMenu cm = new ContextMenu();
MenuItem miAdd = new MenuItem("Add");
miAdd.setOnAction(event -> listView.getItems().add("Apple"));
MenuItem miRemove = new MenuItem("Remove");
miRemove.disableProperty().bind(listView.getSelectionModel().selectedItemProperty().isNull());
miRemove.setOnAction(event -> listView.getItems().remove(listView.getSelectionModel().getSelectedItem()));
cm.getItems().addAll(miAdd, miRemove);
listView.setContextMenu(cm);
miRemove.getStyleClass().add(STYLED);
change.setOnAction(event -> {
if (!miRemove.getStyleClass().contains(STYLED)) {
miRemove.getStyleClass().add(STYLED);
} else {
miRemove.getStyleClass().remove(STYLED);
}
});
}
}
View.fxml
:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.ListView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.VBox?>
<AnchorPane xmlns="http://javafx.com/javafx"
xmlns:fx="http://javafx.com/fxml"
fx:controller="textField.Controller"
stylesheets="css/layout.css">
<VBox>
<Button fx:id="change" text="ChangeStyle"/>
<ListView fx:id="listView"/>
</VBox>
</AnchorPane>
layout.css
:
.styled .text {
-fx-strikethrough: true;
}
.styled {
-fx-background-color: gray;
}
How can I manage to add/remove style to my MenuItem
?