У меня есть следующий код:
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();
}
}
Но, похоже, это не работает. Я работаю над Eclipse IDE на компьютере Mac. Что-то не так в том, что я делаю?
Это может быть не тот ответ, который вы искали, но я тоже заметил, что некоторые слушатели не работают на Mac (слушатель фокуса не работает на оболочке, и другие слушатели тоже не работают на Mac). Лучше всего было бы попробовать заменить Button с текстом. И сделайте его похожим. Слушатель фокуса работает с текстом даже на 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();
}
}
Теперь единственное, что вам нужно сделать, это изменить поле, чтобы оно больше напоминало кнопку. Надеюсь, поможет. Удачи!
PS: Кто-то должен открыть ошибку по этой проблеме.