01: package org.uispec4j.interception;
02:
03: import junit.framework.AssertionFailedError;
04: import org.uispec4j.*;
05: import org.uispec4j.assertion.Assertion;
06: import org.uispec4j.assertion.UISpecAssert;
07: import org.uispec4j.interception.handlers.InterceptionHandler;
08: import org.uispec4j.interception.toolkit.UISpecDisplay;
09: import org.uispec4j.utils.TriggerRunner;
10:
11: import javax.swing.*;
12:
13: /**
14: * Interceptor for (usually right-click triggered) pop-up menus.<p>
15: * For instance, in the following code snippedt we right-click in the (2,4) cell of a table,
16: * then click on the "Copy" item found in the popped-up menu:
17: * <pre><code>
18: * PopupMenuInterceptor
19: * .run(table.triggerRightClick(2, 4))
20: * .getSubMenu("Copy")
21: * .click();
22: * </code></pre>
23: *
24: * @see <a href="http://www.uispec4j.org/interception.html">Intercepting windows</a>
25: */
26: public class PopupMenuInterceptor {
27:
28: /**
29: * Runs the given trigger and returns the intercepted popup menu.<p/>
30: * This method will wait for the popup to be shown, up to a time specified with
31: * {@link UISpec4J#setWindowInterceptionTimeLimit(long)}.
32: * @throws AssertionFailedError if no popup is shown before the timeout expires.
33: */
34: public static MenuItem run(final Trigger trigger) {
35: PopupHandler interceptor = new PopupHandler();
36: final UISpecDisplay display = UISpecDisplay.instance();
37: try {
38: display.add(interceptor);
39: display.setCurrentPopup(null);
40: TriggerRunner.runInSwingThread(trigger);
41: UISpecAssert.waitUntil("No popup was shown",
42: new Assertion() {
43: public void check() throws Exception {
44: if (display.getCurrentPopup() == null) {
45: throw new Exception("No popup shown");
46: }
47: ;
48: }
49: }, UISpec4J.getWindowInterceptionTimeLimit());
50: return new MenuItem(display.getCurrentPopup());
51: } finally {
52: display.remove(interceptor);
53: }
54: }
55:
56: private static class PopupHandler implements InterceptionHandler {
57: MenuItem menu;
58:
59: public void process(Window window) {
60: try {
61: this .menu = new MenuItem((JPopupMenu) window
62: .findSwingComponent(JPopupMenu.class));
63: } catch (ItemNotFoundException e) {
64: } catch (ComponentAmbiguityException e) {
65: }
66: }
67: }
68: }
|