0

我对上下文菜单有疑问。上下文菜单中的项目可以设置样式,但不能动态工作。我的意思是,例如,在初始化时,我向 中添加了一个样式类,MenuItem并通过一个事件将其删除,但样式仍然存在。如何解决?

这是一个简单的例子:

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;
}

我怎样才能设法添加/删除样式到我的MenuItem

4

0 回答 0