当前位置: 首页 > 知识库问答 >
问题:

如何为JavaFx对话框分配快捷方式(组合键)

殳毅
2023-03-14
dialog.dialogPane().getButtonTypes.addAll(ButtonType.OK, ButtonType.Cancel)

如何将ESC键分配给ButtonType.Cancel?

谢了。

共有1个答案

慕河
2023-03-14

您可以使用加速器,如:

  • 使用JavaFX 2.2助记符(和加速器)

JavaFX对话框定义和使用按钮的方式有点奇怪(也有点复杂),所以添加加速器有点麻烦,但仍然是可能的。下面的代码设置了一个加速器,当按下一个组合键shortcut+F时触发按钮操作,其中快捷键将根据您的操作系统而改变(在OS X上是标记为“Command”的键)。

// Create a custom button type:
ButtonType fishingButtonType = new ButtonType( "Go fishing", ButtonBar.ButtonData.OTHER);

dialog.getDialogPane().getButtonTypes().add(fishingButtonType);

// Set an accelerator and an action for the fishing button.
Button fishingButton = (Button) dialog.getDialogPane().lookupButton(fishingButtonType);
fishingButton.addEventFilter(ActionEvent.ACTION, ae -> {
    // linkware image: http://www.iconka.com
    dialog.setGraphic(new ImageView("http://icons.iconarchive.com/icons/iconka/meow/64/cat-fish-icon.png"));
    ae.consume();  // consume the action so that the dialog does not close when the button is pressed.
});
fishingButton.sceneProperty().addListener((observable, oldValue, newScene) -> {
    if (newScene != null) {
        newScene.getAccelerators().put(
                new KeyCodeCombination(KeyCode.F, KeyCombination.SHORTCUT_DOWN),
                fishingButton::fire
        );
    }
});
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.ImageView;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.util.Pair;

import java.util.Optional;

public class LoginDialog extends Application {

    @Override 
    public void start(Stage stage) throws Exception {
        Button showDialogButton = new Button("Show Dialog");
        showDialogButton.setOnAction(event -> {
            showDialog();
        });

        StackPane layout = new StackPane(showDialogButton);
        layout.setPadding(new Insets(10));
        stage.setScene(new Scene(layout));

        stage.show();
    }

    private void showDialog() {
        // Create the custom dialog.
        Dialog<Pair<String, String>> dialog = new Dialog<>();
        dialog.setTitle("Login Dialog");
        dialog.setHeaderText("Look, a Custom Login Dialog");

        // Set the icon.
        // icon source: http://www.iconarchive.com/show/soft-scraps-icons-by-hopstarter/Lock-Lock-icon.html
        dialog.setGraphic(new ImageView("http://icons.iconarchive.com/icons/hopstarter/soft-scraps/64/Lock-Lock-icon.png"));

        // Set the button types.
        ButtonType loginButtonType = new ButtonType("Login", ButtonBar.ButtonData.OK_DONE);
        ButtonType fishingButtonType = new ButtonType( "Go fishing", ButtonBar.ButtonData.OTHER);
        dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, fishingButtonType, ButtonType.CANCEL);

        // Create the username and password labels and fields.
        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20, 150, 10, 10));

        TextField username = new TextField();
        username.setPromptText("Username");
        PasswordField password = new PasswordField();
        password.setPromptText("Password");

        grid.add(new Label("Username:"), 0, 0);
        grid.add(username, 1, 0);
        grid.add(new Label("Password:"), 0, 1);
        grid.add(password, 1, 1);

        // Enable/Disable login button depending on whether a username was entered.
        Node loginButton = dialog.getDialogPane().lookupButton(loginButtonType);
        loginButton.setDisable(true);

        // Set an accelerator and an action for the fishing button.
        Button fishingButton = (Button) dialog.getDialogPane().lookupButton(fishingButtonType);
        fishingButton.addEventFilter(ActionEvent.ACTION, ae -> {
            // linkware image: http://www.iconka.com
            dialog.setGraphic(new ImageView("http://icons.iconarchive.com/icons/iconka/meow/64/cat-fish-icon.png"));
            ae.consume();
        });
        fishingButton.sceneProperty().addListener((observable, oldValue, newScene) -> {
            if (newScene != null) {
                newScene.getAccelerators().put(
                        new KeyCodeCombination(KeyCode.F, KeyCombination.SHORTCUT_DOWN),
                        fishingButton::fire
                );
            }
        });

        // Do some validation (using the Java 8 lambda syntax).
        username.textProperty().addListener((observable, oldValue, newValue) -> {
            loginButton.setDisable(newValue.trim().isEmpty());
        });

        dialog.getDialogPane().setContent(grid);

        // Request focus on the username field by default.
        Platform.runLater(username::requestFocus);

        // Convert the result to a username-password-pair when the login button is clicked.
        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == loginButtonType) {
                return new Pair<>(username.getText(), password.getText());
            }
            return null;
        });

        Optional<Pair<String, String>> result = dialog.showAndWait();

        result.ifPresent(usernamePassword -> {
            System.out.println("Username=" + usernamePassword.getKey() + ", Password=" + usernamePassword.getValue());
        });
    }

    public static void main(String[] args) {
        launch(args);
    }
}
 类似资料:
  • target String - 从这个快捷方式启动的目标。 cwd String(可选) - 工作目录。默认值为空。 args String(可选) - 从此快捷方式启动时应用于`target'的参数。默认值为空。 description String(可选) - 快捷方式的描述。默认值为空。 icon String(可选) - 图标的路径,可以是DLL或EXE。 icon和iconIndex必须

  • 问题内容: 我需要在JavaFX中创建一个对话框。我知道我可以通过修改模式,所有者和可调整大小的属性来使舞台表现得像对话框。 但是,如何从舞台窗口中隐藏“最小化”和“最大化”按钮?典型的对话框只有“关闭”按钮。 问题答案: 在Windows 7下,在显示窗口之前初始化为StageStyle.UTILITY将创建一个仅具有关闭按钮而没有最小化或最大化按钮的窗口: 如果您需要一整套基本的JavaFX对

  • 我需要用JavaFX创建一个对话框。我知道我可以通过修改modal、owner和resizable属性使Stage的行为像一个对话框。 但是我如何从舞台窗口隐藏“最小化”和“最大化”按钮呢?典型的对话框只有“关闭”按钮。

  • 我尝试了很多我在网上看到的不同东西,但我什么都做不了。我只需要一个简单的对话框,当你点击菜单中的退出按钮并询问“您确定要退出吗?”并提供一个有效的“是的,我确定。”和“不,取消”按钮。

  • 问题内容: 我想在Swing中添加一个简单的方法,但是我想为组合中的每个项目分配值。我有以下代码 现在我想要的是,当单击组合框时,它应该相应地返回1、2和3,而不是a,b,c。有没有办法为组合框中的每个项目分配键值? 问题答案: 您可以将项目添加为对象,而不是像这样添加String: 因此,要返回键,事件的功能是: 这样做,您必须重写ItemClass类的功能以返回要在组合框中显示的字符串。 顺便