Java Code Examples for javax.swing.SwingWorker#execute()

The following examples show how to use javax.swing.SwingWorker#execute() . 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: VisualProfiler.java    From diirt with MIT License 6 votes vote down vote up
private void cancelThread(){
    if (thread != null){
        thread.cancel(true);
        console.btnCancelThread.setEnabled(false);

        SwingWorker worker = new SwingWorker(){

            @Override
            protected Object doInBackground() throws Exception {
                publish("\nAction Cancelled\n");
                publish("--------\n");
                return null;
            }

        };
        worker.execute();
    }
}
 
Example 2
Source File: bug6432565.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Toolkit.getDefaultToolkit().getSystemEventQueue().push(new EventProcessor());

    SwingWorker<Void, CharSequence> swingWorker =
        new SwingWorker<Void,CharSequence>() {
            @Override
            protected Void doInBackground() {
                publish(new String[] {"hello"});
                publish(new StringBuilder("world"));
                return null;
            }
            @Override
            protected void done() {
                isDone.set(true);
            }
        };
    swingWorker.execute();

    while (! isDone.get()) {
        Thread.sleep(100);
    }
    if (throwable.get() instanceof ArrayStoreException) {
        throw new RuntimeException("Test failed");
    }
}
 
Example 3
Source File: bug6432565.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Toolkit.getDefaultToolkit().getSystemEventQueue().push(new EventProcessor());

    SwingWorker<Void, CharSequence> swingWorker =
        new SwingWorker<Void,CharSequence>() {
            @Override
            protected Void doInBackground() {
                publish(new String[] {"hello"});
                publish(new StringBuilder("world"));
                return null;
            }
            @Override
            protected void done() {
                isDone.set(true);
            }
        };
    swingWorker.execute();

    while (! isDone.get()) {
        Thread.sleep(100);
    }
    if (throwable.get() instanceof ArrayStoreException) {
        throw new RuntimeException("Test failed");
    }
}
 
Example 4
Source File: BackgroundProgress.java    From open-ig with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Run a background process and show a dialog during this operation.
 * @param title the title
 * @param label the label
 * @param activity the background activity
 * @param onComplete the activity once the background finished
 */
public static void run(String title, String label,
		final Action0 activity, final Action0 onComplete) {
	final BackgroundProgress bgp = new BackgroundProgress();
	bgp.setTitle(title);
	bgp.setLabelText(label);
	bgp.pack();
	bgp.setLocationRelativeTo(null);
	SwingWorker<Void, Void> sw = new SwingWorker<Void, Void>() {
		@Override
		protected Void doInBackground() throws Exception {
			activity.invoke();
			return null;
		}
		@Override
		protected void done() {
			bgp.dispose();
			if (onComplete != null) {
				onComplete.invoke();
			}
		}
	};
	sw.execute();
	bgp.setVisible(true);
}
 
Example 5
Source File: ClassySharkPanel.java    From android-classyshark with Apache License 2.0 6 votes vote down vote up
private void readMappingFile(final File resultFile) {
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        private TokensMapper reverseMappings;

        @Override
        protected Void doInBackground() throws Exception {
            reverseMappings = silverGhost.readMappingFile(resultFile);
            return null;
        }

        protected void done() {
            silverGhost.addMappings(reverseMappings);
        }
    };

    worker.execute();
}
 
Example 6
Source File: bug6432565.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Toolkit.getDefaultToolkit().getSystemEventQueue().push(new EventProcessor());

    SwingWorker<Void, CharSequence> swingWorker =
        new SwingWorker<Void,CharSequence>() {
            @Override
            protected Void doInBackground() {
                publish(new String[] {"hello"});
                publish(new StringBuilder("world"));
                return null;
            }
            @Override
            protected void done() {
                isDone.set(true);
            }
        };
    swingWorker.execute();

    while (! isDone.get()) {
        Thread.sleep(100);
    }
    if (throwable.get() instanceof ArrayStoreException) {
        throw new RuntimeException("Test failed");
    }
}
 
Example 7
Source File: ScriptAction.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Run a CLI script from a File.
 *
 * @param script The script file.
 */
protected void runScript(File script) {
    if (!script.exists()) {
        JOptionPane.showMessageDialog(cliGuiCtx.getMainPanel(), script.getAbsolutePath() + " does not exist.",
                                      "Unable to run script.", JOptionPane.ERROR_MESSAGE);
        return;
    }

    int choice = JOptionPane.showConfirmDialog(cliGuiCtx.getMainPanel(), "Run CLI script " + script.getName() + "?",
                                               "Confirm run script", JOptionPane.YES_NO_OPTION);
    if (choice != JOptionPane.YES_OPTION) return;

    menu.addScript(script);

    cliGuiCtx.getTabs().setSelectedIndex(1); // set to Output tab to view the output
    output.post("\n");

    SwingWorker scriptRunner = new ScriptRunner(script);
    scriptRunner.execute();
}
 
Example 8
Source File: ExceptionSafePlugin.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public void executeSwingWorker(SwingWorker<?, ?> sw) {
    try {
        sw.execute();
    } catch (RuntimeException e) {
        handleException(e);
    }
}
 
Example 9
Source File: ChartsPanel.java    From javamelody with Apache License 2.0 5 votes vote down vote up
ChartsPanel(RemoteCollector remoteCollector) {
	super(remoteCollector);

	final JLabel throbberLabel = new JLabel(THROBBER_ICON);
	add(throbberLabel, BorderLayout.NORTH);
	add(createButtonsPanel(), BorderLayout.CENTER);

	// SwingWorker pour afficher le reste de l'écran et pour éviter de faire attendre rien que pour les graphiques
	final SwingWorker<Map<String, byte[]>, Object> swingWorker = new SwingWorker<Map<String, byte[]>, Object>() {
		@Override
		protected Map<String, byte[]> doInBackground() throws IOException {
			return getRemoteCollector().collectJRobins(CHART_WIDTH, CHART_HEIGHT);
		}

		@Override
		protected void done() {
			try {
				final Map<String, byte[]> jrobins = get();
				final JPanel mainJRobinsPanel = createJRobinPanel(jrobins);
				remove(throbberLabel);
				add(mainJRobinsPanel, BorderLayout.NORTH);
				revalidate();
			} catch (final Exception e) {
				showException(e);
				remove(throbberLabel);
			}
		}
	};
	swingWorker.execute();
}
 
Example 10
Source File: AnimPlay.java    From open-ig with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Save the selected file's audio as Wave.
 * @param what the file to use as input
 * @param target the target output filename
 * @param modal show the dialog as modal?
 * @param parent the parent frame
 * @return the worker
 */
static SwingWorker<Void, Void> saveAsWavWorker(final File what, final File target, boolean modal, JFrame parent) {
	final ProgressFrame pf = new ProgressFrame("Save as WAV: " + target, parent);
	SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
		@Override
		protected Void doInBackground() throws Exception {
			transcodeToWav(what.getAbsolutePath(), target.getAbsolutePath(), new ProgressCallback() {
				@Override
				public void progress(final int value, final int max) {
					SwingUtilities.invokeLater(new Runnable() {
						@Override
						public void run() {
							pf.setMax(max);
							pf.setCurrent(value, "Progress: " + value + " / " + max + " frames");
						}
					});
				}
				@Override
				public boolean cancel() {
					return pf.isCancelled();
				}
			});
			return null;
		}
		@Override
		protected void done() {
			// delay window close a bit further
			SwingUtilities.invokeLater(new Runnable() {
				@Override
				public void run() {
					pf.dispose();
				}
			});
		}
	};
	worker.execute();
	pf.setModalityType(modal ? ModalityType.APPLICATION_MODAL : ModalityType.MODELESS);
	pf.setVisible(true);
	return worker;
}
 
Example 11
Source File: Launcher.java    From Openfire with Apache License 2.0 4 votes vote down vote up
private void installPlugin(final File plugin) {
    final JDialog dialog = new JDialog(frame, "Installing Plugin", true);
    dialog.getContentPane().setLayout(new BorderLayout());
    JProgressBar bar = new JProgressBar();
    bar.setIndeterminate(true);
    bar.setString("Installing Plugin.  Please wait...");
    bar.setStringPainted(true);
    dialog.getContentPane().add(bar, BorderLayout.CENTER);
    dialog.pack();
    dialog.setSize(225, 55);

    final SwingWorker<File, Void> installerThread = new SwingWorker<File, Void>() {
        @Override
        public File doInBackground() {
            File pluginsDir = new File(binDir.getParentFile(), "plugins");
            String tempName = plugin.getName() + ".part";
            File tempPluginsFile = new File(pluginsDir, tempName);

            File realPluginsFile = new File(pluginsDir, plugin.getName());

            // Copy Plugin into Dir.
            try {
                // Just for fun. Show no matter what for two seconds.
                Thread.sleep(2000);

                copy(plugin.toURI().toURL(), tempPluginsFile);

                // If successfull, rename to real plugin name.
                tempPluginsFile.renameTo(realPluginsFile);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
            return realPluginsFile;
        }

        @Override
        public void done() {
            dialog.setVisible(false);
        }
    };

    // Start installation
    installerThread.execute();

    dialog.setLocationRelativeTo(frame);
    dialog.setVisible(true);
}
 
Example 12
Source File: XSheet.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private void displayMBeanNode(final DefaultMutableTreeNode node) {
    final XNodeInfo uo = (XNodeInfo) node.getUserObject();
    if (!uo.getType().equals(Type.MBEAN)) {
        return;
    }
    mbean = (XMBean) uo.getData();
    SwingWorker<MBeanInfo, Void> sw = new SwingWorker<MBeanInfo, Void>() {
        @Override
        public MBeanInfo doInBackground() throws InstanceNotFoundException,
                IntrospectionException, ReflectionException, IOException {
            return mbean.getMBeanInfo();
        }
        @Override
        protected void done() {
            try {
                MBeanInfo mbi = get();
                if (mbi != null) {
                    if (!isSelectedNode(node, currentNode)) {
                        return;
                    }
                    mbeanInfo.addMBeanInfo(mbean, mbi);
                    invalidate();
                    mainPanel.removeAll();
                    mainPanel.add(mbeanInfo, BorderLayout.CENTER);
                    southPanel.setVisible(false);
                    southPanel.removeAll();
                    validate();
                    repaint();
                }
            } catch (Exception e) {
                Throwable t = Utils.getActualException(e);
                if (JConsole.isDebug()) {
                    System.err.println("Couldn't get MBeanInfo for MBean [" +
                            mbean.getObjectName() + "]");
                    t.printStackTrace();
                }
                showErrorDialog(t.toString(),
                        Messages.PROBLEM_DISPLAYING_MBEAN);
            }
        }
    };
    sw.execute();
}
 
Example 13
Source File: TaxaEditor.java    From beast-mcmc with GNU Lesser General Public License v2.1 4 votes vote down vote up
private void doOk() {

		frame.setBusy();
		SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

			// Executed in background thread
			public Void doInBackground() {

				try {

					// delete taxa connected to this row
					String value = dataList.recordsList.get(row).getName();
					Utils.removeTaxaWithAttributeValue(dataList,
							Utils.TREE_FILENAME, value);

					String name = String.valueOf("TaxaSet").concat(
							String.valueOf(row + 1));
					Taxa taxa = taxaEditorTableModel.getTaxaSet();
					TreesTableRecord record = new TreesTableRecord(name, taxa);

					dataList.recordsList.set(row, record);
					dataList.allTaxa.addTaxa(taxa);

					// treesTableModel.setRow(row, record);

				} catch (Exception e) {
					Utils.handleException(e);
				}// END: try-catch block

				return null;
			}// END: doInBackground()

			// Executed in event dispatch thread
			public void done() {
				frame.setIdle();
				frame.fireTaxaChanged();
				window.setVisible(false);
			}// END: done
		};

		worker.execute();

	}
 
Example 14
Source File: XSheet.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private void displayMBeanNode(final DefaultMutableTreeNode node) {
    final XNodeInfo uo = (XNodeInfo) node.getUserObject();
    if (!uo.getType().equals(Type.MBEAN)) {
        return;
    }
    mbean = (XMBean) uo.getData();
    SwingWorker<MBeanInfo, Void> sw = new SwingWorker<MBeanInfo, Void>() {
        @Override
        public MBeanInfo doInBackground() throws InstanceNotFoundException,
                IntrospectionException, ReflectionException, IOException {
            return mbean.getMBeanInfo();
        }
        @Override
        protected void done() {
            try {
                MBeanInfo mbi = get();
                if (mbi != null) {
                    if (!isSelectedNode(node, currentNode)) {
                        return;
                    }
                    mbeanInfo.addMBeanInfo(mbean, mbi);
                    invalidate();
                    mainPanel.removeAll();
                    mainPanel.add(mbeanInfo, BorderLayout.CENTER);
                    southPanel.setVisible(false);
                    southPanel.removeAll();
                    validate();
                    repaint();
                }
            } catch (Exception e) {
                Throwable t = Utils.getActualException(e);
                if (JConsole.isDebug()) {
                    System.err.println("Couldn't get MBeanInfo for MBean [" +
                            mbean.getObjectName() + "]");
                    t.printStackTrace();
                }
                showErrorDialog(t.toString(),
                        Messages.PROBLEM_DISPLAYING_MBEAN);
            }
        }
    };
    sw.execute();
}
 
Example 15
Source File: CustomSettingsDialog.java    From swingsane with Apache License 2.0 4 votes vote down vote up
private void importActionPerformed(ActionEvent e) {

    final File file = getLoadFile("scanner", "xml");

    if (file == null) {
      return;
    }

    final INotification notificaiton = new DialogNotificationImpl(getRootPane()
        .getTopLevelAncestor());

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

      @Override
      protected Void doInBackground() throws Exception {
        notificaiton.message(Localizer.localize("LoadingScannerPreferencesMessageText"));
        String remoteAddress = scanner.getRemoteAddress();
        int remotePort = scanner.getRemotePortNumber();
        String description = scanner.getDescription();
        scanner = PreferencesUtils.importScannerXML(xstream, file);
        scanner.setRemoteAddress(remoteAddress);
        scanner.setRemotePortNumber(remotePort);
        scanner.setDescription(description);
        updateTableModel();
        optionNameTable.revalidate();
        return null;
      }

      @Override
      protected void done() {
        try {
          get();
          showLoadSuccessMessage();
          ((JDialog) notificaiton).setVisible(false);
        } catch (Exception ex) {
          LOG.error(ex, ex);
          showLoadErrorMessage(ex);
        } finally {
          ((JDialog) notificaiton).dispose();
        }
      }
    };

    worker.execute();

    ((JDialog) notificaiton).setModal(true);
    ((JDialog) notificaiton).setVisible(true);

  }
 
Example 16
Source File: XSheet.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private void displayMBeanNode(final DefaultMutableTreeNode node) {
    final XNodeInfo uo = (XNodeInfo) node.getUserObject();
    if (!uo.getType().equals(Type.MBEAN)) {
        return;
    }
    mbean = (XMBean) uo.getData();
    SwingWorker<MBeanInfo, Void> sw = new SwingWorker<MBeanInfo, Void>() {
        @Override
        public MBeanInfo doInBackground() throws InstanceNotFoundException,
                IntrospectionException, ReflectionException, IOException {
            return mbean.getMBeanInfo();
        }
        @Override
        protected void done() {
            try {
                MBeanInfo mbi = get();
                if (mbi != null) {
                    if (!isSelectedNode(node, currentNode)) {
                        return;
                    }
                    mbeanInfo.addMBeanInfo(mbean, mbi);
                    invalidate();
                    mainPanel.removeAll();
                    mainPanel.add(mbeanInfo, BorderLayout.CENTER);
                    southPanel.setVisible(false);
                    southPanel.removeAll();
                    validate();
                    repaint();
                }
            } catch (Exception e) {
                Throwable t = Utils.getActualException(e);
                if (JConsole.isDebug()) {
                    System.err.println("Couldn't get MBeanInfo for MBean [" +
                            mbean.getObjectName() + "]");
                    t.printStackTrace();
                }
                showErrorDialog(t.toString(),
                        Messages.PROBLEM_DISPLAYING_MBEAN);
            }
        }
    };
    sw.execute();
}
 
Example 17
Source File: VisualProfiler.java    From diirt with MIT License 4 votes vote down vote up
/**
 * Thread safe operation to save the console log of the graphical
 * user interface.
 * The log is saved as a <b>.txt</b> file with the current timestamp.
 */
private void saveLog(){
    SwingWorker worker = new SwingWorker<Object, String>(){

        @Override
        protected Object doInBackground() throws Exception {
            setEnabledActions(false);
            threadStart(this);

            //Where saving occurs
            saveFile();

            publish("--------\n");
            publish("Saving Log...");

            //Saves beforehand to prevent this from being in log

            publish("finished.\n");
            publish("--------\n");
            setEnabledActions(true);
            threadFinish();
            return null;
        }

        private void saveFile(){
            //Creates file
            File outputFile = new File(ProfileGraph2D.LOG_FILEPATH +
                              DateUtils.getDate(DateFormat.NONDELIMITED) +
                              "-Log.txt");

            try {
                outputFile.createNewFile();

                PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));

                //Prints console
                out.print(console.txtConsole.getText());

                out.close();
            } catch (IOException ex) {
                System.err.println("Output errors exist.");
            }
        }

        @Override
        protected void process(List<String> chunks){
            for (String chunk: chunks){
                print(chunk);
            }
        }
    };
    worker.execute();
}
 
Example 18
Source File: XSheet.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
private void displayMBeanOperationsNode(final DefaultMutableTreeNode node) {
    final XNodeInfo uo = (XNodeInfo) node.getUserObject();
    if (!uo.getType().equals(Type.OPERATIONS)) {
        return;
    }
    mbean = (XMBean) uo.getData();
    SwingWorker<MBeanInfo, Void> sw = new SwingWorker<MBeanInfo, Void>() {
        @Override
        public MBeanInfo doInBackground() throws InstanceNotFoundException,
                IntrospectionException, ReflectionException, IOException {
            return mbean.getMBeanInfo();
        }
        @Override
        protected void done() {
            try {
                MBeanInfo mbi = get();
                if (mbi != null) {
                    if (!isSelectedNode(node, currentNode)) {
                        return;
                    }
                    mbeanOperations.loadOperations(mbean, mbi);
                    invalidate();
                    mainPanel.removeAll();
                    JPanel borderPanel = new JPanel(new BorderLayout());
                    borderPanel.setBorder(BorderFactory.createTitledBorder(
                            Messages.OPERATION_INVOCATION));
                    borderPanel.add(new JScrollPane(mbeanOperations));
                    mainPanel.add(borderPanel, BorderLayout.CENTER);
                    southPanel.setVisible(false);
                    southPanel.removeAll();
                    validate();
                    repaint();
                }
            } catch (Exception e) {
                Throwable t = Utils.getActualException(e);
                if (JConsole.isDebug()) {
                    System.err.println("Problem displaying MBean " +
                            "operations for MBean [" +
                            mbean.getObjectName() + "]");
                    t.printStackTrace();
                }
                showErrorDialog(t.toString(),
                        Messages.PROBLEM_DISPLAYING_MBEAN);
            }
        }
    };
    sw.execute();
}
 
Example 19
Source File: BinningIOPanel.java    From snap-desktop with GNU General Public License v3.0 4 votes vote down vote up
private void openFirstProduct(final String[] inputPaths) {
    final SwingWorker<Product, Void> worker = new SwingWorker<Product, Void>() {
        @Override
        protected Product doInBackground() throws Exception {
            for (String inputPath : inputPaths) {
                if (inputPath == null || inputPath.trim().length() == 0) {
                    continue;
                }
                try {
                    final TreeSet<File> fileSet = new TreeSet<>();
                    WildcardMatcher.glob(inputPath, fileSet);
                    for (File file : fileSet) {
                        final Product product = ProductIO.readProduct(file);
                        if (product != null) {
                            return product;
                        }
                    }
                } catch (IOException e) {
                    Logger logger = SystemUtils.LOG;
                    logger.severe("I/O problem occurred while scanning source product files: " + e.getMessage());
                }
            }
            return null;
        }

        @Override
        protected void done() {
            try {
                Product firstProduct = get();
                if (firstProduct != null) {
                    binningFormModel.useAsContextProduct(firstProduct);
                    firstProduct.dispose();
                }
            } catch (Exception ex) {
                String msg = String.format("Cannot open source products.\n%s", ex.getMessage());
                appContext.handleError(msg, ex);
            }
        }
    };
    worker.execute();
}
 
Example 20
Source File: MainFrame.java    From beast-mcmc with GNU Lesser General Public License v2.1 3 votes vote down vote up
private void generateXML(final File outFile) {

        setBusy();

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

            // Executed in background thread
            public Void doInBackground() {

                try {

                    collectAllSettings();
                    XMLGenerator xmlGenerator = new XMLGenerator(dataList);
                    xmlGenerator.generateXML(outFile);

                } catch (Exception e) {
                    Utils.handleException(e);
                    setStatus("Exception occured.");
                    setIdle();
                }

                return null;
            }// END: doInBackground

            // Executed in event dispatch thread
            public void done() {

                setStatus("Generated " + outFile);
                setIdle();

            }// END: done
        };

        worker.execute();

    }