如何防止Escape键关闭JFace对话框

时间:2018-07-06 14:55:28

标签: java swt jface

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

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

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

}

1 个答案:

答案 0 :(得分:1)

您可以将键侦听器添加到父Composite控件,并获取keyEventSWT.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;
    }