首页 > 解决方案 > 如何防止 Escape 键关闭 JFace 对话框

问题描述

我希望能够拥有它,以便 Escape 键不会关闭弹出的 JFace 对话框。

在我准备的代码中,您可以通过运行 main 方法来查看此行为,当您按 Escape 时。

public class TestDialog extends Dialog
{

    private Label status;

    private String title;

    public TestDialog(Shell parentShell, String title)
    {
        super(parentShell);
        this.title = title;
        setShellStyle(getShellStyle() & ~SWT.CLOSE);
    }

    @Override
    protected void configureShell(Shell shell)
    {
        super.configureShell(shell);
        shell.setText(this.title);
    }

    @Override
    protected Control createDialogArea(Composite parent)
    {
        Composite composite = (Composite) super.createDialogArea(parent);
        composite.setLayout(new GridLayout(1, false));
        status = new Label(composite, SWT.NONE);
        status.setText("Hello World");
        composite.pack();
        parent.pack();
        return composite;
    }

    @Override
    protected Control createButtonBar(Composite parent)
    {
        return parent;

    }


    public static void main(String[] args) {
        TestDialog d = new TestDialog(new Shell(), "Test");
        d.open();
    }

}

标签: javaswtjface

解决方案


您可以向父Composite控件添加一个键侦听器,并在其中keyEvent匹配SWT.ESC并编写您的自定义代码,以便在按下 ESC 键时执行您想要执行的操作。现在它将阻止 JFace 对话框关闭。

@Override
    protected Control createDialogArea(final Composite parent) {
        Composite composite = (Composite) super.createDialogArea(parent);
        composite.setLayout(new GridLayout(1, false));
        status = new Label(composite, SWT.NONE);
        status.setText("Hello World");
        composite.pack();
        parent.pack();

        composite.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                String string = "";

                if (e.keyCode == SWT.ESC) {
                    string += "ESCAPE - keyCode = " + e.keyCode;
                }

                if (!string.isEmpty()) {
                    // do nothing 
                    // here I am printing in console
                    System.out.println(string);
                }
            }
        });

        return composite;
    }

推荐阅读