我有以下代码:
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/