java - FocusListener 无法在 Mac 上运行

标签 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。我的做法有问题吗?

最佳答案

这可能不是您正在寻找的答案,但我也注意到一些监听器在 mac 上不起作用(焦点监听器在 shell 上也不起作用,其他监听器在 mac 上也有问题)。这里最好的选择是尝试用文本替换按钮。并使其看起来相似。即使在 Mac 上,焦点监听器也适用于文本。因此,您的代码将如下所示:

 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.:应该有人提出有关此问题的错误。

关于java - FocusListener 无法在 Mac 上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25716610/

相关文章:

java - 如何创建一种从数组中搜索并打印整个数组框的方法?

java - Jackson 和 GSON 中 JSON 对象的稳定/术语比较

ruby - 如何在 Ruby 中使用 '~' 指定文件路径?

java - 通过单击列标题进行 SWT 表排序

java - 是否可以在 Eclipse 中自定义工具提示文本的字体?

java - 微调器未正确重绘

java - 在 Java 中 Ping 多台服务器

java - 检索 log4j 的 Activity 日志记录级别

macos - 如何在 OS X 上使用同上,在 Linux 上像 cp -a 一样工作

.net - macOS 上的 Asp.NET Core 数据库