FocusListener无法在Mac上运行

时间:2014-09-08 02:15:26

标签: java macos swt

我有以下代码:

        Display display = new Display();
        Shell shell = new Shell(display);
        shell.setLayout(new GridLayout(3, true));
        shell.setText("One Potato, Two Potato");

        // Create the focus listener
        FocusListener listener = new FocusListener() {
            public void focusGained(FocusEvent event) {
                Button button = (Button) event.getSource();
                button.setText("I'm It!");
            }

            public void focusLost(FocusEvent event) {
                Button button = (Button) event.getSource();
                button.setText("Pick Me!");
            }
        };
        // Create the buttons and add the listener to each one
        for (int i = 0; i < 6; i++) {
            Button button = new Button(shell, SWT.PUSH);
            button.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
            button.setText("Pick Me!");
            button.addFocusListener(listener);
        }
        // Display the window
        shell.pack();
        shell.open();
        while (!shell.isDisposed()) {
            if (!display.readAndDispatch()) {
                display.sleep();
            }
        }

但它似乎不起作用。我正在使用Mac机上的Eclipse IDE。我正在做的事情有什么问题吗?

1 个答案:

答案 0 :(得分:1)

这可能不是你想要的答案,但是我也注意到一些听众不能在mac上工作(焦点监听器也不能在shell上工作,而其他监听器在mac上也是错误的)。这里你最好的选择是尝试用文本替换Button。并使它看起来相似。焦点监听器即使在mac上也可以在Text上工作。所以,你的代码看起来像这样:

 Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout(3, true));
    shell.setText("One Potato, Two Potato");

    // Create the focus listener
    FocusListener listener = new FocusListener() {
        public void focusGained(FocusEvent event) {
            Text text = (Text) event.getSource();
            text.setText("I'm It!");
        }

        public void focusLost(FocusEvent event) {
            Text text = (Text) event.getSource();
            text.setText("Pick Me!");
        }
    };
    // Create the buttons and add the listener to each one
    for (int i = 0; i < 6; i++) {
        Text text = new Text(shell, SWT.PUSH);
        text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
        text.setText("Pick Me!");
        text.addFocusListener(listener);
    }
    // Display the window
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }

现在你唯一需要做的就是更改字段,使它看起来更像一个按钮。希望能帮助到你。 祝你好运!

P.S。:有人应该就此问题打开一个错误。