List of usage examples for javax.swing SwingWorker execute
public final void execute()
From source file:org.usfirst.frc.team2084.neuralnetwork.HeadingNeuralNetworkTrainer.java
private void trainNetwork() { if (!training) { // Set training flag and disable button training = true;/*from w w w .j a v a 2s. co m*/ trainButton.setEnabled(false); final ProgressMonitor progressMonitor = new ProgressMonitor(frame, "Training Network...", "", 0, 100); progressMonitor.setMillisToDecideToPopup(100); progressMonitor.setMillisToPopup(400); @SuppressWarnings("unchecked") final ArrayList<XYDataItem> data = new ArrayList<>(outputGraphDataSeries.getItems()); final int maxProgress = iterations * data.size(); final SwingWorker<Void, Void> trainingWorker = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { // Reset the neural network to default values synchronized (this) { network.reset(); network.setEta(eta); network.setMomentum(momentum); } outer: for (int j = 0; j < iterations; j++) { for (int i = 0; i < data.size(); i++) { if (!isCancelled()) { XYDataItem d = data.get(i); double error = convertAngleToInput(d.getXValue()); double output = d.getYValue(); synchronized (this) { network.feedForward(error); network.backPropagation(output); } int jl = j; int il = i; int progress = (int) (((float) (data.size() * jl + il + 1) / maxProgress) * 100); setProgress(progress); } else { break outer; } } } displayNetwork(); return null; } @Override protected void done() { training = false; trainButton.setEnabled(true); progressMonitor.close(); } }; trainingWorker.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals("progress")) { progressMonitor.setProgress((int) evt.getNewValue()); } if (progressMonitor.isCanceled()) { trainingWorker.cancel(true); } } }); trainingWorker.execute(); } }
From source file:it.illinois.adsc.ema.softgrid.monitoring.ui.SPMainFrame.java
public void startIEDs(final String caseFilePath) { runButton.setEnabled(false);/*from w ww .ja v a 2 s . c o m*/ clearButton.setEnabled(true); serverStatus = 0; setTitle("SoftGrid Monitor"); SwingWorker iedWorker = new SwingWorker() { @Override protected Object doInBackground() throws Exception { System.out.println("Starting IED initialization...!"); resultTabbedPane.add(logAreaScrollPane, "IED Log"); queryScrolPane.getViewport().add(queryTextArea, null); messageHandler.addLogMessage("Initialize Power World...DONE"); messageHandler.addLogMessage("Initialize COM interface...DONE"); messageHandler.addLogMessage("Initialize IED interfaces...DONE"); messageHandler.addLogMessage("Starting IED Servers.........!(This may take few seconds)"); it.illinois.adsc.ema.control.conf.generator.ConfigGenerator.generateConfigXml(ConfigUtil.SCL_PATH, ConfigUtil.CONFIG_PEROPERTY_FILE, ConfigUtil.IP); messageHandler.addLogMessage("Generating SCL files...!"); SclGenerator.generateSCLFiles(); messageHandler.addLogMessage("SCL files generated."); String[] args = { "-f", ConfigUtil.CONFIG_PEROPERTY_FILE, ConfigUtil.SERVER_TYPE, "local" }; mainTabbedPane.add(altertScrolPane, "Transient Monitor"); monitorButton.setVisible(true); SoftGridController.setIEDLogEventListener(SPMainFrame.this); executeMonitorQuery(); startPython(); System.out.println("All Init Operations are executed...!"); SoftGridController.initiate(args); try { dataFileWriter = new BufferedWriter(new FileWriter(new File(ConfigUtil.EXP_DATA_FILE))); } catch (IOException e) { e.printStackTrace(); } return null; } }; iedWorker.execute(); startMonitor(); }
From source file:com.opendoorlogistics.studio.AppFrame.java
public AppFrame() { // create frame with desktop pane Container con = getContentPane(); con.setLayout(new BorderLayout()); SwingWorker<BufferedImage, BufferedImage> createBackground = new SwingWorker<BufferedImage, BufferedImage>() { @Override/*from w ww. j av a2 s.c o m*/ protected BufferedImage doInBackground() throws Exception { // background = new AppBackground().create(); AppBackground ab = new AppBackground(); ab.start(); long lastTime = System.currentTimeMillis(); int lastRendered = 0; while (ab.getNbConsecutiveFails() < 100) { ab.doStep(); long current = System.currentTimeMillis(); if (current - lastTime > 100 && lastRendered != ab.getNbRendered()) { background = ImageUtils.deepCopy(ab.getImage()); publish(background); lastTime = current; lastRendered = ab.getNbRendered(); } } ab.finish(); background = ab.getImage(); return background; } @Override protected void process(List<BufferedImage> chunks) { repaint(); } @Override public void done() { AppFrame.this.repaint(); } }; createBackground.execute(); initWindowPosition(); registerAppFrameDependentComponents(); // then create other objects which might use the components tables = new DatastoreTablesPanel(this); // create scripts panel after registering components scriptManager = new ScriptUIManagerImpl(this); scriptsPanel = new ScriptsPanel(getApi(), PreferencesManager.getSingleton().getScriptsDirectory(), scriptManager); // set my icon setIconImage(Icons.loadFromStandardPath("App logo.png").getImage()); // create actions fileActions = initFileActions(); editActions = initEditActions(); // create left-hand panel with scripts and tables splitterTablesScripts = new JSplitPane(JSplitPane.VERTICAL_SPLIT, tables, scriptsPanel); splitterTablesScripts.setPreferredSize(new Dimension(200, splitterTablesScripts.getPreferredSize().height)); splitterTablesScripts.setResizeWeight(0.5); // split center part into tables/scripts browser on the left and desktop // pane on the right desktopScrollPane = new DesktopScrollPane(desktopPane); splitterLeftPanelMain = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, splitterTablesScripts, desktopScrollPane); con.add(splitterLeftPanelMain, BorderLayout.CENTER); // add toolbar initToolbar(con); initMenus(); // control close operation to stop changed being lost setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { if (canCloseDatastore()) { dispose(); System.exit(0); } } }); setVisible(true); updateAppearance(); }
From source file:com.mirth.connect.client.ui.SettingsPanelServer.java
public void doRestore() { if (getFrame().isSaveEnabled()) { if (!getFrame().alertOkCancel(this, "Your new settings will first be saved. Continue?")) { return; }/*from ww w. j av a2 s . c om*/ if (!doSave()) { return; } } String content = getFrame().browseForFileString("XML"); if (content != null) { try { if (!getFrame().promptObjectMigration(content, "server configuration")) { return; } final ServerConfiguration configuration = ObjectXMLSerializer.getInstance().deserialize(content, ServerConfiguration.class); final JCheckBox deployChannelsCheckBox = new JCheckBox("Deploy all channels after import"); deployChannelsCheckBox.setSelected(true); String warningMessage = "Import configuration from " + configuration.getDate() + "?\nWARNING: This will overwrite all current channels,\nalerts, server properties, and plugin properties.\n"; Object[] params = { warningMessage, new JLabel(" "), deployChannelsCheckBox }; int option = JOptionPane.showConfirmDialog(this, params, "Select an Option", JOptionPane.YES_NO_OPTION); if (option == JOptionPane.YES_OPTION) { final Set<String> alertIds = new HashSet<String>(); for (AlertStatus alertStatus : PlatformUI.MIRTH_FRAME.mirthClient.getAlertStatusList()) { alertIds.add(alertStatus.getId()); } final String workingId = getFrame().startWorking("Restoring server config..."); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { private boolean updateAlerts = false; public Void doInBackground() { try { getFrame().mirthClient.setServerConfiguration(configuration, deployChannelsCheckBox.isSelected()); getFrame().channelPanel.clearChannelCache(); doRefresh(); getFrame().alertInformation(SettingsPanelServer.this, "Your configuration was successfully restored."); updateAlerts = true; } catch (ClientException e) { getFrame().alertThrowable(SettingsPanelServer.this, e); } return null; } public void done() { if (getFrame().alertPanel == null) { getFrame().alertPanel = new DefaultAlertPanel(); } if (updateAlerts) { getFrame().alertPanel.updateAlertDetails(alertIds); } getFrame().stopWorking(workingId); } }; worker.execute(); } } catch (Exception e) { getFrame().alertError(this, "Invalid server configuration file."); } } }
From source file:mainGUI.TrainingJFrame.java
private void startTrainButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_startTrainButtonActionPerformed series.clear();/* w w w. j a va 2 s .com*/ stopTrainButton.setEnabled(true); startTrainButton.setEnabled(false); trainingHelper = new TrainingHelper(neuralNet, trainingDataSet, trainingDataSet.subDataSet(0, 700), learningParameters); epochProgressBar.setValue(0); epochProgressBar.setMaximum(trainingDataSet.size()); SwingWorker<Boolean, TrainingPublishable> worker = new SwingWorker<Boolean, TrainingPublishable>() { @Override protected Boolean doInBackground() throws Exception { trainingHelper.setOnItemTrainListener(new OnItemTrainListener() { @Override public void onItemTrain(int trainingDataItemIndex) { publish(new TrainingPublishable(trainingDataItemIndex)); } }); trainingHelper.setOnEpochFinishListner(new OnEpochFinishListener() { @Override public void onEpochFinish() { publish(new TrainingPublishable(neuralNet.deepClone(), trainingHelper.getEpoch(), trainingHelper.getEpochMSE())); } }); trainingHelper.train(); return true; } @Override protected void done() { System.out.println("Training Done"); } @Override protected void process(List<TrainingPublishable> chunks) { for (TrainingPublishable chunk : chunks) { if (chunk.neuralNet == null) { if (chunk.trainingDataItemIndex != -1) { epochProgressBar.setValue(chunk.trainingDataItemIndex); epochProgressBar.setString(chunk.trainingDataItemIndex + " of 60000"); } } else { System.gc(); System.out.println("Calling GC"); logHeap(); epochFinished(chunk.neuralNet, chunk.epochNum, chunk.MSE); } } } }; worker.execute(); }
From source file:com.mirth.connect.plugins.datapruner.DataPrunerPanel.java
private void updateStatus() { final String workingId = parent.startWorking("Refreshing status..."); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { @Override// www.ja va 2s. c o m protected Void doInBackground() { try { Map<String, String> status = parent.mirthClient.getServlet(DataPrunerServletInterface.class) .getStatusMap(); currentStateTextLabel.setText(status.get("currentState")); currentProcessTextLabel.setText(status.get("currentProcess")); lastProcessTextLabel.setText(status.get("lastProcess")); String nextProcess = "Not scheduled"; if (yesEnabledRadio.isSelected()) { nextProcess = status.get("nextProcess"); } nextProcessTextLabel.setText(nextProcess); if (status.get("isRunning").equals("false")) { currentStateTextLabel.setForeground(INACTIVE_STATUS_COLOR); setStartTaskVisible(true); setStopTaskVisible(false); } else { currentStateTextLabel.setForeground(ACTIVE_STATUS_COLOR); setStartTaskVisible(false); setStopTaskVisible(true); } } catch (ClientException e) { currentStateTextLabel.setText("Unknown"); currentStateTextLabel.setForeground(UNKNOWN_STATUS_COLOR); currentProcessTextLabel.setText(""); lastProcessTextLabel.setText(""); nextProcessTextLabel.setText(""); setStartTaskVisible(false); setStopTaskVisible(false); parent.alertThrowable(parent, e, "An error occurred while attempting to retrieve the status of the data pruner."); } return null; } @Override public void done() { parent.stopWorking(workingId); refreshing.set(false); } }; worker.execute(); }
From source file:com.mirth.connect.client.ui.SettingsPanelServer.java
public boolean doSave() { final ServerSettings serverSettings = getServerSettings(); final UpdateSettings updateSettings = getUpdateSettings(); // Integer queueBufferSize will be null if it was invalid queueBufferSizeField.setBackground(null); if (serverSettings.getQueueBufferSize() == null) { queueBufferSizeField.setBackground(UIConstants.INVALID_COLOR); getFrame().alertWarning(this, "Please enter a valid queue buffer size."); return false; }/* w w w . j av a2s .co m*/ try { String emailAddress = serverSettings.getSmtpFrom(); if (StringUtils.isNotBlank(emailAddress)) { new InternetAddress(emailAddress).validate(); } } catch (Exception e) { PlatformUI.MIRTH_FRAME.alertWarning(PlatformUI.MIRTH_FRAME, "The Default From Address is invalid: " + e.getMessage()); return false; } final String workingId = getFrame().startWorking("Saving " + getTabName() + " settings..."); SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { public Void doInBackground() { try { getFrame().mirthClient.setServerSettings(serverSettings); String serverName = serverNameField.getText(); StringBuilder titleText = new StringBuilder(); StringBuilder statusBarText = new StringBuilder(); statusBarText.append("Connected to: "); if (!StringUtils.isBlank(serverNameField.getText())) { titleText.append(serverName); statusBarText.append(serverName + " | "); PlatformUI.SERVER_NAME = serverNameField.getText(); } else { titleText.append(PlatformUI.SERVER_URL); } titleText.append(" - " + UIConstants.TITLE_TEXT); statusBarText.append(PlatformUI.SERVER_URL); titleText.append(" - (" + PlatformUI.SERVER_VERSION + ")"); getFrame().setTitle(titleText.toString()); getFrame().statusBar.setServerText(statusBarText.toString()); getFrame().mirthClient.setUpdateSettings(updateSettings); } catch (Exception e) { getFrame().alertThrowable(getFrame(), e); } return null; } @Override public void done() { setSaveEnabled(false); getFrame().stopWorking(workingId); } }; worker.execute(); return true; }
From source file:com.enderville.enderinstaller.ui.Installer.java
private void buildInstallingPane() { getNextButton().setEnabled(false);/*from www. j a v a 2 s.c o m*/ getCancelButton().setEnabled(false); getMainPane().removeAll(); getMainPane().setLayout(new MigLayout(new LC().fill())); final JTextArea text = new JTextArea(); text.setEditable(false); getMainPane().add(new JScrollPane(text), new CC().grow().spanY().wrap()); getMainPane().validate(); getMainPane().repaint(); SwingWorker<Object, String> worker = new SwingWorker<Object, String>() { @Override protected Object doInBackground() throws Exception { try { List<String> mods = new ArrayList<String>(); CheckBoxTreeSelectionModel select = getModTree().getCheckBoxTreeSelectionModel(); TreePath[] paths = select.getSelectionPaths(); if (paths != null && paths.length > 0) { for (TreePath path : paths) { DefaultMutableTreeNode node = ((DefaultMutableTreeNode) path.getLastPathComponent()); String mod = (String) node.getUserObject(); if (mod == null) { for (int i = 0; i < node.getChildCount(); i++) { DefaultMutableTreeNode child = (DefaultMutableTreeNode) node.getChildAt(i); mods.add((String) child.getUserObject()); } } else { mods.add(mod); } } } InstallScript.guiInstall(mods, text, getProgressBar()); } catch (Exception e) { LOGGER.error("Error while trying to install mods", e); JOptionPane.showMessageDialog(Installer.this, "Unexpected error while installing mods:\n" + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); setVisible(false); dispose(); } return null; } @Override public void done() { getNextButton().removeActionListener(Installer.this); getNextButton().setText("Done"); getNextButton().addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { setVisible(false); dispose(); } }); getNextButton().setEnabled(true); } }; worker.execute(); }
From source file:com.mirth.connect.client.ui.LibraryResourcesDialog.java
public LibraryResourcesDialog(Channel channel) { super(PlatformUI.MIRTH_FRAME, true); selectedResourceIds = new HashMap<Integer, Set<String>>(); Set<String> channelResourceIds = channel.getProperties().getResourceIds(); if (channelResourceIds == null) { channelResourceIds = new LinkedHashSet<String>(); }// w ww . ja v a 2s . c o m selectedResourceIds.put(null, new LinkedHashSet<String>(channelResourceIds)); Set<String> sourceResourceIds = ((SourceConnectorPropertiesInterface) channel.getSourceConnector() .getProperties()).getSourceConnectorProperties().getResourceIds(); if (sourceResourceIds == null) { sourceResourceIds = new LinkedHashSet<String>(); } selectedResourceIds.put(channel.getSourceConnector().getMetaDataId(), new LinkedHashSet<String>(sourceResourceIds)); for (Connector destinationConnector : channel.getDestinationConnectors()) { Set<String> destinationResourceIds = ((DestinationConnectorPropertiesInterface) destinationConnector .getProperties()).getDestinationConnectorProperties().getResourceIds(); if (destinationResourceIds == null) { destinationResourceIds = new LinkedHashSet<String>(); } selectedResourceIds.put(destinationConnector.getMetaDataId(), new LinkedHashSet<String>(destinationResourceIds)); } initComponents(channel); setPreferredSize(new Dimension(450, 444)); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setTitle("Library Resources"); pack(); setLocationRelativeTo(PlatformUI.MIRTH_FRAME); okButton.setEnabled(false); final String workingId = PlatformUI.MIRTH_FRAME.startWorking("Loading library resources..."); SwingWorker<List<LibraryProperties>, Void> worker = new SwingWorker<List<LibraryProperties>, Void>() { @Override public List<LibraryProperties> doInBackground() throws ClientException { List<ResourceProperties> resourceProperties = PlatformUI.MIRTH_FRAME.mirthClient.getResources(); List<LibraryProperties> libraryProperties = new ArrayList<LibraryProperties>(); for (ResourceProperties resource : resourceProperties) { if (resource instanceof LibraryProperties) { libraryProperties.add((LibraryProperties) resource); } } return libraryProperties; } @Override public void done() { try { List<LibraryProperties> resources = get(); if (resources == null) { resources = new ArrayList<LibraryProperties>(); } Object[][] data = new Object[resources.size()][3]; int i = 0; for (LibraryProperties properties : resources) { data[i][SELECTED_COLUMN] = null; data[i][PROPERTIES_COLUMN] = properties; data[i][TYPE_COLUMN] = properties.getType(); i++; } ((RefreshTableModel) resourceTable.getModel()).refreshDataVector(data); treeTable.getSelectionModel().setSelectionInterval(0, 0); treeTable.getTreeSelectionModel().setSelectionPath(treeTable.getPathForRow(0)); okButton.setEnabled(true); } catch (Throwable t) { if (t instanceof ExecutionException) { t = t.getCause(); } PlatformUI.MIRTH_FRAME.alertThrowable(PlatformUI.MIRTH_FRAME, t, "Error loading library resources: " + t.toString()); } finally { PlatformUI.MIRTH_FRAME.stopWorking(workingId); } } }; worker.execute(); setVisible(true); }
From source file:forge.gui.ImportDialog.java
@SuppressWarnings("serial") public ImportDialog(final String forcedSrcDir, final Runnable onDialogClose) { this.forcedSrcDir = forcedSrcDir; _topPanel = new FPanel(new MigLayout("insets dialog, gap 0, center, wrap, fill")); _topPanel.setOpaque(false);/*from www . j a v a 2s. c om*/ _topPanel.setBackgroundTexture(FSkin.getIcon(FSkinProp.BG_TEXTURE)); isMigration = !StringUtils.isEmpty(forcedSrcDir); // header _topPanel.add(new FLabel.Builder().text((isMigration ? "Migrate" : "Import") + " profile data").fontSize(15) .build(), "center"); // add some help text if this is for the initial data migration if (isMigration) { final FPanel blurbPanel = new FPanel(new MigLayout("insets panel, gap 10, fill")); blurbPanel.setOpaque(false); final JPanel blurbPanelInterior = new JPanel( new MigLayout("insets dialog, gap 10, center, wrap, fill")); blurbPanelInterior.setOpaque(false); blurbPanelInterior.add(new FLabel.Builder().text("<html><b>What's this?</b></html>").build(), "growx, w 50:50:"); blurbPanelInterior.add(new FLabel.Builder() .text("<html>Over the last several years, people have had to jump through a lot of hoops to" + " update to the most recent version. We hope to reduce this workload to a point where a new" + " user will find that it is fairly painless to update. In order to make this happen, Forge" + " has changed where it stores your data so that it is outside of the program installation directory." + " This way, when you upgrade, you will no longer need to import your data every time to get things" + " working. There are other benefits to having user data separate from program data, too, and it" + " lays the groundwork for some cool new features.</html>") .build(), "growx, w 50:50:"); blurbPanelInterior.add( new FLabel.Builder().text("<html><b>So where's my data going?</b></html>").build(), "growx, w 50:50:"); blurbPanelInterior.add(new FLabel.Builder().text( "<html>Forge will now store your data in the same place as other applications on your system." + " Specifically, your personal data, like decks, quest progress, and program preferences will be" + " stored in <b>" + ForgeConstants.USER_DIR + "</b> and all downloaded content, such as card pictures," + " skins, and quest world prices will be under <b>" + ForgeConstants.CACHE_DIR + "</b>. If, for whatever" + " reason, you need to set different paths, cancel out of this dialog, exit Forge, and find the <b>" + ForgeConstants.PROFILE_TEMPLATE_FILE + "</b> file in the program installation directory. Copy or rename" + " it to <b>" + ForgeConstants.PROFILE_FILE + "</b> and edit the paths inside it. Then restart Forge and use" + " this dialog to move your data to the paths that you set. Keep in mind that if you install a future" + " version of Forge into a different directory, you'll need to copy this file over so Forge will know" + " where to find your data.</html>") .build(), "growx, w 50:50:"); blurbPanelInterior.add(new FLabel.Builder().text( "<html><b>Remember, your data won't be available until you complete this step!</b></html>") .build(), "growx, w 50:50:"); final FScrollPane blurbScroller = new FScrollPane(blurbPanelInterior, true, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); blurbPanel.add(blurbScroller, "hmin 150, growy, growx, center, gap 0 0 5 5"); _topPanel.add(blurbPanel, "gap 10 10 20 0, growy, growx, w 50:50:"); } // import source widgets final JPanel importSourcePanel = new JPanel(new MigLayout("insets 0, gap 10")); importSourcePanel.setOpaque(false); importSourcePanel.add(new FLabel.Builder().text("Import from:").build()); _txfSrc = new FTextField.Builder().readonly().build(); importSourcePanel.add(_txfSrc, "pushx, growx"); _btnChooseDir = new FLabel.ButtonBuilder().text("Choose directory...").enabled(!isMigration).build(); final JFileChooser _fileChooser = new JFileChooser(); _fileChooser.setMultiSelectionEnabled(false); _fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); _btnChooseDir.setCommand(new UiCommand() { @Override public void run() { // bring up a file open dialog and, if the OK button is selected, apply the filename // to the import source text field if (JFileChooser.APPROVE_OPTION == _fileChooser.showOpenDialog(JOptionPane.getRootFrame())) { final File f = _fileChooser.getSelectedFile(); if (!f.canRead()) { FOptionPane.showErrorDialog("Cannot access selected directory (Permission denied)."); } else { _txfSrc.setText(f.getAbsolutePath()); } } } }); importSourcePanel.add(_btnChooseDir, "h pref+8!, w pref+12!"); // add change handler to the import source text field that starts up a // new analyzer. it also interacts with the current active analyzer, // if any, to make sure it cancels out before the new one is initiated _txfSrc.getDocument().addDocumentListener(new DocumentListener() { boolean _analyzerActive; // access synchronized on _onAnalyzerDone String prevText; private final Runnable _onAnalyzerDone = new Runnable() { @Override public synchronized void run() { _analyzerActive = false; notify(); } }; @Override public void removeUpdate(final DocumentEvent e) { } @Override public void changedUpdate(final DocumentEvent e) { } @Override public void insertUpdate(final DocumentEvent e) { // text field is read-only, so the only time this will get updated // is when _btnChooseDir does it final String text = _txfSrc.getText(); if (text.equals(prevText)) { // only restart the analyzer if the directory has changed return; } prevText = text; // cancel any active analyzer _cancel = true; if (!text.isEmpty()) { // ensure we don't get two instances of this function running at the same time _btnChooseDir.setEnabled(false); // re-disable the start button. it will be enabled if the previous analyzer has // already successfully finished _btnStart.setEnabled(false); // we have to wait in a background thread since we can't block in the GUI thread final SwingWorker<Void, Void> analyzerStarter = new SwingWorker<Void, Void>() { @Override protected Void doInBackground() throws Exception { // wait for active analyzer (if any) to quit synchronized (_onAnalyzerDone) { while (_analyzerActive) { _onAnalyzerDone.wait(); } } return null; } // executes in gui event loop thread @Override protected void done() { _cancel = false; synchronized (_onAnalyzerDone) { // this will populate the panel with data selection widgets final _AnalyzerUpdater analyzer = new _AnalyzerUpdater(text, _onAnalyzerDone, isMigration); analyzer.run(); _analyzerActive = true; } if (!isMigration) { // only enable the directory choosing button if this is not a migration dialog // since in that case we're permanently locked to the starting directory _btnChooseDir.setEnabled(true); } } }; analyzerStarter.execute(); } } }); _topPanel.add(importSourcePanel, "gaptop 20, pushx, growx"); // prepare import selection panel (will be cleared and filled in later by an analyzer) _selectionPanel = new JPanel(); _selectionPanel.setOpaque(false); _topPanel.add(_selectionPanel, "growx, growy, gaptop 10"); // action button widgets final Runnable cleanup = new Runnable() { @Override public void run() { SOverlayUtils.hideOverlay(); } }; _btnStart = new FButton("Start import"); _btnStart.setEnabled(false); _btnCancel = new FButton("Cancel"); _btnCancel.addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { _cancel = true; cleanup.run(); if (null != onDialogClose) { onDialogClose.run(); } } }); final JPanel southPanel = new JPanel(new MigLayout("ax center")); southPanel.setOpaque(false); southPanel.add(_btnStart, "center, w pref+144!, h pref+12!"); southPanel.add(_btnCancel, "center, w pref+144!, h pref+12!, gap 72"); _topPanel.add(southPanel, "growx"); }