Как (правильно) сделать интерактивный элемент управления JavaFX? - PullRequest
0 голосов
/ 23 марта 2020

У меня вопрос о том, как лучше реализовать интерактивный элемент управления JavaFX. По сути, я хотел бы позволить пользователям «щелкать» по моему элементу управления, но вместо того, чтобы обрабатывать события мыши, я хочу, чтобы он также обрабатывал и другие его аспекты: ввод с клавиатуры, вкладки и т. Д. c.

* 1002. * Я создал пользовательский элемент управления, расположенный в DashboardAction.java, со связанным файлом F XML dashboard_action.fxml. Ниже приводится DashboardAction.java:
// [Package, imports, etc. removed.]

/**
 * A sub-class of VBox that represents a "dashboard action" custom component. A DashboardAction displays (1) a
 * description of the action, and (2) an icon.
 *
 * @version 0.0.1
 * @author Jacob Lockard
 */
public class DashboardAction extends VBox implements Initializable {
    /**
     * A simple String property that represents the description of this dashboard action.
     */
    private SimpleStringProperty actionDescription;
    /**
     * A simple Image property that represents the icon image of this dashboard action.
     */
    private ObjectProperty<Image> actionIconImage;
    /**
     * A Label that displays the description.
     */
    @FXML
    private Label actionDescriptionLabel;
    /**
     * An ImageView that displays the icon.
     */
    @FXML
    private ImageView actionIconImageView;

    /**
     * Constructs a new instance of DashboardAction.
     */
    public DashboardAction() {
        // Initialize properties.
        actionDescription = new SimpleStringProperty("");
        actionIconImage = new SimpleObjectProperty<>(null);

        // Attempt to load an associated FXML file into this custom control.
        FXMLQuickLoader.loadToControl(this);
    }

    /**
     * Gets the description of this dashboard action.
     *
     * @return a String object representing the description.
     */
    public String getActionDescription() {
        return actionDescription.get();
    }

    /**
     * Sets the description of this dashboard action.
     *
     * @param actionDescription A String object representing the description.
     */
    public void setActionDescription(String actionDescription) {
        this.actionDescription.set(actionDescription);
    }

    /**
     * Gets the description property of this dashboard action.
     *
     * @return a SimpleStringProperty object representing the description.
     */
    public SimpleStringProperty actionDescription() {
        return actionDescription;
    }

    /**
     * Gets the icon image of this dashboard action.
     *
     * @return an Image object representing the icon image.
     */
    public Image getActionIconImage() {
        return actionIconImage.get();
    }

    /**
     * Sets the icon image of this dashboard action.
     *
     * @param actionIconImage An Image object representing the icon image.
     */
    public void setActionIconImage(Image actionIconImage) {
        this.actionIconImage.set(actionIconImage);
    }

    /**
     * Gets the icon image property of this dashboard action.
     *
     * @return a ObjectProperty object representing the icon image.
     */
    public ObjectProperty<Image> actionIconImage() {
        return actionIconImage;
    }

    /**
     * Sets the icon image of this dashboard action to a new Image at the given file path.
     *
     * @param path A String object representing the file path of the Image.
     */
    public void setActionIconImagePath(String path) {
        setActionIconImage(new Image(path));
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // Bind properties to controls.
        actionDescriptionLabel.textProperty().bind(actionDescription());
        actionIconImageView.imageProperty().bind(actionIconImage());
    }
}

И dashboard_action.fxml:

<!-- [XML definition, imports, etc. removed] -->
<fx:root type="VBox" xmlns="http://javafx.com/javafx"
         xmlns:fx="http://javafx.com/fxml"
         prefHeight="100" prefWidth="100"
         maxHeight="150" maxWidth="150"
         alignment="CENTER">
    <ImageView fitHeight="32" preserveRatio="true" fx:id="actionIconImageView" />
    <Label fx:id="actionDescriptionLabel" />
</fx:root>

Вы можете игнорировать FXMLQuickLoader в DashboardAction. Это служебный класс, который я создал для более легкой (и эффективной) загрузки файлов F XML.

Мотивация этого вопроса заключается в том, что мне нужно знать (т.е. добавлять прослушиватель событий), когда этот пользовательский элемент управления (DashboardAction) был нажат или, более конкретно, "действовал". Таким образом, мне нужно, чтобы пользователь мог использовать клавишу табуляции, чтобы выделить ее, клавишу ввода, чтобы «щелкнуть» по ней и т. Д. И т. Д.

Сначала я думал о том, чтобы вместо расширения VBox, расширение Button. Тогда на весь мой контроль можно было бы "воздействовать". Это полностью провалилось, однако. Как видите, Button на самом деле не способен отображать детей. По-видимому, он просто отображает их текстовое представление:

Screenshot of Button

Однако, есть ли другой элемент управления, который обладает всеми этими возможностями «щелчка»? Если так, то мой контроль мог бы просто расширить это. Однако, несмотря на это, я ищу способ правильно создать интерактивный настраиваемый элемент управления.

Спасибо,
—Jacob

...