Example usage for javax.swing SwingWorker SwingWorker

List of usage examples for javax.swing SwingWorker SwingWorker

Introduction

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

Prototype

public SwingWorker() 

Source Link

Document

Constructs this SwingWorker .

Usage

From source file:Main.java

public static void main(String[] args) throws UnsupportedEncodingException {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel(new BorderLayout());
    JPanel buttons = new JPanel();
    JScrollPane pane = new JScrollPane(buttons);
    pane.getViewport().addChangeListener(e -> {
        System.out.println("Change in " + e.getSource());
        System.out.println("Vertical visible? " + pane.getVerticalScrollBar().isVisible());
        System.out.println("Horizontal visible? " + pane.getHorizontalScrollBar().isVisible());
    });// w w  w  .j a  v  a 2 s.com
    panel.add(pane);
    frame.setContentPane(panel);
    frame.setSize(300, 200);
    frame.setVisible(true);
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            for (int i = 0; i < 10; i++) {
                Thread.sleep(800);
                buttons.add(new JButton("Hello " + i));
                buttons.revalidate();
            }
            return null;
        }
    };
    worker.execute();
}

From source file:Main.java

public static void main(String[] args) {
    JProgressBar progressBar = new JProgressBar();
    progressBar.setOpaque(false);//from  w ww. j a  v  a 2s. co  m
    progressBar.setUI(new GradientPalletProgressBarUI());

    JPanel p = new JPanel();
    p.add(progressBar);
    p.add(new JButton(new AbstractAction("Start") {
        @Override
        public void actionPerformed(ActionEvent e) {
            SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
                @Override
                public Void doInBackground() {
                    int current = 0, lengthOfTask = 100;
                    while (current <= lengthOfTask && !isCancelled()) {
                        try {
                            Thread.sleep(50);
                        } catch (Exception ie) {
                            return null;
                        }
                        setProgress(100 * current / lengthOfTask);
                        current++;
                    }
                    return null;
                }
            };
            worker.addPropertyChangeListener(new ProgressListener(progressBar));
            worker.execute();
        }
    }));

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.getContentPane().add(p);
    frame.setSize(320, 240);
    frame.setVisible(true);
}

From source file:com.josescalia.tumblr.app.Bootstrap.java

public static void main(String[] args) {
    final Bootstrap app = new Bootstrap();

    //initialize splashScreen
    final ApplicationSplash splash = new ApplicationSplash();
    splash.setTitle("Tumblr Rss Image Viewer");
    splash.setSplashImage(app.getSplashImage());
    splash.setIconImage(new ImageIcon(splash.getClass().getResource("/icons/tumblr.png")).getImage());
    splash.setVisible(true);/*from  w ww.j  a  v  a2s.  com*/
    //read or write applicationConfig

    new SwingWorker<String, String>() {
        @Override
        protected String doInBackground() throws Exception {
            app.runApp(splash);
            return "Done";
        }

        protected void done() {
            System.gc();
            logger.info("Application Running..");
        }
    }.execute();
}

From source file:com.att.aro.ui.view.MainFrame.java

/**
 * Launch the application./*ww  w  .j a  v a  2 s .  c  om*/
 */
public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                window = new MainFrame();
                window.frmApplicationResourceOptimizer.setVisible(true);
                setLocationMap();
            } catch (Exception e) {
                e.printStackTrace();
            }
            final SplashScreen splash = new SplashScreen();
            splash.setVisible(true);
            splash.setAlwaysOnTop(true);
            new SwingWorker<Object, Object>() {
                @Override
                protected Object doInBackground() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                    }
                    return null;
                }

                @Override
                protected void done() {
                    splash.dispose();
                }
            }.execute();

            new Thread(() -> {
                if (window.ffmpegConfirmationImpl.checkFFmpegExistance() == false) {
                    SwingUtilities.invokeLater(() -> window.launchDialog(new FFmpegConfirmationDialog()));
                }
            }).start();

            new Thread(() -> {
                if (Util.isMacOS() && !window.pcapConfirmationImpl.checkPcapVersion()) {
                    SwingUtilities.invokeLater(() -> window.launchDialog(new PcapConfirmationDialog()));
                }
            }).start();
        }
    });
}

From source file:Main.java

public static void doInBackground(final Runnable r) {
    new SwingWorker<Void, Void>() {
        @Override/*from  ww w.j  av  a  2 s  .c om*/
        protected Void doInBackground() {
            r.run();
            return null;
        }
    }.execute();
}

From source file:Main.java

/**
 * If runOnEDT is true will execute the thread on the Event Dispatch Thread
 * Otherwise it will use a SwingWorker/* w  w  w  .ja va2 s  . com*/
 * @param r <code>Runnable</code> to execute
 * @param runOnEDT run on Event Dispatching Thread
 *
 * @see javax.swing.SwingWorker
 * @see java.lang.Runnable
 * @deprecated
 */
@Deprecated
public static void runTask(final Runnable r, boolean runOnEDT) {
    if (runOnEDT) {
        SwingUtilities.invokeLater(r);
        return;
    }

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

        @Override
        protected Void doInBackground() throws Exception {
            r.run();
            return null;
        }
    };
    worker.execute();
}

From source file:Main.java

public Main() {
    super(BoxLayout.Y_AXIS);

    Box info = Box.createVerticalBox();
    info.add(new Label("Please wait 3 seconds"));
    final JButton continueButton = new JButton("Continue");
    info.add(continueButton);//from  ww w  . ja  v a2 s .com

    JDialog d = new JDialog();
    d.setModalityType(ModalityType.APPLICATION_MODAL);
    d.setContentPane(info);
    d.pack();

    continueButton.addActionListener(e -> d.dispose());
    continueButton.setVisible(false);

    SwingWorker sw = new SwingWorker<Integer, Integer>() {
        protected Integer doInBackground() throws Exception {
            int i = 0;
            while (i++ < 30) {
                System.out.println(i);
                Thread.sleep(100);
            }
            return null;
        }

        @Override
        protected void done() {
            continueButton.setVisible(true);
        }

    };
    JButton button = new JButton("Click Me");
    button.addActionListener(e -> {
        sw.execute();
        d.setVisible(true);
    });
    add(button);
}

From source file:commonline.query.gui.action.ClearDatabaseAction.java

public void actionPerformed(ActionEvent actionEvent) {
    if (JOptionPane.showConfirmDialog(parent, "Are you sure you want to clear the databases?", "Clear DB",
            JOptionPane.YES_NO_OPTION) == JOptionPane.OK_OPTION) {
        SwingWorker worker = new SwingWorker<Void, Void>() {
            protected Void doInBackground() throws Exception {
                for (RecordParserDataSource dataSource : dataSources) {
                    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
                    for (RecordLayoutTableInfo tableInfo : dataSource.getTableInfos()) {
                        try {
                            jdbcTemplate.execute("delete from " + tableInfo.getTableName());
                        } catch (Exception err) {
                            throw new RuntimeException("Problem clearing table:" + tableInfo.getTableName()
                                    + ", in DB:" + dataSource.getUrl(), err);
                        }/*from  w  ww. j  a  v  a2  s .c om*/
                    }
                }
                return null;
            }
        };
        worker.execute();
    }
}

From source file:be.ac.ua.comp.scarletnebula.gui.keywizards.FinalNewKeyPage.java

@Override
protected void performAction(final KeyRecorder recorder) {
    recorder.keyname = keyname;//from  w  ww  .j a v a2 s  .c o m
    recorder.makeDefault = makeKeyDefault();

    (new SwingWorker<Exception, Object>() {
        @Override
        protected Exception doInBackground() throws Exception {
            try {
                provider.createKey(keyname, makeKeyDefault());
            } catch (final Exception e) {
                return e;
            }
            return null;
        }

        @Override
        public void done() {
            try {
                final Exception result = get();

                if (result != null) {
                    log.error("Could not create key", result);
                    JOptionPane.showMessageDialog(FinalNewKeyPage.this, result.getLocalizedMessage(),
                            "Error creating key", JOptionPane.ERROR_MESSAGE);
                }
            } catch (final Exception ignore) {
            }
        }
    }).execute();
}

From source file:actions.ScanFileAction.java

@Override
public void actionPerformed(ActionEvent e) {
    new SwingWorker() {
        @Override/*  www. jav  a  2 s .c  o m*/
        protected Object doInBackground() throws Exception {
            if (pmFileNode.pmFile.isIsScanned()) {
                JOptionPane.showMessageDialog(null, "The file has been already scanned.");
            }
            if (VirusTotalAPIHelper.apiKey.equals("")) {
                VirusTotalAPIHelper.apiKey = JOptionPane.showInputDialog("Enter valid API key");
            }
            if (VirusTotalAPIHelper.apiKey.equals("")) {
                return null;
            } else {
                // scan file and get the report.
                CloseableHttpResponse scanFileResponse = VirusTotalAPIHelper
                        .scanFile(pmFileNode.pmFile.getFile());
                try {
                    JSONObject obj = (JSONObject) parser
                            .parse(getStringFromClosableHttpResponse(scanFileResponse));
                    pmFileNode.pmFile.isScanned = true;
                    pmFileNode.pmFile.md5 = (String) obj.get("md5");
                    pmFileNode.pmFile.sha1 = (String) obj.get("sha1");
                    pmFileNode.pmFile.sha2 = (String) obj.get("sha256");
                    pmFileNode.pmFile.scan_id = (String) obj.get("scan_id");
                } catch (ParseException ex) {
                    Exceptions.printStackTrace(ex);
                }
            }
            CloseableHttpResponse reportResponse = VirusTotalAPIHelper.getReport(pmFileNode.pmFile.getSha2());
            try {
                JSONObject obj = (JSONObject) parser.parse(getStringFromClosableHttpResponse(reportResponse));
                pmFileNode.pmFile.scanDate = (String) obj.get("scan_date");
                pmFileNode.pmFile.positives = (Long) obj.get("positives");
                pmFileNode.pmFile.totals = (Long) obj.get("total");
                JSONObject scans = (JSONObject) obj.get("scans");
                if (scans != null && !scans.isEmpty()) {
                    Iterator iterator = scans.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry pair = (Map.Entry) iterator.next();
                        JSONObject scan = (JSONObject) pair.getValue();
                        pmFileNode.pmFile.listOfScans.add(new Scan((String) pair.getKey(), true,
                                scan.get("result") == null ? "" : (String) scan.get("result"),
                                scan.get("version") == null ? "" : (String) scan.get("version"),
                                scan.get("update") == null ? "" : (String) scan.get("update")));
                        iterator.remove(); // avoids a ConcurrentModificationException
                        pmFileNode.pmFile.numberOfScans++;
                    }
                }

            } catch (ParseException ex) {
                Exceptions.printStackTrace(ex);
            }
            MainWindowTopComponent.getInstance().writeOutput(pmFileNode.pmFile.toString());
            pmFileNode.pmfcf.refresh(pmFileNode.pmFile);
            return null;
        }
    }.run();

}