Example usage for javax.swing SwingUtilities invokeLater

List of usage examples for javax.swing SwingUtilities invokeLater

Introduction

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

Prototype

public static void invokeLater(Runnable doRun) 

Source Link

Document

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

Usage

From source file:ca.sqlpower.wabit.swingui.enterprise.UserPanel.java

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                WabitWorkspace p = new WabitWorkspace();
                p.setUUID("system");

                // Add data sources to workspace
                DataSourceCollection<SPDataSource> plini = new PlDotIni();
                plini.read(new File(System.getProperty("user.home"), "pl.ini"));
                List<SPDataSource> dataSources = plini.getConnections();
                for (int i = 0; i < 10 && i < dataSources.size(); i++) {
                    p.addDataSource(new WabitDataSource(dataSources.get(i)));
                }/*from   w  w  w  .  j av  a 2  s  .  c om*/

                // Add layouts to workspace
                Report layout = new Report("Example Layout");
                p.addReport(layout);
                Page page = layout.getPage();
                page.addContentBox(new ContentBox());
                page.addGuide(new Guide(Axis.HORIZONTAL, 123));
                page.addContentBox(new ContentBox());

                // dd a report task
                ReportTask task = new ReportTask();
                task.setReport(layout);
                p.addReportTask(task);

                User user = new User("admin", "admin");
                user.setParent(p);
                Group group = new Group("Admins");
                group.setParent(p);
                group.addMember(new GroupMember(user));

                Group group2 = new Group("Other Group");
                group2.setParent(p);

                p.addUser(user);
                p.addGroup(group);
                p.addGroup(group2);

                UserPanel panel = new UserPanel(user);

                UserPanel panel2 = new UserPanel(user);

                JFrame f = new JFrame("TEST PANEL");
                JPanel outerPanel = new JPanel(new BorderLayout());
                outerPanel.setBorder(BorderFactory.createLineBorder(Color.BLUE));
                outerPanel.add(panel.getPanel(), BorderLayout.CENTER);
                f.setContentPane(outerPanel);
                f.pack();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.setVisible(true);

                JFrame f2 = new JFrame("TEST PANEL");
                JPanel outerPanel2 = new JPanel(new BorderLayout());
                outerPanel2.setBorder(BorderFactory.createLineBorder(Color.BLUE));
                outerPanel2.add(panel2.getPanel(), BorderLayout.CENTER);
                f2.setContentPane(outerPanel2);
                f2.pack();
                f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f2.setVisible(true);

            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    });
}

From source file:net.sf.mpaxs.test.DistributedRmiExecution.java

@Override
public Double call() throws Exception {
    /*/*from ww w . j a v a 2s.  c  o  m*/
     * Compute Server is only required for VM external execution
     */
    Impaxs impxs = ComputeServerFactory.getComputeServer();
    if (cfg.getBoolean(ConfigurationKeys.KEY_GUI_MODE, false)) {
        final JFrame jf = new JFrame();
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel controlPanel = new JPanel();
        jf.add(controlPanel);
        controlPanel.setLayout(new BorderLayout());
        impxs.startMasterServer(cfg, controlPanel);
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                jf.setVisible(true);
                jf.pack();
            }
        });
    } else {
        impxs.startMasterServer(cfg);
    }
    CompletionServiceFactory<Double> csf = new CompletionServiceFactory<Double>();
    csf.setBlockingWait(true);
    final ICompletionService<Double> mcs = csf.asResubmissionService(csf.newDistributedCompletionService(), 3);
    for (int i = 0; i < maxJobs; i++) {
        mcs.submit(new TestCallable());
    }
    Job<Boolean> job = new Job<Boolean>(new TestScheduledRunnable(), Boolean.TRUE);
    //increase the priority so that the job can bypass other, waiting jobs
    job.setPriority(job.getPriority() + 1);
    //api submission, this job will be wrapped as a ScheduledJob
    impxs.submitScheduledJob(job, 1, 5, TimeUnit.SECONDS);
    //alternative, direct creation of a ScheduledJob
    //      impxs.submitJob(new ScheduledJob(job, 1, 5, TimeUnit.SECONDS));
    double result = 0.0d;
    try {
        List<Double> results = mcs.call();
        System.out.println("Distributed execution: " + results);
        for (Double double1 : results) {
            result += double1;
        }
    } catch (Exception ex) {
        Logger.getLogger(DistributedRmiExecution.class.getName()).log(Level.SEVERE, null, ex);
        throw ex;
    }

    CompletionServiceFactory<String> csf2 = new CompletionServiceFactory<String>();
    //        csf2.setTimeOut(1);
    //        csf2.setTimeUnit(TimeUnit.SECONDS);
    csf2.setBlockingWait(true);
    final ICompletionService<String> mcs2 = csf2.newDistributedCompletionService();
    for (int i = 0; i < maxJobs; i++) {
        mcs2.submit(new TestCallable2());
    }
    try {
        List<String> results = mcs2.call();
        System.out.println("Distributed execution: " + results);
        for (String str : results) {
            System.out.println("Result: " + str);
        }
    } catch (Exception ex) {
        Logger.getLogger(DistributedRmiExecution.class.getName()).log(Level.SEVERE, null, ex);
        throw ex;
    }

    final ICompletionService<Double> mcs3 = csf.newDistributedCompletionService();
    for (int i = 0; i < maxJobs; i++) {
        mcs3.submit(new TestCallable());
    }
    try {
        List<Double> results = mcs3.call();
        System.out.println("Distributed execution: " + results);
        for (Double double1 : results) {
            result += double1;
        }
    } catch (Exception ex) {
        Logger.getLogger(DistributedRmiExecution.class.getName()).log(Level.SEVERE, null, ex);
        throw ex;
    }

    impxs.stopMasterServer();
    return result;
}

From source file:net.sf.maltcms.chromaui.ui.paintScales.PaintScaleDialogAction.java

@Override
public void actionPerformed(ActionEvent ae) {
    Runnable r = new Runnable() {

        @Override//  w ww . j a v  a 2s  . c  om
        public void run() {
            PaintScale ps = showPaintScaleDialog();
            for (PaintScaleTarget pst : targets) {
                pst.setPaintScale(ps);
            }
        }
    };
    SwingUtilities.invokeLater(r);
}

From source file:finale.year.stage.responsable.ResponsableInterface.java

public static void updateStatus(final String message) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override// w ww . j  a va 2 s.com
        public void run() {
            errorStatusBar.setText("");
            errorStatusBar.setForeground(Color.red);
            errorStatusBar.setText(message);
        }
    });
}

From source file:net.sourceforge.jabm.view.TimeSeriesChart.java

@Override
public void afterPropertiesSet() {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            initialiseGUI();//from  ww w  . j  a  v a 2  s . c  o m
        }
    });
}

From source file:turtlekit.viewer.PopulationCharter.java

@Override
protected void observe() {
    updateSeries();/*  w  w w  .  j a va2  s .  c  om*/
    SwingUtilities.invokeLater(new Runnable() {//avoiding null pointers on the awt thread
        @Override
        public void run() {
            for (Entry<Probe<Turtle>, XYSeries> entry : series.entrySet()) {
                entry.getValue().add(index, entry.getKey().size());
            }
            index++;
            if (timeFrame > 0 && index % timeFrame == 0) {
                for (XYSeries serie : series.values()) {
                    serie.clear();
                }
            }
        }
    });
}

From source file:es.emergya.ui.base.Message.java

private void inicializar(final String texto) {
    log.trace("inicializar(" + texto + ")");
    final Message message_ = this;

    SwingUtilities.invokeLater(new Runnable() {

        @Override/*from   w  w  w  .j a  v a2 s  .  c o m*/
        public void run() {
            log.trace("Sacamos un nuevo mensaje: " + texto);
            JDialog frame = new JDialog(window.getFrame(), true);
            frame.setUndecorated(true);
            frame.getContentPane().setBackground(Color.WHITE);
            frame.setLocation(150, window.getHeight() - 140);
            frame.setSize(new Dimension(window.getWidth() - 160, 130));
            frame.setName("Incoming Message");
            frame.setBackground(Color.WHITE);
            frame.getRootPane().setBorder(new MatteBorder(4, 4, 4, 4, color));

            frame.setLayout(new BorderLayout());
            if (font != null)
                frame.setFont(font);

            JLabel icon = new JLabel(new ImageIcon(this.getClass().getResource("/images/button-ok.png")));
            icon.setToolTipText("Cerrar");

            icon.removeMouseListener(null);
            icon.addMouseListener(new Cerrar(frame, message_));

            JLabel text = new JLabel(texto);
            text.setBackground(Color.WHITE);
            text.setForeground(Color.BLACK);
            frame.add(text, BorderLayout.WEST);
            frame.add(icon, BorderLayout.EAST);

            frame.setVisible(true);
        }
    });
}

From source file:hudson.lifecycle.WindowsSlaveInstaller.java

public Void call() {
    if (File.separatorChar == '/')
        return null; // not Windows
    if (System.getProperty("hudson.showWindowsServiceInstallLink") == null)
        return null; // only show this when it makes sense, which is when we run from JNLP

    dialog = MainDialog.get();// w  w  w. jav  a  2  s .  c  o  m
    if (dialog == null)
        return null; // can't find the main window. Maybe not running with GUI

    // capture the engine
    engine = Engine.current();

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            MainMenu mainMenu = dialog.getMainMenu();
            JMenu m = mainMenu.getFileMenu();
            JMenuItem menu = new JMenuItem(Messages.WindowsInstallerLink_DisplayName(), KeyEvent.VK_W);
            menu.addActionListener(WindowsSlaveInstaller.this);
            m.add(menu);
            mainMenu.commit();
        }
    });

    return null;
}

From source file:SwingThreadingWait.java

public void actionPerformed(ActionEvent e) {
    start = System.currentTimeMillis();
    new Thread(new Runnable() {
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }/*from  w w w. j a  v  a 2  s  .c o m*/

                final int elapsed = (int) ((System.currentTimeMillis() - start) / 1000);
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        counter.setText("Time elapsed: " + elapsed + "s");
                    }
                });

                if (elapsed == 4) {
                    try {
                        final int[] answer = new int[1];
                        SwingUtilities.invokeAndWait(new Runnable() {
                            public void run() {
                                answer[0] = JOptionPane.showConfirmDialog(SwingThreadingWait.this,
                                        "Abort long operation?", "Abort?", JOptionPane.YES_NO_OPTION);
                            }
                        });
                        if (answer[0] == JOptionPane.YES_OPTION) {
                            return;
                        }
                    } catch (InterruptedException e1) {
                    } catch (InvocationTargetException e1) {
                    }
                }
            }
        }
    }).start();
}

From source file:ext.services.lastfm.LastFmAlbumsRunnable.java

@Override
public void run() {
    if (!interrupted) {
        listener.setLastAlbumRetrieved(null, id);
        if (retrieveArtistInfo) {
            listener.setLastArtistRetrieved(null, id);
        }/*from  www  .  j a v a  2 s  .  com*/
    }
    // Get wiki start for artist
    final String wikiText = service.getWikiText(audioObject.getArtist());
    final String wikiURL = service.getWikiURL(audioObject.getArtist());
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            listener.notifyWikiInfoRetrieved(wikiText, wikiURL, id);
        }
    });
    Image image = null;
    AlbumInfo album = null;
    List<AlbumInfo> albums = null;
    if (!interrupted) {
        // If possible use album artist
        String artist = audioObject.getAlbumArtist().isEmpty() ? audioObject.getArtist()
                : audioObject.getAlbumArtist();
        album = service.getAlbum(artist, audioObject.getAlbum());
        final AlbumInfo albumHelp = album;
        listener.setAlbum(albumHelp, id);
        if (album != null) {
            image = service.getImage(album);
        }
        listener.setImage(image, audioObject, id);
    }
    if (image != null && !interrupted) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                listener.notifyAlbumRetrieved(audioObject, id);
            }
        });
    }
    try {
        Thread.sleep(1000); // Wait a second to prevent IP banning
    } catch (InterruptedException e) {
        Log.debug("albums runnable interrupted");
    }
    // If we have to retrieve artist info do it. If not, get previous retrieved
    // albums list
    if (retrieveArtistInfo) {
        if (!interrupted) {
            String sArtist = audioObject.getArtist();
            if (StringUtils.isNotBlank(sArtist)
                    && !sArtist.equalsIgnoreCase(Messages.getString("unknown_artist"))) {
                AlbumListInfo albumList = service.getAlbumList(sArtist, true, 0);
                if (albumList != null) { //NOSONAR
                    albums = albumList.getAlbums();
                }
            }
            if (albums == null) {
                interrupted = true;
            }
            listener.setAlbums(albums, id);
        }
    } else {
        albums = listener.getAlbums();
    }
    if (album == null && albums != null && !interrupted) {
        // Try to find an album which fits
        AlbumInfo auxAlbum = null;
        int i = 0;
        while (!interrupted && auxAlbum == null && i < albums.size()) {
            AlbumInfo a = albums.get(i);
            StringTokenizer st = new StringTokenizer(a.getTitle(), " ");
            boolean matches = true;
            int tokensAnalyzed = 0;
            while (st.hasMoreTokens() && matches) {
                String t = st.nextToken();
                if (forbiddenToken(t)) { // Ignore album if contains forbidden chars
                    matches = false;
                    break;
                }
                if (!validToken(t)) { // Ignore tokens without alphanumerics
                    if (tokensAnalyzed == 0 && !st.hasMoreTokens()) {
                        matches = false;
                    } else {
                        continue;
                    }
                }
                if (!audioObject.getAlbum().toLowerCase(Locale.getDefault())
                        .contains(t.toLowerCase(Locale.getDefault()))) {
                    matches = false;
                }
                tokensAnalyzed++;
            }
            if (matches) {
                auxAlbum = a;
            }
            i++;
        }
        if (!interrupted && auxAlbum != null) {
            auxAlbum = service.getAlbum(auxAlbum.getArtist(), auxAlbum.getTitle());
            if (auxAlbum != null) {
                listener.setAlbum(auxAlbum, id);
                image = service.getImage(auxAlbum);
                listener.setImage(image, audioObject, id);
            }
        }
        if (!interrupted && auxAlbum != null) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    listener.notifyAlbumRetrieved(audioObject, id);
                }
            });
        }
    }
}