Example usage for java.awt EventQueue invokeAndWait

List of usage examples for java.awt EventQueue invokeAndWait

Introduction

In this page you can find the example usage for java.awt EventQueue invokeAndWait.

Prototype

public static void invokeAndWait(Runnable runnable) throws InterruptedException, InvocationTargetException 

Source Link

Document

Causes runnable to have its run method called in the #isDispatchThread dispatch thread of Toolkit#getSystemEventQueue the system EventQueue .

Usage

From source file:org.zaproxy.zap.extension.ascan.ExtensionActiveScan.java

@Override
public void sessionChanged(final Session session) {
    if (EventQueue.isDispatchThread()) {
        sessionChangedEventHandler(session);

    } else {/* w  ww.jav  a2 s.  c o  m*/
        try {
            EventQueue.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    sessionChangedEventHandler(session);
                }
            });

        } catch (InterruptedException | InvocationTargetException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:fur.shadowdrake.minecraft.InstallPanel.java

public void begin(boolean first) {
    workingDir = dirBox.getText();//from  w ww.j a  v  a2 s  .c  o  m
    workingPack = (String) modpackChooser.getSelectedItem();
    parentFrame.dropAllProceedListeners();
    new Thread(() -> {
        try {
            JTabbedPane tabPane;
            tabPane = (JTabbedPane) getParent();

            if (force.isSelected()) {
                log.println("Cleaning up.");
                cleanUp(new File(workingDir));
                Manifest mf = manifest.get(workingPack);
                if (mf != null) {
                    mf.clear();
                }
            }

            Pack detected = detectPack(new File(workingDir));
            if ((detected == null) && checkDir(new File(workingDir), 2)) {
                try {
                    EventQueue.invokeAndWait(() -> {
                        JOptionPane.showMessageDialog(parentFrame,
                                "This directory contains an unknown modpack.\nChoose another directory or force reinstall.");
                    });
                } catch (InterruptedException | InvocationTargetException ex) {
                }
                completedListener.actionPerformed(new ActionEvent(this, 2, "Install"));
            } else if (detected == null) {
                try {
                    EventQueue.invokeAndWait(() -> {
                        tabPane.remove(this);
                    });
                } catch (InterruptedException | InvocationTargetException ex) {
                }

                if (first && !addonsOpenedOnce) {
                    addonsPanel = new AddonsPanel(
                            availablePacks.get(modpackChooser.getSelectedIndex()).addons.toArray(new Addon[0]));
                    tabPane.add("Addons", addonsPanel);
                    tabPane.setSelectedComponent(addonsPanel);
                    addonsOpenedOnce = true;
                    parentFrame.setAbortListener((ActionEvent e) -> {
                        tabPane.remove(addonsPanel);
                        tabPane.add("Install", this);
                        tabPane.setSelectedComponent(this);
                        parentFrame.setProceedListener((ActionEvent ev) -> {
                            begin(false);
                        });
                        parentFrame.setAbortListener((ActionEvent ev) -> {
                            tabPane.remove(this);
                            parentFrame.state = 0;
                            parentFrame.dropAllAbortListeners();
                            parentFrame.dropAllProceedListeners();
                        });
                    });
                    parentFrame.setProceedListener((ActionEvent e) -> {
                        tabPane.remove(addonsPanel);
                        boolean s[];
                        s = addonsPanel.getSelected();
                        for (int n = 0; n < s.length; n++) {
                            availablePacks.get(modpackChooser.getSelectedIndex()).addons.get(n).install = s[n];
                        }
                        begin(false);
                    });
                    return;
                }

                if (downloadPack() && downloadAddons() && doPostDownload()) {
                    log.println("Installation completed successful.");
                    log.setStatusText("Ok");
                    completedListener.actionPerformed(new ActionEvent(this, 1, "Install"));
                } else {
                    log.println("Installation completed with errors.");
                    log.setStatusText("Error");
                    EventQueue.invokeLater(() -> {
                        JOptionPane.showMessageDialog(parentFrame, "Installation failed");
                    });
                    completedListener.actionPerformed(new ActionEvent(this, 0, "Install"));
                }
            } else if (detected.name.equals(modpackChooser.getSelectedItem())) {
                if (!isInstalled(detected)) {
                    try {
                        Gson gson = new GsonBuilder().create();
                        tabPane.remove(this);
                        packList.add(detected);

                        String latestVersion = ftpClient.getLatestVersion(detected.name);
                        if (!latestVersion.equals(detected.version)) {
                            updatePack(detected);
                        }

                        try (FileWriter fw = new FileWriter(
                                new File(config.getInstallDir(), "modpacks.json"))) {
                            gson.toJson(packList, fw);
                        }
                        log.println("Installation completed successful.");
                        completedListener.actionPerformed(new ActionEvent(this, 1, "Install"));
                    } catch (IOException ex1) {
                        log.println("Installation failed.");
                        Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, null, ex1);
                    }
                } else {
                    try {
                        EventQueue.invokeAndWait(() -> {
                            tabPane.remove(this);
                        });
                    } catch (InterruptedException | InvocationTargetException ex) {
                    }
                    if (downloadAddons()) {
                        log.println("Installation completed successful.");
                        log.setStatusText("Ok");
                        log.reset();
                        completedListener.actionPerformed(new ActionEvent(this, 1, "Install"));
                    } else {
                        log.println("Installation failed.");
                        EventQueue.invokeLater(() -> {
                            JOptionPane.showMessageDialog(parentFrame, "Installation failed");
                        });
                    }
                }
            } else {
                try {
                    EventQueue.invokeAndWait(() -> {
                        JOptionPane.showMessageDialog(parentFrame, "This directory contains modpack "
                                + detected.name + ".\nSelect the correct pack or force reinstall.");
                    });
                } catch (InterruptedException | InvocationTargetException ex) {
                }
                completedListener.actionPerformed(new ActionEvent(this, 2, "Install"));
            }
            writeFiles();
        } catch (NetworkException ex) {
            Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, null, ex);
            JOptionPane.showMessageDialog(parentFrame, ex.getMessage(), "Network error",
                    JOptionPane.ERROR_MESSAGE);
            ftpClient.close();
            log.println(
                    "Timeout. Previous command wasn't received by the server. This is a network error. Please try again later.");
            log.setStatusText("Error");
        }
    }, "Installer").start();
}

From source file:com.t3.client.TabletopTool.java

public static BufferedImage takeMapScreenShot(final PlayerView view) {
    final ZoneRenderer renderer = clientFrame.getCurrentZoneRenderer();
    if (renderer == null) {
        return null;
    }/*from w ww. j a v  a  2s .  c  o m*/

    Dimension size = renderer.getSize();
    if (size.width == 0 || size.height == 0) {
        return null;
    }

    BufferedImage image = new BufferedImage(size.width, size.height, Transparency.OPAQUE);
    final Graphics2D g = image.createGraphics();
    g.setClip(0, 0, size.width, size.height);

    // Have to do this on the EDT so that there aren't any odd side effects
    // of rendering
    // using a renderer that's on screen
    if (!EventQueue.isDispatchThread()) {
        try {
            EventQueue.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    renderer.renderZone(g, view);
                }
            });
        } catch (InterruptedException ie) {
            TabletopTool.showError("While creating snapshot", ie);
        } catch (InvocationTargetException ite) {
            TabletopTool.showError("While creating snapshot", ite);
        }
    } else {
        renderer.renderZone(g, view);
    }

    g.dispose();

    return image;
}

From source file:net.rptools.maptool.client.MapTool.java

public static BufferedImage takeMapScreenShot(final PlayerView view) {
    final ZoneRenderer renderer = clientFrame.getCurrentZoneRenderer();
    if (renderer == null) {
        return null;
    }//from   w  w  w . j a  v a2 s.  c  o m

    Dimension size = renderer.getSize();
    if (size.width == 0 || size.height == 0) {
        return null;
    }

    BufferedImage image = new BufferedImage(size.width, size.height, Transparency.OPAQUE);
    final Graphics2D g = image.createGraphics();
    g.setClip(0, 0, size.width, size.height);

    // Have to do this on the EDT so that there aren't any odd side effects
    // of rendering
    // using a renderer that's on screen
    if (!EventQueue.isDispatchThread()) {
        try {
            EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    renderer.renderZone(g, view);
                }
            });
        } catch (InterruptedException ie) {
            MapTool.showError("While creating snapshot", ie);
        } catch (InvocationTargetException ite) {
            MapTool.showError("While creating snapshot", ite);
        }
    } else {
        renderer.renderZone(g, view);
    }

    g.dispose();

    return image;
}

From source file:de.huxhorn.lilith.Lilith.java

private static void hideSplashScreen(final SplashScreen splashScreen)
        throws InvocationTargetException, InterruptedException {
    if (splashScreen != null) {
        EventQueue.invokeAndWait(() -> splashScreen.setVisible(false));
    }/*from w  w  w  . ja va2s  . c o m*/
}

From source file:org.parosproxy.paros.extension.history.ExtensionHistory.java

@Override
public void sessionAboutToChange(final Session session) {
    if (getView() == null || EventQueue.isDispatchThread()) {
        historyTableModel.clear();//from   www . j  a v  a 2s  .  com
        historyIdToRef.clear();

        if (getView() != null) {
            getView().getRequestPanel().clearView(true);
            getView().getResponsePanel().clearView(false);
        }
    } else {
        try {
            EventQueue.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    sessionAboutToChange(session);
                }
            });
        } catch (Exception e) {
            // ZAP: Added logging.
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:de.huxhorn.lilith.Lilith.java

public static void startUI(final String appTitle) {
    final Logger logger = LoggerFactory.getLogger(Lilith.class);

    UIManager.installLookAndFeel("JGoodies Windows", "com.jgoodies.looks.windows.WindowsLookAndFeel");
    UIManager.installLookAndFeel("JGoodies Plastic", "com.jgoodies.looks.plastic.PlasticLookAndFeel");
    UIManager.installLookAndFeel("JGoodies Plastic 3D", "com.jgoodies.looks.plastic.Plastic3DLookAndFeel");
    UIManager.installLookAndFeel("JGoodies Plastic XP", "com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
    // Substance requires 1.6
    UIManager.installLookAndFeel("Substance Dark - Twilight",
            "org.pushingpixels.substance.api.skin.SubstanceTwilightLookAndFeel");
    UIManager.installLookAndFeel("Substance Light - Business",
            "org.pushingpixels.substance.api.skin.SubstanceBusinessLookAndFeel");

    //UIManager.installLookAndFeel("Napkin", "net.sourceforge.napkinlaf.NapkinLookAndFeel");

    // look & feels must be installed before creation of ApplicationPreferences.
    ApplicationPreferences applicationPreferences = new ApplicationPreferences();

    // init look & feel
    String lookAndFeelName = applicationPreferences.getLookAndFeel();
    String systemLookAndFeelClassName = UIManager.getSystemLookAndFeelClassName();
    String lookAndFeelClassName = systemLookAndFeelClassName;
    if (lookAndFeelName != null) {
        for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
            if (lookAndFeelName.equals(info.getName())) {
                lookAndFeelClassName = info.getClassName();
                break;
            }//from   w  w  w.  j a  va2s .c  o m
        }
    }

    try {
        UIManager.setLookAndFeel(lookAndFeelClassName);
    } catch (Throwable e) {
        if (logger.isWarnEnabled())
            logger.warn("Failed to set look&feel to '{}'.", lookAndFeelClassName, e);
        if (!lookAndFeelClassName.equals(systemLookAndFeelClassName)) {
            try {
                UIManager.setLookAndFeel(systemLookAndFeelClassName);
                lookAndFeelClassName = systemLookAndFeelClassName;
            } catch (Throwable e2) {
                if (logger.isWarnEnabled())
                    logger.warn("Failed to set look&feel to '{}'.", systemLookAndFeelClassName, e);
                lookAndFeelClassName = null;
            }
        }
    }

    boolean screenMenuBar = false;
    if (systemLookAndFeelClassName.equals(lookAndFeelClassName)) {
        // This instance of application is only used to query some info. The real one is in MainFrame.
        Application application = new DefaultApplication();

        if (application.isMac()) {
            // Use Apple Aqua L&F screen menu bar if available; set property before any frames created
            try {
                System.setProperty(APPLE_SCREEN_MENU_BAR_SYSTEM_PROPERTY, "true");
                screenMenuBar = true;
            } catch (Throwable e) {
                try {
                    screenMenuBar = Boolean
                            .parseBoolean(System.getProperty(APPLE_SCREEN_MENU_BAR_SYSTEM_PROPERTY, "false"));
                } catch (Throwable e2) {
                    // ignore
                }
            }
        }
    }

    applicationPreferences.setUsingScreenMenuBar(screenMenuBar);

    boolean splashScreenDisabled = applicationPreferences.isSplashScreenDisabled();
    try {
        SplashScreen splashScreen = null;
        if (!splashScreenDisabled) {
            CreateSplashRunnable createRunnable = new CreateSplashRunnable(appTitle);
            EventQueue.invokeAndWait(createRunnable);
            splashScreen = createRunnable.getSplashScreen();
            Thread.sleep(500); // so the splash gets the chance to get displayed :(
            updateSplashStatus(splashScreen, "Initialized application preferences...");
        }

        File startupApplicationPath = applicationPreferences.getStartupApplicationPath();
        if (startupApplicationPath.mkdirs()) {
            if (logger.isDebugEnabled())
                logger.debug("Created '{}'.", startupApplicationPath.getAbsolutePath());
        }

        // System.err redirection
        {
            File errorLog = new File(startupApplicationPath, "errors.log");
            boolean freshFile = false;
            if (!errorLog.isFile()) {
                freshFile = true;
            }
            try {
                FileOutputStream fos = new FileOutputStream(errorLog, true);
                PrintStream ps = new PrintStream(fos, true, StandardCharsets.UTF_8.name());
                if (!freshFile) {
                    ps.println("----------------------------------------");
                }
                String currentDateTime = DateTimeFormatters.DATETIME_IN_SYSTEM_ZONE_SPACE.format(Instant.now());
                ps.println("Started " + APP_NAME + " V" + APP_VERSION + " at " + currentDateTime);
                System.setErr(ps);
                if (logger.isInfoEnabled())
                    logger.info("Writing System.err to '{}'.", errorLog.getAbsolutePath());
            } catch (FileNotFoundException | UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        File prevPathFile = new File(startupApplicationPath,
                ApplicationPreferences.PREVIOUS_APPLICATION_PATH_FILENAME);
        if (prevPathFile.isFile()) {
            updateSplashStatus(splashScreen, "Moving application path content...");
            moveApplicationPathContent(prevPathFile, startupApplicationPath);
        }
        if (!applicationPreferences.isLicensed()) {
            hideSplashScreen(splashScreen);

            LicenseAgreementDialog licenseDialog = new LicenseAgreementDialog();
            licenseDialog.setAlwaysOnTop(true);
            licenseDialog.setAutoRequestFocus(true);
            Windows.showWindow(licenseDialog, null, true);
            if (licenseDialog.isLicenseAgreed()) {
                applicationPreferences.setLicensed(true);
            } else {
                if (logger.isWarnEnabled())
                    logger.warn("Didn't accept license! Exiting...");
                System.exit(-1);
            }
        }

        updateSplashStatus(splashScreen, "Creating main window...");
        CreateMainFrameRunnable createMain = new CreateMainFrameRunnable(applicationPreferences, splashScreen,
                appTitle);
        EventQueue.invokeAndWait(createMain);
        final MainFrame frame = createMain.getMainFrame();
        if (logger.isDebugEnabled())
            logger.debug("After show...");
        updateSplashStatus(splashScreen, "Initializing application...");
        EventQueue.invokeAndWait(frame::startUp);
        hideSplashScreen(splashScreen);
        mainFrame = frame;

    } catch (InterruptedException ex) {
        if (logger.isInfoEnabled())
            logger.info("Interrupted...", ex);
        IOUtilities.interruptIfNecessary(ex);
    } catch (InvocationTargetException ex) {
        if (logger.isWarnEnabled())
            logger.warn("InvocationTargetException...", ex);
        if (logger.isWarnEnabled())
            logger.warn("Target-Exception: ", ex.getTargetException());

    }
}

From source file:org.zaproxy.zap.extension.plugnhack.ExtensionPlugNHack.java

@Override
public void sessionChanged(final Session session) {
    if (EventQueue.isDispatchThread()) {
        sessionChangedEventHandler(session);

    } else {/* w w w . j  a  v a 2s.  c o m*/
        try {
            EventQueue.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    sessionChangedEventHandler(session);
                }
            });
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:org.parosproxy.paros.extension.ExtensionLoader.java

private void hookAllExtension(double progressFactor) {
    final double factorPerc = progressFactor / getExtensionCount();

    for (int i = 0; i < getExtensionCount(); i++) {
        final Extension ext = getExtension(i);
        try {/*from ww  w . j  a va2  s  . c  om*/
            logger.info("Initializing " + ext.getDescription());
            final ExtensionHook extHook = new ExtensionHook(model, view);
            ext.hook(extHook);
            extensionHooks.put(ext, extHook);

            hookContextDataFactories(ext, extHook);
            hookApiImplementors(ext, extHook);
            hookHttpSenderListeners(ext, extHook);

            if (view != null) {
                EventQueue.invokeAndWait(new Runnable() {

                    @Override
                    public void run() {
                        // no need to hook view if no GUI
                        hookView(ext, view, extHook);
                        hookMenu(view, extHook);
                        view.addSplashScreenLoadingCompletion(factorPerc);
                    }
                });
            }

            hookOptions(extHook);
            ext.optionsLoaded();

        } catch (Throwable e) {
            // Catch Errors thrown by out of date extensions as well as Exceptions
            logExtensionInitError(ext, e);
        }
    }
    // Call postInit for all extensions after they have all been initialized
    for (int i = 0; i < getExtensionCount(); i++) {
        Extension extension = getExtension(i);
        try {
            extension.postInit();
        } catch (Throwable e) {
            // Catch Errors thrown by out of date extensions as well as Exceptions
            logExtensionInitError(extension, e);
        }
    }

    if (view != null) {
        view.getMainFrame().getMainMenuBar().validate();
        view.getMainFrame().validate();
    }
}

From source file:ca.uhn.hl7v2.testpanel.ui.v2tree.Hl7V2MessageTree.java

private static TreeNodeBase insertOrReplaceWithExisting(final TreeNodeBase theTreeParent, final int theIndex,
        final TreeNodeBase theNewNode) throws InterruptedException, InvocationTargetException {

    if (theTreeParent.getChildCount() <= theIndex) {
        EventQueue.invokeAndWait(new Runnable() {
            public void run() {
                theTreeParent.insert(theNewNode, theIndex);
            }//from  www . j a  va2s  . c o m
        });
        return theNewNode;
    }

    // if (theTreeParent.getChildAt(theIndex).equals(theNewNode)) {
    // return (TreeNodeBase) theTreeParent.getChildAt(theIndex);
    // }

    while (theTreeParent.getChildCount() > (theIndex)) {
        TreeNode node = theTreeParent.getChildAt(theIndex);
        if (node instanceof IDestroyable) {
            ((IDestroyable) node).destroy();
        }

        EventQueue.invokeAndWait(new Runnable() {
            public void run() {
                theTreeParent.remove(theIndex);
            }
        });
        if (theTreeParent.getChildCount() > (theIndex)
                && theTreeParent.getChildAt(theIndex).equals(theNewNode)) {
            return (TreeNodeBase) theTreeParent.getChildAt(theIndex);
        }
    }

    EventQueue.invokeAndWait(new Runnable() {
        public void run() {
            theTreeParent.insert(theNewNode, theIndex);
        }
    });

    return theNewNode;
}