在用SWTBot获取元素右键菜单的时候,往往因为时间问题、或者是SWTBot的限制问题,抛出菜单获取不到、或者XXX dispose等问题。
public static void clickContextMenu(final AbstractSWTBot<?> bot,
final String... texts) {
// show
final MenuItem menuItem = UIThreadRunnable
.syncExec(new WidgetResult<MenuItem>() {
public MenuItem run() {
MenuItem menuItem = null;
Control control = (Control) bot.widget;
Menu menu = control.getMenu();
for (String text : texts) {
Matcher<?> matcher = allOf(
instanceOf(MenuItem.class),
withMnemonic(text));
menuItem = show(menu, matcher);
if (menuItem != null) {
menu = menuItem.getMenu();
} else {
hide(menu);
break;
}
}
return menuItem;
}
});
if (menuItem == null) {
throw new WidgetNotFoundException("Could not find menu: "
+ Arrays.asList(texts));
}
// click
click(menuItem);
// hide
UIThreadRunnable.syncExec(new VoidResult() {
public void run() {
hide(menuItem.getParent());
}
});
}
右键菜单点击:
private static void click(final MenuItem menuItem) {
final Event event = new Event();
event.time = (int) System.currentTimeMillis();
event.widget = menuItem;
event.display = menuItem.getDisplay();
event.type = SWT.Selection;
UIThreadRunnable.asyncExec(menuItem.getDisplay(), new VoidResult() {
public void run() {
menuItem.notifyListeners(SWT.Selection, event);
}
});
}
隐藏右键菜单:
private static void hide(final Menu menu) {
menu.notifyListeners(SWT.Hide, new Event());
if (menu.getParentMenu() != null) {
hide(menu.getParentMenu());
}
}
SWTBot在使用的时候,很多问题都有因为等待时间造成的。以上这种方法,利用另外一个UI线程,打开右键菜单 --> 点击 --> 隐藏右键菜单。