Java Code Examples for java.awt.EventQueue#invokeAndWait()

The following examples show how to use java.awt.EventQueue#invokeAndWait() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebSocketPanel.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
@Override
public void onStateChange(final State state, WebSocketProxy proxy) {
    final WebSocketChannelDTO channel = proxy.getDTO();

    try {
        if (EventQueue.isDispatchThread()) {
            updateChannelsState(state, channel);
        } else {
            EventQueue.invokeAndWait(
                    new Runnable() {
                        @Override
                        public void run() {
                            updateChannelsState(state, channel);
                        }
                    });
        }
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}
 
Example 2
Source File: TimableEventQueueTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testDispatchEvent() throws Exception {
    class Slow implements Runnable {
        private int ok;
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Exceptions.printStackTrace(ex);
            }
            ok++;
        }
    }
    Slow slow = new Slow();
    
    EventQueue.invokeAndWait(slow);
    EventQueue.invokeAndWait(slow);
    TimableEventQueue.RP.shutdown();
    TimableEventQueue.RP.awaitTermination(3, TimeUnit.SECONDS);
    
    assertEquals("called", 2, slow.ok);

    if (!log.toString().contains("too much time in AWT thread")) {
        fail("There shall be warning about too much time in AWT thread:\n" + log);
    }
}
 
Example 3
Source File: TransformedPaintTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws
    InterruptedException, InvocationTargetException
{
    boolean show = (args.length > 0 && "-show".equals(args[0]));

    final TransformedPaintTest t = new TransformedPaintTest();
    if (show) {
        EventQueue.invokeAndWait(new Runnable() {
            public void run() {
                showFrame(t);
            }
        });
    } else {
        t.runTest();
    }
}
 
Example 4
Source File: ExtensionWappalyzer.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
@Override
public void sessionChanged(final Session session) {
    if (getView() == null) {
        return;
    }

    if (EventQueue.isDispatchThread()) {
        sessionChangedEventHandler(session);

    } else {
        try {
            EventQueue.invokeAndWait(
                    new Runnable() {
                        @Override
                        public void run() {
                            sessionChangedEventHandler(session);
                        }
                    });
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
 
Example 5
Source File: TextViewOOM.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    /* Create and display the form */
    EventQueue.invokeAndWait(TextViewOOM::createAndShowGUI);
    for (int i = 0; i < 10; i++) {
        System.gc();
        Thread.sleep(1000);
    }
    long mem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    System.err.println("Memory before creating the text: "+mem);
    final StringBuilder sb = new StringBuilder(N * STRING.length());
    for (int i = 0; i < N; i++) {
        sb.append(STRING);
    }
    for (int i = 0; i < 10; i++) {
        System.gc();
        Thread.sleep(1000);
    }
    mem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    System.err.println("Memory after  creating the text: "+mem);

    EventQueue.invokeAndWait(() -> {
        ta.setText(sb.toString());
        for (int i = 0; i < 10; i++) {
            System.gc();
            try {Thread.sleep(200);} catch (InterruptedException iex) {}
        }
        long mem1 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        System.err.println("Memory after  setting the text: " + mem1);
    });
    for (int i = 0; i < 10; i++) {
        System.gc();
        Thread.sleep(1000);
    }
    mem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    System.err.println("Final memory  after everything: " + mem);
    EventQueue.invokeAndWait(frame::dispose);
}
 
Example 6
Source File: ToolbarWithOverflowTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testInitOutsideOfEDT() throws Exception {
    class MyToolbar extends ToolbarWithOverflow implements Runnable {

        @Override
        protected void setUI(ComponentUI newUI) {
            assertTrue("Can only be called in EDT", EventQueue.isDispatchThread());
            super.setUI(newUI);
        }

        @Override
        public void setUI(ToolBarUI ui) {
            assertTrue("Can only be called in EDT", EventQueue.isDispatchThread());
            super.setUI(ui);
        }

        private void assertUI() throws Exception {
            EventQueue.invokeAndWait(this);
        }

        @Override
        public void run() {
            assertNotNull("UI delegate is specified", getUI());
        }
    }

    assertFalse("We are not in EDT", EventQueue.isDispatchThread());
    MyToolbar mt = new MyToolbar();
    assertNotNull("Instance created", mt);

    mt.assertUI();
}
 
Example 7
Source File: NpeOnCloseTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args)
{
    Frame frame1 = new Frame("frame 1");
    frame1.setBounds(0, 0, 100, 100);
    frame1.setVisible(true);
    Util.waitForIdle(null);

    Frame frame2 = new Frame("frame 2");
    frame2.setBounds(150, 0, 100, 100);
    frame2.setVisible(true);
    Util.waitForIdle(null);

    Frame frame3 = new Frame("frame 3");
    final Dialog dialog = new Dialog(frame3, "dialog", true);
    dialog.setBounds(300, 0, 100, 100);
    EventQueue.invokeLater(new Runnable() {
            public void run() {
                dialog.setVisible(true);
            }
        });
    try {
        EventQueue.invokeAndWait(new Runnable() { public void run() {} });
        Util.waitForIdle(null);
        EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    dialog.dispose();
                }
            });
    }
    catch (InterruptedException ie) {
        throw new RuntimeException(ie);
    }
    catch (InvocationTargetException ite) {
        throw new RuntimeException(ite);
    }

    frame1.dispose();
    frame2.dispose();
    frame3.dispose();
}
 
Example 8
Source File: ExecutableInputMethodManager.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void run() {
    // If there are no multiple input methods to choose from, wait forever
    while (!hasMultipleInputMethods()) {
        try {
            synchronized (this) {
                wait();
            }
        } catch (InterruptedException e) {
        }
    }

    // Loop for processing input method change requests
    while (true) {
        waitForChangeRequest();
        initializeInputMethodLocatorList();
        try {
            if (requestComponent != null) {
                showInputMethodMenuOnRequesterEDT(requestComponent);
            } else {
                // show the popup menu within the event thread
                EventQueue.invokeAndWait(new Runnable() {
                    public void run() {
                        showInputMethodMenu();
                    }
                });
            }
        } catch (InterruptedException ie) {
        } catch (InvocationTargetException ite) {
            // should we do anything under these exceptions?
        }
    }
}
 
Example 9
Source File: RequestFocusAndHideTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException, java.lang.reflect.InvocationTargetException
{
    final Frame frame = new Frame("the test");
    frame.setLayout(new FlowLayout());
    final Button btn1 = new Button("button 1");
    frame.add(btn1);
    frame.add(new Button("button 2"));
    frame.add(new Button("button 3"));
    frame.pack();
    frame.setVisible(true);

    Robot r = Util.createRobot();
    Util.waitForIdle(r);
    Util.clickOnComp(btn1, r);
    Util.waitForIdle(r);
    KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
    if (kfm.getFocusOwner() != btn1) {
        throw new RuntimeException("test error: can not set focus on " + btn1 + ".");
    }

    EventQueue.invokeAndWait(new Runnable() {
            public void run() {
                final int n_comps = frame.getComponentCount();
                for (int i = 0; i < n_comps; ++i) {
                    frame.getComponent(i).setVisible(false);
                }
            }
        });
    Util.waitForIdle(r);
    final Component focus_owner = kfm.getFocusOwner();

    if (focus_owner != null && !focus_owner.isVisible()) {
        throw new RuntimeException("we have invisible focus owner");
    }
    System.out.println("test passed");
    frame.dispose();
}
 
Example 10
Source File: TemplateWizardTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@RandomlyFails // NB-Core-Build #1639 (NPE in SunGraphics2D.addRenderingHints from HtmlLabelUI.calcPreferredSize);
               // NB-Core-Build #1644 (CCE: javax.swing.KeyStroke from TreeMap.compare in JTextField.<init>)
public void testNextOnIterImpl () throws Exception {
    EventQueue.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            doNextOnIterImpl (false);
        }
    });
}
 
Example 11
Source File: TextViewOOM.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    /* Create and display the form */
    EventQueue.invokeAndWait(TextViewOOM::createAndShowGUI);
    for (int i = 0; i < 10; i++) {
        System.gc();
        Thread.sleep(1000);
    }
    long mem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    System.err.println("Memory before creating the text: "+mem);
    final StringBuilder sb = new StringBuilder(N * STRING.length());
    for (int i = 0; i < N; i++) {
        sb.append(STRING);
    }
    for (int i = 0; i < 10; i++) {
        System.gc();
        Thread.sleep(1000);
    }
    mem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    System.err.println("Memory after  creating the text: "+mem);

    EventQueue.invokeAndWait(() -> {
        ta.setText(sb.toString());
        for (int i = 0; i < 10; i++) {
            System.gc();
            try {Thread.sleep(200);} catch (InterruptedException iex) {}
        }
        long mem1 = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
        System.err.println("Memory after  setting the text: " + mem1);
    });
    for (int i = 0; i < 10; i++) {
        System.gc();
        Thread.sleep(1000);
    }
    mem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
    System.err.println("Final memory  after everything: " + mem);
    EventQueue.invokeAndWait(frame::dispose);
}
 
Example 12
Source File: ScreenMenuMemoryLeakTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws InvocationTargetException, InterruptedException {
    EventQueue.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            System.setProperty("apple.laf.useScreenMenuBar", "true");
            showUI();
        }
    });

    EventQueue.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            removeMenuItemFromMenu();
        }
    });
    System.gc();
    System.runFinalization();
    JMenuItem menuItem = sMenuItem.get();
    EventQueue.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            sFrame.dispose();
        }
    });
    if (menuItem != null) {
        throw new RuntimeException("The menu item should have been GC-ed");
    }
}
 
Example 13
Source File: RequestFocusAndHideTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws InterruptedException, java.lang.reflect.InvocationTargetException
{
    final Frame frame = new Frame("the test");
    frame.setLayout(new FlowLayout());
    final Button btn1 = new Button("button 1");
    frame.add(btn1);
    frame.add(new Button("button 2"));
    frame.add(new Button("button 3"));
    frame.pack();
    frame.setVisible(true);

    Robot r = Util.createRobot();
    Util.waitForIdle(r);
    Util.clickOnComp(btn1, r);
    Util.waitForIdle(r);
    KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
    if (kfm.getFocusOwner() != btn1) {
        throw new RuntimeException("test error: can not set focus on " + btn1 + ".");
    }

    EventQueue.invokeAndWait(new Runnable() {
            public void run() {
                final int n_comps = frame.getComponentCount();
                for (int i = 0; i < n_comps; ++i) {
                    frame.getComponent(i).setVisible(false);
                }
            }
        });
    Util.waitForIdle(r);
    final Component focus_owner = kfm.getFocusOwner();

    if (focus_owner != null && !focus_owner.isVisible()) {
        throw new RuntimeException("we have invisible focus owner");
    }
    System.out.println("test passed");
    frame.dispose();
}
 
Example 14
Source File: NotificationPlugin.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Notify client that a user has come online.
 *
 * @param jid the jid of the user that has come online.
 * @param presence Presence of the online user.
 */
private void notifyUserOnline(final BareJid jid, final Presence presence) {
 try {
	 EventQueue.invokeAndWait( () -> {
            SparkToaster toaster = new SparkToaster();
            toaster.setDisplayTime(preferences.getNotificationsDisplayTime());
            toaster.setBorder(BorderFactory.createBevelBorder(0));
            toaster.setCustomAction(new ChatAction(jid));
            NotificationAlertUI alertUI = new NotificationAlertUI(jid, true, presence);

            toaster.setToasterHeight((int)alertUI.getPreferredSize().getHeight() + 40);

            int width = (int)alertUI.getPreferredSize().getWidth() + 40;
            if (width < 300) {
                width = 300;
            }

            toaster.setToasterWidth(width);

           toaster.showToaster(alertUI.topLabel.getText(), alertUI);
           toaster.setTitleAlert(new Font("Dialog", Font.BOLD, 13), presence);
        } );
 }
 catch(Exception ex) {
	Log.error(ex); 
 }
}
 
Example 15
Source File: ScreenMenuMemoryLeakTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws InvocationTargetException, InterruptedException {
    EventQueue.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            System.setProperty("apple.laf.useScreenMenuBar", "true");
            showUI();
        }
    });

    EventQueue.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            removeMenuItemFromMenu();
        }
    });
    System.gc();
    System.runFinalization();
    JMenuItem menuItem = sMenuItem.get();
    EventQueue.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            sFrame.dispose();
        }
    });
    if (menuItem != null) {
        throw new RuntimeException("The menu item should have been GC-ed");
    }
}
 
Example 16
Source File: NavigationTreeViewTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testStructureFullOfFormFiles() throws Exception {
    if ((
        Utilities.getOperatingSystem() & 
        (Utilities.OS_SOLARIS | Utilities.OS_SUNOS)
    ) != 0) {
        LOG.log(Level.CONFIG, "Giving up, this test fails too randomly on Solaris");
        return;
    }
    
    Children ch = new Children.Array();
    Node root = new AbstractNode(ch);
    root.setName(getName());

    ch.add(nodeWith("A", "-A", "-B", "B"));
    ch.add(nodeWith("X", "Y", "Z"));

    final Node first = ch.getNodes()[0];

    LOG.log(Level.INFO, "Nodes are ready: {0}", root);
    final ExplorerManager em = testWindow.getExplorerManager();
    em.setRootContext(root);
    LOG.info("setRootContext done");
    em.setSelectedNodes(new Node[] { first });
    LOG.log(Level.INFO, "setSelectedNodes to {0}", first);
    LOG.log(Level.INFO, "Verify setSelectedNodes: {0}", Arrays.asList(em.getSelectedNodes()));

    EventQueue.invokeAndWait(new Runnable() {
        @Override
        public void run() {
            TreePath path = treeView.tree.getSelectionPath();
            LOG.log(Level.INFO, "getSelectionPath {0}", path);
            LOG.log(Level.INFO, "getSelectedNodes {0}", Arrays.toString(em.getSelectedNodes()));
            assertNotNull("Something is selected", path);
            Node node = Visualizer.findNode(path.getLastPathComponent());
            assertEquals("It is the first node", first, node);
        }
    });
    
    sendAction("expand");
    sendAction("selectNext");

    assertEquals("Explored context is N0", first, em.getExploredContext());
    assertEquals("Selected node is A", 1, em.getSelectedNodes().length);
    assertEquals("Selected node is A", "A", em.getSelectedNodes()[0].getName());

    sendAction(enter);

    Keys keys = (Keys)first.getChildren();
    assertEquals("One invocation", 1, keys.actionPerformed);
    assertFalse("No write access", keys.writeAccess);
    assertFalse("No read access", keys.readAccess);
}
 
Example 17
Source File: ToolbarPoolDeadlockTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testWaitsForToolbars () throws Exception {
    assertFalse("Not in AWT thread", EventQueue.isDispatchThread());
    class Block implements Runnable {
        int cnt;
        Toolbar[] myTlbs;
        public void run() {
            if (cnt++ > 0) {
                return;
            }
            init();
        }
        private synchronized void init() {
            try {
                notifyAll();
                wait();
            } catch (InterruptedException ex) {
                Exceptions.printStackTrace(ex);
            }

            ToolbarPool.getDefault().waitFinished();
            myTlbs = ToolbarPool.getDefault().getToolbars ();
        }

        public synchronized void waitAWTBlocked() throws InterruptedException {
            EventQueue.invokeLater(this);
            wait();
        }

        public void finish() throws Exception {
            synchronized (this) {
                notifyAll();
            }
            Thread.sleep(200);
            EventQueue.invokeAndWait(this);
            assertNotNull("My toolbars has been obtained", myTlbs);
        }
    }
    Block block = new Block();
    block.waitAWTBlocked();

    FileObject tlb = FileUtil.createFolder (toolbars, "tlbx");
    DataFolder f = DataFolder.findFolder (tlb);
    InstanceDataObject.create (f, "test1", JLabel.class);

    block.finish();

    assertEquals ("One", 1, block.myTlbs.length);
    assertEquals ("By default there is the one", "tlbx", block.myTlbs[0].getName ());
    assertLabels ("One subcomponent", 1, block.myTlbs[0]);
}
 
Example 18
Source File: TrayIconMouseTest.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
TrayIconMouseTest() throws Exception {
    robot = new ExtendedRobot();
    EventQueue.invokeAndWait(this::initializeGUI);
}
 
Example 19
Source File: CreateImage.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(final String[] args) throws Exception {
    EventQueue.invokeAndWait(CreateImage::test);
}
 
Example 20
Source File: bug8003830.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventQueue.invokeAndWait(new bug8003830());
}