Example usage for javax.swing SwingUtilities invokeAndWait

List of usage examples for javax.swing SwingUtilities invokeAndWait

Introduction

In this page you can find the example usage for javax.swing SwingUtilities invokeAndWait.

Prototype

public static void invokeAndWait(final Runnable doRun) throws InterruptedException, InvocationTargetException 

Source Link

Document

Causes doRun.run() to be executed synchronously on the AWT event dispatching thread.

Usage

From source file:org.opennms.poller.remote.Main.java

private void getAuthenticationInfo() throws InvocationTargetException, InterruptedException {
    if (m_uri == null) {
        throw new IllegalArgumentException("no URI specified!");
    } else if (m_uri.getScheme() == null) {
        throw new IllegalArgumentException("no URI scheme specified!");
    }/*from   www.j  a  v a  2 s .  com*/

    // Make sure that the URI is a valid value
    SpringExportSchemes.valueOf(m_uri.getScheme());

    if (SpringExportSchemes.rmi.toString().equals(m_uri.getScheme())) {
        // RMI doesn't have authentication
        return;
    }

    if (m_username == null) {
        // Display a screen where the username and password are entered
        final AuthenticationGui gui = createGui();
        SwingUtilities.invokeAndWait(new Runnable() {
            @Override
            public void run() {
                gui.createAndShowGui();
            }
        });

        /*
         * This call pauses on a {@link CountDownLatch} that is
         * signaled when the user hits the 'OK' button on the GroovyGui
         * screen.
         */
        AuthenticationBean auth = gui.getAuthenticationBean();

        m_username = auth.getUsername();
        m_password = auth.getPassword();
    }

    if (m_username != null) {
        SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
        SecurityContextHolder.getContext()
                .setAuthentication(new UsernamePasswordAuthenticationToken(m_username, m_password));
    }
}

From source file:org.pentaho.reporting.engine.classic.core.util.ComponentDrawable.java

/**
 * Returns the preferred size of the drawable. If the drawable is aspect ratio aware, these bounds should be used to
 * compute the preferred aspect ratio for this drawable.
 * <p/>/*from   w w w . ja  v  a  2  s  .  c  o m*/
 * This calls {@link java.awt.Component#getPreferredSize()} on the given component.
 *
 * @return the preferred size.
 */
public Dimension getPreferredSize() {
    if (component == null) {
        return new Dimension(0, 0);
    }
    if (SwingUtilities.isEventDispatchThread() || paintSynchronized == false) {
        preferredSizeRunnable.run();
        return preferredSizeRunnable.getRetval();
    }

    try {
        SwingUtilities.invokeAndWait(preferredSizeRunnable);
        return preferredSizeRunnable.getRetval();
    } catch (Exception e) {
        ComponentDrawable.logger.warn("Failed to compute the preferred size.");
    }
    return new Dimension(0, 0);
}

From source file:org.pentaho.reporting.engine.classic.core.util.ComponentDrawable.java

/**
 * Returns the declared size of the drawable. If the drawable is aspect ratio aware, these bounds should be used to
 * compute the declared aspect ratio for this drawable.
 * <p/>/*from w w  w  . j  a v a  2s.  com*/
 * This calls {@link java.awt.Component#getSize()} on the given component.
 *
 * @return the preferred size.
 */
public Dimension getSize() {
    if (component == null) {
        return new Dimension(0, 0);
    }
    if (SwingUtilities.isEventDispatchThread() || paintSynchronized == false) {
        sizeRunnable.run();
        return sizeRunnable.getRetval();
    }

    try {
        SwingUtilities.invokeAndWait(sizeRunnable);
        return sizeRunnable.getRetval();
    } catch (Exception e) {
        ComponentDrawable.logger.warn("Failed to compute the defined size.");
    }
    return new Dimension(0, 0);
}

From source file:org.pentaho.reporting.engine.classic.core.util.ComponentDrawable.java

/**
 * Draws the component.//ww  w . j a v  a 2s.  c o m
 *
 * @param g2
 *          the graphics device.
 * @param area
 *          the area inside which the object should be drawn.
 */
public void draw(final Graphics2D g2, final Rectangle2D area) {
    if (component == null) {
        return;
    }

    runnable.setArea(area);
    runnable.setGraphics(g2);

    if (SwingUtilities.isEventDispatchThread() || paintSynchronized == false) {
        runnable.run();
    } else {
        try {
            SwingUtilities.invokeAndWait(runnable);
        } catch (Exception e) {
            ComponentDrawable.logger.warn("Failed to redraw the component.");
        }
    }
}

From source file:org.photovault.swingui.color.Test_ColorSettingsDlgController.java

private void showFrame() {
    try {//from ww  w  .  j  a v a  2 s  .co  m
        // Always do direct component manipulation on the event thread
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                frame.pack();
                frame.show();
            }
        });
    } catch (InterruptedException ex) {
        ex.printStackTrace();
    } catch (InvocationTargetException ex) {
        ex.printStackTrace();
    }
}

From source file:org.photovault.swingui.taskscheduler.SwingWorkerTaskScheduler.java

/**
This method is called by command handler in wirker thread when a command
is executed. It asks the parent controller to fire the event in
java AWT thread.//  w  w w. j a  v  a 2 s.  c o m
@param e The command event
 */
public void commandExecuted(final CommandExecutedEvent e) {
    if (parent == null) {
        return;
    }
    log.debug("Scheduling command event " + e);
    /*
     Wait until the event has been processed in AWT event thread to avoid 
     race condition while scheduling the next event
     */
    while (true) {
        try {

            SwingUtilities.invokeAndWait(new Runnable() {

                public void run() {
                    log.debug("Firing " + e);
                    parent.fireEventGlobal(e);
                }
            });
            break;
        } catch (Exception ex) {
        }
    }
}

From source file:org.rdv.ui.ControlPanel.java

/**
 * Update the boundaries of the time sliders based on the subscribed channel
 * bounds and the event marker bounds.//from w ww . j a  v  a 2s .co m
 */
private void updateTimeBoundaries() {
    // We haven't got the metadata channel tree yet
    if (ctree == null) {
        return;
    }

    if (!SwingUtilities.isEventDispatchThread()) {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                public void run() {
                    updateTimeBoundaries();
                }
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return;
    }

    double startTime = -1;
    double endTime = -1;

    boolean hasSubscribedChannels = rbnbController.hasSubscribedChannels();

    // get the time bounds for all channels
    Iterator<?> it = ctree.iterator();
    while (it.hasNext()) {
        ChannelTree.Node node = (ChannelTree.Node) it.next();
        ChannelTree.NodeTypeEnum type = node.getType();
        if (type != ChannelTree.CHANNEL) {
            continue;
        }

        String channelName = node.getFullName();
        if (rbnbController.isSubscribed(channelName) || !hasSubscribedChannels) {
            double channelStart = node.getStart();
            double channelDuration = node.getDuration();
            double channelEnd = channelStart + channelDuration;
            if (startTime == -1 || channelStart < startTime) {
                startTime = channelStart;
            }
            if (endTime == -1 || channelEnd > endTime) {
                endTime = channelEnd;
            }
        }
    }

    if (hideEmptyTime) {
        List<TimeRange> timeRanges = new ArrayList<TimeRange>();

        double markerStartTime = -1;

        // get the time bounds for all markers
        List<EventMarker> markers = rbnbController.getMarkerManager().getMarkers();
        for (EventMarker marker : markers) {
            double markerTime = Double.parseDouble(marker.getProperty("timestamp"));
            if (startTime == -1 || markerTime < startTime) {
                startTime = markerTime;
            }
            if (endTime == -1 || markerTime > endTime) {
                endTime = markerTime;
            }

            String type = marker.getProperty("type");
            if (type.compareToIgnoreCase("start") == 0 && markerStartTime == -1) {
                markerStartTime = markerTime;
            } else if (type.compareToIgnoreCase("stop") == 0 && markerStartTime != -1) {
                timeRanges.add(new TimeRange(markerStartTime, markerTime));
                markerStartTime = -1;
            }
        }

        // add time range for ongoing event
        if (markerStartTime != -1) {
            timeRanges.add(new TimeRange(markerStartTime, Double.MAX_VALUE));
        }

        zoomTimeSlider.setTimeRanges(timeRanges);
        globalTimeSlider.setTimeRanges(timeRanges);
    }

    if (startTime == -1) {
        return;
    }

    double state = rbnbController.getState();
    double location = rbnbController.getLocation();
    if (state == Player.STATE_MONITORING && location > endTime) {
        endTime = location;
    }

    globalTimeSlider.setValues(startTime, endTime);

    // reset the selected time range if it gets stuck together
    double start = globalTimeSlider.getStart();
    double end = globalTimeSlider.getEnd();
    if (start == end) {
        if (start == globalTimeSlider.getMinimum()) {
            globalTimeSlider.setEnd(globalTimeSlider.getMaximum());
        } else if (start == globalTimeSlider.getMaximum()) {
            globalTimeSlider.setStart(globalTimeSlider.getMinimum());
        }
    }
}

From source file:org.rdv.ui.ControlPanel.java

/**
 * Called when the time changes. This updates the slider and display
 * components in the UI. It will also adjust the bounds and range if needed.
 * /*  w w  w. ja  va  2  s  .c  o  m*/
 * @param time  the new time
 */
public void postTime(final double time) {
    if (!SwingUtilities.isEventDispatchThread()) {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                public void run() {
                    postTime(time);
                }
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return;
    }

    if (time < globalTimeSlider.getMinimum()) {
        globalTimeSlider.setMinimum(time);
    } else if (time > globalTimeSlider.getMaximum()) {
        globalTimeSlider.setMaximum(time);
    }

    if (time < globalTimeSlider.getStart()) {
        globalTimeSlider.setStart(time);
    } else if (time > globalTimeSlider.getEnd()) {
        globalTimeSlider.setEnd(time);
    }

    if (!zoomTimeSlider.isValueAdjusting()) {
        zoomTimeSlider.removeTimeAdjustmentListener(this);
        zoomTimeSlider.setValue(time);
        zoomTimeSlider.addTimeAdjustmentListener(this);
    }

    if (rbnbController.getState() == Player.STATE_PLAYING && !globalTimeSlider.isTimeValid(time)) {
        double newTime = globalTimeSlider.getNextValidTime(time);
        if (newTime == -1) {
            newTime = globalTimeSlider.getActualMaximum();
        }
        zoomTimeSlider.setValue(newTime);
        if (newTime > time) {
            rbnbController.play();
        }
    }

    globalTimeSlider.setValue(time);

    locationButton.setText(DataViewer.formatDate(time));
}

From source file:org.springframework.richclient.application.ApplicationLauncher.java

/**
 * Launches the rich client application. If no startup context has so far
 * been provided, the main application context will be searched for a splash
 * screen to display. The main application context will then be searched for
 * the {@link Application} to be launched, using the bean name
 * {@link #APPLICATION_BEAN_ID}. If the application is found, it will be
 * started./* ww  w.  j av a2  s  . c  o  m*/
 *
 */
private void launchMyRichClient() {

    if (startupContext == null) {
        displaySplashScreen(rootApplicationContext);
    }

    final Application application;

    try {
        application = (Application) rootApplicationContext.getBean(APPLICATION_BEAN_ID, Application.class);
    } catch (NoSuchBeanDefinitionException e) {
        throw new IllegalArgumentException(
                "A single bean definition with id " + APPLICATION_BEAN_ID + ", of type "
                        + Application.class.getName() + " must be defined in the main application context",
                e);
    }

    try {
        // To avoid deadlocks when events fire during initialization of some swing components
        // Possible to do: in theory not a single Swing component should be created (=modified) in the launcher thread...
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                application.start();
            }
        });
    } catch (InterruptedException e) {
        logger.warn("Application start interrupted", e);
    } catch (InvocationTargetException e) {
        Throwable cause = e.getCause();
        throw new IllegalStateException("Application start thrown an exception: " + cause.getMessage(), cause);
    }

    logger.debug("Launcher thread exiting...");

}

From source file:org.springframework.richclient.application.ApplicationLauncher.java

/**
 * Searches the given bean factory for a {@link SplashScreen} defined with
 * the bean name {@link #SPLASH_SCREEN_BEAN_ID} and displays it, if found.
 *
 * @param beanFactory The bean factory that is expected to contain the
 * splash screen bean definition. Must not be null.
 *
 * @throws NullPointerException if {@code beanFactory} is null.
 * @throws BeanNotOfRequiredTypeException if the bean found under the splash
 * screen bean name is not a {@link SplashScreen}.
 *
 */// www  .j  a v  a2s  .c om
private void displaySplashScreen(BeanFactory beanFactory) {
    if (beanFactory.containsBean(SPLASH_SCREEN_BEAN_ID)) {
        this.splashScreen = (SplashScreen) beanFactory.getBean(SPLASH_SCREEN_BEAN_ID, SplashScreen.class);
        logger.debug("Displaying application splash screen...");
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                public void run() {
                    ApplicationLauncher.this.splashScreen.splash();
                }
            });
        } catch (Exception e) {
            throw new RuntimeException("EDT threading issue while showing splash screen", e);
        }
    } else {
        logger.info("No splash screen bean found to display. Continuing...");
    }
}