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:edu.ku.brc.specify.dbsupport.cleanuptools.AgentCleanupProcessor.java

/**
 * @param fii/*from   www .  j  a va  2  s.c o m*/
 */
private void doMergeOfAgents(final FindItemInfo fii) {
    prgDlg.setProcess(0, 100);

    System.out.println(String.format("%d : %s - %d", fii.getId(), fii.getValue(), fii.getCount()));

    SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
        @Override
        protected Object doInBackground() throws Exception {
            try {
                doProcessMerge(fii);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return null;
        }

        @Override
        protected void done() {
            if (hasMoreAgents()) {
                nextAgent();
            } else {
                doComplete();
            }
        }
    };
    worker.execute();
}

From source file:de.cismet.verdis.CidsAppBackend.java

/**
 * former synchronized method.//from  w w w.j ava  2 s. c  om
 *
 * @param  kassenzeichen   DOCUMENT ME!
 * @param  edit            DOCUMENT ME!
 * @param  historyEnabled  DOCUMENT ME!
 */
private void gotoKassenzeichen(final String kassenzeichen, final boolean edit, final boolean historyEnabled) {
    final String[] test = kassenzeichen.split(":");

    final String kassenzeichenNummer;
    final String flaechenBez;
    if (test.length > 1) {
        kassenzeichenNummer = test[0];
        flaechenBez = test[1];
    } else {
        kassenzeichenNummer = kassenzeichen;
        flaechenBez = "";
    }

    if (!Main.getInstance().isInEditMode()) {
        Main.getInstance().disableKassenzeichenCmds();
        Main.getInstance().getKassenzeichenPanel().setSearchStarted();
        GrundbuchblattSucheDialog.getInstance().setEnabled(false);
        Main.getInstance().getKassenzeichenPanel().setSearchField(kassenzeichen);

        WaitDialog.getInstance().showDialog();
        WaitDialog.getInstance().startLoadingKassenzeichen(1);

        new SwingWorker<CidsBean, Void>() {

            @Override
            protected CidsBean doInBackground() throws Exception {
                final CidsBean cidsBean = loadKassenzeichenByNummer(Integer.parseInt(kassenzeichenNummer));
                updateCrossReferences(cidsBean);
                return cidsBean;
            }

            @Override
            protected void done() {
                try {
                    final CidsBean cidsBean = get();

                    if (cidsBean != null) {
                        setCidsBean(cidsBean);
                        selectCidsBeanByIdentifier(flaechenBez);
                        Main.getInstance().getKassenzeichenPanel().flashSearchField(Color.GREEN);
                        if (historyEnabled) {
                            historyModel.addToHistory(kassenzeichen);
                        }
                    } else {
                        setCidsBean(null);
                        Main.getInstance().getKassenzeichenPanel().flashSearchField(Color.RED);
                    }
                } catch (final Exception ex) {
                    setCidsBean(null);
                    LOG.error("Exception in Background Thread", ex);
                    Main.getInstance().getKassenzeichenPanel().flashSearchField(Color.RED);
                    showError("Fehler beim Laden", "Kassenzeichen konnte nicht geladen werden", ex);
                }
                Main.getInstance().getKassenzeichenPanel().setSearchFinished();
                GrundbuchblattSucheDialog.getInstance().setEnabled(true);
                Main.getInstance().refreshKassenzeichenButtons();

                WaitDialog.getInstance().progressLoadingKassenzeichen(1);
                if (edit) {
                    new SwingWorker<Boolean, Void>() {

                        @Override
                        protected Boolean doInBackground() throws Exception {
                            if (Main.getInstance().acquireLocks()) { // try to acquire
                                return true;
                            }
                            return null;
                        }

                        @Override
                        protected void done() {
                            try {
                                final Boolean enableEditing = get();
                                if (enableEditing != null) {
                                    Main.getInstance().setEditMode(enableEditing);
                                }
                            } catch (final Exception ex) {
                                LOG.error(ex, ex);
                            } finally {
                                WaitDialog.getInstance().dispose();
                            }
                        }
                    }.execute();
                } else {
                    WaitDialog.getInstance().dispose();
                }
            }
        }.execute();
    } else {
        JOptionPane.showMessageDialog(Main.getInstance(),
                "Das Kassenzeichen kann nur gewechselt werden wenn alle \u00C4nderungen gespeichert oder verworfen worden sind.",
                "Wechseln nicht m\u00F6glich", JOptionPane.WARNING_MESSAGE);
    }
}

From source file:display.containers.FileManager.java

/** Add the files that are contained within the directory of this node.
Thanks to Hovercraft Full Of Eels. */
private void showChildren(final Path node) {
    //tree.setEnabled(false);

    SwingWorker<Void, File> worker = new SwingWorker<Void, File>() {
        @Override//  www . ja  v  a 2 s  .c  o m
        public Void doInBackground() {
            table.setEnabled(false);
            File file = (File) node.toFile();
            setCurrentDir(file);
            if (file.isDirectory()) {
                File[] files = fileSystemView.getFiles(file, !UserProfile.SHOW_HIDDEN_FILES); //!!
                File[] filesTemp = new File[files.length + 1];
                File[] filesWithParent;
                filesTemp[0] = new File(file.getAbsolutePath() + "/..");
                for (int i = 1; i < filesTemp.length; i++) {
                    filesTemp[i] = files[i - 1];
                }
                switch (getMode()) {
                case 1:
                    List<File> list = new ArrayList<File>();
                    if (file.toPath().equals(SystemSettings.SERVER_INFO.getServerDir())) {
                        for (File fi : filesTemp) {
                            for (Project p : UserProfile.CURRENT_USER.getProjects()) {
                                if ((ServerInfo.WORKSPACE_PREFIXE + p.getNom()).equals(fi.getName())) {
                                    list.add(fi);
                                }
                            }
                        }
                        filesWithParent = list.toArray(new File[list.size()]);
                    } else {
                        filesWithParent = filesTemp;
                    }

                    break;
                case 2:
                    List<File> list2 = new ArrayList<File>();
                    if (file.toPath().equals(SystemSettings.SERVER_INFO.getServerDir())) {
                        for (File fi : filesTemp) {
                            if (fi.getName().equals(ServerInfo.NRI_DICOM_NAME)
                                    || fi.getName().equals(ServerInfo.NRI_ANALYSE_NAME)) {
                                list2.add(fi);
                            }
                        }
                        filesWithParent = list2.toArray(new File[list2.size()]);
                    } else {
                        filesWithParent = filesTemp;
                    }
                    break;
                default:
                    filesWithParent = filesTemp;
                }
                if (filesWithParent != null) {
                    setTableData(filesWithParent);
                }
            }
            return null;
        }
    };
    worker.execute();
}

From source file:edu.ku.brc.specify.dbsupport.cleanuptools.AgentCleanupProcessor.java

/**
 * //w  w w . ja va2s.c  om
 */
private void processNextAgent(final FindItemInfo fii) {
    SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() {
        private boolean doSkip = false;

        @Override
        protected Object doInBackground() throws Exception {
            if (outputRows[0].length() > 0) {
                tblWriter.logObjRowVAlign(outputRows, "top");
            }
            for (StringBuilder sb : outputRows) {
                sb.setLength(0);
            }
            updCnt = 0;

            outputRows[0].append(getAgentStr(fii.getId()));
            for (Integer agentID : fii.getDuplicateIds()) {
                if (outputRows[1].length() > 0)
                    outputRows[1].append("<BR>");
                outputRows[1].append(getAgentStr(agentID));
            }

            if (isGroupOK(fii) && isRolesOK(fii) && isCollectorsOK(fii) && isFundingAgentOK(fii)
                    && isVariantOK(fii)) {
                if (usedIds == null || !usedIds.contains(fii.getId())) {
                    int numLeft = fii.cleanDuplicateIds(usedIds);
                    if (numLeft > 0) {
                        checkForAddrs(fii); // this calls doMergeOfAgents
                    } else {
                        doMergeOfAgents(fii);
                    }
                } else {
                    doMergeOfAgents(fii);
                }
            } else {
                doSkip = true;
            }
            currIndex++;
            return null;
        }

        @Override
        protected void done() {
            prgDlg.setOverall(currIndex);
            if (doSkip) {
                if (hasMoreAgents()) {
                    nextAgent();
                } else {
                    doComplete();
                }
            }
        }
    };
    worker.execute();
}

From source file:net.sourceforge.atunes.kernel.modules.repository.RepositoryHandler.java

/**
 * Imports folders passed as argument to repository
 * //from www .j av  a 2  s .co  m
 * @param folders
 * @param path
 */
private void importFolders(final List<File> folders, final String path) {
    SwingWorker<List<AudioFile>, Void> worker = new SwingWorker<List<AudioFile>, Void>() {
        @Override
        protected List<AudioFile> doInBackground() throws Exception {
            VisualHandler.getInstance().showIndeterminateProgressDialog(
                    StringUtils.getString(LanguageTool.getString("READING_FILES_TO_IMPORT"), "..."));
            return RepositoryLoader.getSongsForFolders(folders);
        }

        @Override
        protected void done() {
            super.done();
            VisualHandler.getInstance().hideIndeterminateProgressDialog();

            try {
                final List<AudioFile> filesToLoad = get();

                TagAttributesReviewed tagAttributesReviewed = null;
                // Review tags if selected in settings
                if (ApplicationState.getInstance().isReviewTagsBeforeImport()) {
                    ReviewImportDialog reviewImportDialog = VisualHandler.getInstance().getReviewImportDialog();
                    reviewImportDialog.show(folders, filesToLoad);
                    if (reviewImportDialog.isDialogCancelled()) {
                        return;
                    }
                    tagAttributesReviewed = reviewImportDialog.getResult();
                }

                final ImportFilesProcess process = new ImportFilesProcess(filesToLoad, folders, path,
                        tagAttributesReviewed);
                process.addProcessListener(new ProcessListener() {
                    @Override
                    public void processCanceled() {
                        // Nothing to do, files copied will be removed before calling this method 
                    }

                    @Override
                    public void processFinished(final boolean ok) {
                        if (!ok) {
                            try {
                                SwingUtilities.invokeAndWait(new Runnable() {
                                    @Override
                                    public void run() {
                                        VisualHandler.getInstance().showErrorDialog(
                                                LanguageTool.getString("ERRORS_IN_IMPORT_PROCESS"));
                                    }
                                });
                            } catch (InterruptedException e) {
                                // Do nothing
                            } catch (InvocationTargetException e) {
                                // Do nothing
                            }
                        } else {
                            // If import is ok then add files to repository
                            addFilesAndRefresh(process.getFilesTransferred());
                        }
                    }
                });
                process.execute();

            } catch (InterruptedException e) {
                getLogger().error(LogCategories.REPOSITORY, e);
            } catch (ExecutionException e) {
                getLogger().error(LogCategories.REPOSITORY, e);
            }
        }
    };
    worker.execute();
}

From source file:com.xilinx.kintex7.MainScreen.java

private JPanel testPanelItems1() {
    JPanel panel = new JPanel();
    panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
    /*panel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("Test Parameters-1"),
                BorderFactory.createEmptyBorder()));*/
    float w = (float) ((float) width * 0.4);
    //panel.setPreferredSize(new Dimension((int)w, 100));
    panel.add(new JLabel("Data Path-1:"));
    t2_o1 = new JCheckBox("Loopback");
    if (mode == LandingPage.PERFORMANCE_MODE_GENCHK || mode == LandingPage.PERFORMANCE_MODE_GENCHK_DV)
        t2_o1.setToolTipText("This loops back software generated traffic at DMA user interface");
    else if (mode == LandingPage.PERFORMANCE_MODE_RAW || mode == LandingPage.PERFORMANCE_MODE_RAW_DV)
        t2_o1.setToolTipText("This loops back software generated raw Ethernet frames at 10G PHY");

    t2_o1.setSelected(true);/*from   w  w  w. j a va2s .  co m*/
    t2_o1.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (mode == LandingPage.PERFORMANCE_MODE_RAW || mode == LandingPage.PERFORMANCE_MODE_RAW_DV) {
                t2_o1.setSelected(true);
                return;
            }
            if (t2_o1.isSelected()) {
                // disable others
                test2_option = DriverInfo.ENABLE_LOOPBACK;
                t2_o2.setSelected(false);
                t2_o3.setSelected(false);
            } else {
                if (!t2_o2.isSelected() && !t2_o3.isSelected()) {
                    test2_option = DriverInfo.CHECKER;
                    t2_o2.setSelected(true);
                }
            }
        }
    });
    //b1.setSelected(true);
    t2_o2 = new JCheckBox("HW Checker");
    if (mode == LandingPage.PERFORMANCE_MODE_GENCHK || mode == LandingPage.PERFORMANCE_MODE_GENCHK_DV)
        t2_o2.setToolTipText(
                "This enables Checker in hardware at DMA user interface verifying traffic generated by software");
    t2_o2.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (t2_o2.isSelected()) {
                // disable others
                test2_option = DriverInfo.CHECKER;
                t2_o1.setSelected(false);
                //t2_o3.setSelected(false);
                if (t2_o3.isSelected())
                    test2_option = DriverInfo.CHECKER_GEN;
            } else {
                if (t2_o3.isSelected())
                    test2_option = DriverInfo.GENERATOR;
                else {
                    test2_option = DriverInfo.ENABLE_LOOPBACK;
                    t2_o1.setSelected(true);
                }
            }
        }
    });
    //b2.setEnabled(false);
    t2_o3 = new JCheckBox("HW Generator");
    if (mode == LandingPage.PERFORMANCE_MODE_GENCHK || mode == LandingPage.PERFORMANCE_MODE_GENCHK_DV)
        t2_o3.setToolTipText("This enables traffic generator in hardware at the DMA user interface");
    t2_o3.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            if (t2_o3.isSelected()) {
                // disable others
                test2_option = DriverInfo.GENERATOR;
                t2_o1.setSelected(false);
                //t2_o2.setSelected(false);
                if (t2_o2.isSelected())
                    test2_option = DriverInfo.CHECKER_GEN;
            } else {
                if (t2_o2.isSelected())
                    test2_option = DriverInfo.CHECKER;
                else {
                    test2_option = DriverInfo.ENABLE_LOOPBACK;
                    t2_o1.setSelected(true);
                }
            }
        }
    });
    //b3.setEnabled(false);
    JPanel ip = new JPanel();
    ip.setLayout(new BoxLayout(ip, BoxLayout.PAGE_AXIS));
    ip.add(t2_o1);
    ip.add(t2_o2);
    ip.add(t2_o3);
    panel.add(ip);
    panel.add(new JLabel("Packet Size (bytes):"));
    t2_psize = new JTextField("32768", 5);
    panel.add(t2_psize);
    stest = new JButton("Start");
    stest.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {

            //Check for led status and start the test
            if (mode == LandingPage.PERFORMANCE_MODE_RAW || mode == LandingPage.PERFORMANCE_MODE_RAW_DV) {
                if (lstats.ddrCalib == LED_OFF && (lstats.phy0 == LED_ON && lstats.phy1 == LED_ON)) {
                    JOptionPane.showMessageDialog(null, "DDR3 is not calibrated. Test cannot be started",
                            "Error", JOptionPane.ERROR_MESSAGE);
                    return;
                } else if (lstats.ddrCalib == LED_OFF && (lstats.phy0 == LED_OFF || lstats.phy1 == LED_OFF)) {
                    JOptionPane.showMessageDialog(null,
                            "DDR3 is not calibrated and 10G-PHY link is down. Test cannot be started", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                } else if (lstats.ddrCalib == LED_ON && (lstats.phy0 == LED_OFF || lstats.phy1 == LED_OFF)) {
                    JOptionPane.showMessageDialog(null, "10G-PHY link is down. Test cannot be started", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }
            }
            if (stest.getText().equals("Start")) {
                int psize = 0;
                dataMismatch2 = errcnt1 = false;
                try {
                    psize = Integer.parseInt(t2_psize.getText());
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Only Natural numbers are allowed", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }
                if (psize < minpkt1 || psize > maxpkt1) {
                    JOptionPane.showMessageDialog(null,
                            "Packet size must be within " + minpkt1 + " to " + maxpkt1 + " bytes", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }
                di.startTest(1, test2_option, psize);
                t2_o1.setEnabled(false);
                t2_o2.setEnabled(false);
                t2_o3.setEnabled(false);
                t2_psize.setEnabled(false);
                stest.setText("Stop");
                testStarted1 = true;
                updateLog("[Test Started for Data Path-1]", logStatus);

            } else if (stest.getText().equals("Stop")) {
                // Disable button to avoid multiple clicks
                stest.setEnabled(false);
                SwingWorker worker = new SwingWorker<Void, Void>() {

                    @Override
                    protected Void doInBackground() throws Exception {
                        try {
                            stopTest2();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                };
                worker.execute();
            }
        }
    });
    panel.add(stest);
    if ((mode == LandingPage.APPLICATION_MODE) || (mode == LandingPage.APPLICATION_MODE_P2P)) {
        t2_o1.setSelected(false);
        t2_o2.setSelected(false);
        t2_o3.setSelected(false);
        t2_o1.setEnabled(false);
        t2_o2.setEnabled(false);
        t2_o3.setEnabled(false);
        t2_psize.setEnabled(false);
        t2_psize.setText("");
        stest.setEnabled(false);
    }
    return panel;
}

From source file:ca.uviccscu.lp.server.main.MainFrame.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    l.info("Add game action activated");
    MainFrame.lockInterface();//from  w ww .  ja va  2s.co  m
    MainFrame.updateTask("Adding game...", true);
    AddGameDialog addGameDialog = new AddGameDialog(this, true);
    addGameDialog.setLocationRelativeTo(null);
    //addGameDialog.setVisible(true);
    final Game g = addGameDialog.popupCreateDialog();
    if (g != null) {
        l.trace("Analyzing game: " + g.gameAbsoluteFolderPath);
        MainFrame.updateTask("Adding game...", true);
        final int row = getNextFreeRowNumber();
        addFreeRow();
        jTable1.getModel().setValueAt(g.gameName, row, 0);
        jTable1.getModel().setValueAt(g.gameAbsoluteExecPath, row, 1);
        jTable1.getModel().setValueAt(GamelistStorage.gameStatusToString(g.gameStatus), row, 3);
        MainFrame.updateProgressBar(0, 0, 0, "Analyzing game", true, true);
        final ObjectPlaceholder obj = new ObjectPlaceholder();
        SwingWorker worker = new SwingWorker<Long, Void>() {

            @Override
            public Long doInBackground() throws IOException {
                l.trace("Checking size");
                MainFrame.updateProgressBar(0, 0, 0, "Analyzing game size", true, true);
                obj.payload = FileUtils.sizeOfDirectory(new File(g.gameAbsoluteFolderPath));
                l.trace("Checking files");
                MainFrame.updateProgressBar(0, 0, 0, "Analyzing game files", true, true);
                g.gameFileNumber = FileUtils.listFiles(new File(g.gameAbsoluteFolderPath), null, true).size();
                l.trace("Checking CRC32");
                MainFrame.updateProgressBar(0, 0, 0, "Analyzing game signature", true, true);
                g.gameExecCRC32 = FileUtils.checksumCRC32(new File(g.gameAbsoluteExecPath));
                return ((Long) obj.payload);
            }

            public void done() {
                l.trace("Finishing game check");
                MainFrame.updateProgressBar(0, 0, 0, "Finishing game creation", false, false);
                g.gameSize = ((Long) obj.payload);
                /*
                double mbsize = Math.ceil(g.gameSize / (1024 * 1024));
                jTable1.getModel().setValueAt(mbsize, row, 2);
                 * 
                 */
                jTable1.getModel().setValueAt(FileUtils.byteCountToDisplaySize(g.gameSize), row, 2);
                Shared.lastCreatedGame = null;
                GamelistStorage.addGame(g);
                jTable1.getModel().setValueAt(GamelistStorage.gameStatusToString(g.gameStatus), row, 3);
                g.gameStatus = 0;
                SettingsManager.getStorage().storeGame(g);
                /*
                try {
                SettingsManager.storeCurrentSettings();
                } catch (Exception ex) {
                l.debug(ex.getMessage(), ex);
                }
                 * 
                 */
                l.trace("Done adding game");
                MainFrame.setReportingIdle();
                MainFrame.unlockInterface();
            }
        };
        worker.execute();
    } else {
        l.debug("Add game dialog - null game returned, nothing done");
        MainFrame.setReportingIdle();
        MainFrame.unlockInterface();
    }
    MainFrame.updateGameInterfaceFromStorage();
}

From source file:fi.hoski.remote.ui.Admin.java

private JMenuItem menuItemSync() {
    JMenuItem syncItem = new JMenuItem();
    TextUtil.populate(syncItem, "SYNCHRONIZE");
    ActionListener syncAction = new ActionListener() {

        @Override/*from w w w  .j  av a2s  .  co  m*/
        public void actionPerformed(ActionEvent e) {
            SwingWorker task = new SwingWorker<Void, Void>() {

                @Override
                protected Void doInBackground() throws Exception {
                    Progress progress = new UIProgress(frame, TextUtil.getText("SYNCHRONIZE"));
                    progress.setNote("");
                    try {
                        dss.synchronize(progress);
                    } catch (Throwable ex) {
                        progress.close();
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(frame, ex.getMessage());
                    }
                    return null;
                }
            };
            task.execute();
        }
    };
    syncAction = createActionListener(frame, syncAction);
    syncItem.addActionListener(syncAction);
    return syncItem;
}

From source file:com.josescalia.tumblr.form.PreferenceForm.java

private void btnCleanLogActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCleanLogActionPerformed
    frame = (MainFrame) this.getTopLevelAncestor();
    if (UIAlert.showConfirm(this, "Are you sure ?") == JOptionPane.OK_OPTION) {
        logger.info("deleting log file");
        //busy cursor and progress bar
        frame.setCursor(new Cursor(Cursor.WAIT_CURSOR));
        frame.startProgressBar("Deleting");

        //background process
        new SwingWorker<String, String>() {
            @Override/*from   www. java  2 s. c o  m*/
            protected String doInBackground() throws Exception {
                int successDeleteCount = 0;
                int failedDeleteCount = 0;
                for (File file : logFile.getFileList()) {
                    logger.info(file.getName());
                    if (!file.getName().equalsIgnoreCase(Bootstrap.applicationLog)
                            && !file.getName().equalsIgnoreCase(Bootstrap.applicationErrorLog)) {
                        if (file.delete()) {
                            successDeleteCount++;
                        } else {
                            failedDeleteCount++;
                        }
                    }
                }
                return "Done\n " + successDeleteCount + " log file(s) deleted\n" + failedDeleteCount
                        + " log file(s) not deleted";
            }

            @Override
            protected void done() {
                try {
                    UIAlert.showInformation(null, get());
                } catch (InterruptedException e) {
                    logger.error(e);
                } catch (ExecutionException e) {
                    logger.error(e);
                }
                setupLogFileInfo();
                frame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                frame.stopProgressBar("");
            }
        }.execute();
    }

}

From source file:ca.uviccscu.lp.server.main.MainFrame.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    l.info("Edit game action activated");
    MainFrame.lockInterface();//from   ww w.ja v a2s .c o m
    MainFrame.updateTask("Editing game...", true);
    l.info("Starting game edit action");
    DefaultTableModel mdl = (DefaultTableModel) jTable1.getModel();
    final int row = jTable1.getSelectedRow();
    if (row >= 0 && mdl.getValueAt(row, 0) != null) {
        AddGameDialog addGameDialog = new AddGameDialog(this, true);
        addGameDialog.setLocationRelativeTo(null);
        //addGameDialog.setVisible(true);
        final Game temp = GamelistStorage.getGame((String) mdl.getValueAt(row, 0));
        final Game g = addGameDialog.popupEditDialog(temp);
        if (g != null) {
            l.trace("Edit done, checking for changes");
            //l.trace("Calculating folder size: " + g.gameAbsoluteFolderPath);
            MainFrame.updateTask("Checking for changes...", true);
            MainFrame.updateGameInterfaceFromStorage();
            boolean changed = true;
            if (temp.gameAbsoluteExecPath.equals(g.gameAbsoluteExecPath)
                    && temp.gameAbsoluteFolderPath.equals(g.gameAbsoluteFolderPath)) {
                l.trace("Location same - assuming no changes made");
                g.gameName = temp.gameName;
                g.gameBatCommands = temp.gameBatCommands;
                g.gamePName = temp.gamePName;
                g.gamePUser = temp.gamePUser;
                g.gamePWName = temp.gamePWName;
                g.gameRuntimeFlags = temp.gameRuntimeFlags;
                changed = false;
            } else {
                l.trace("Locations changed - rescanning the game");
                g.gameStatus = 0;
                MainFrame.updateProgressBar(0, 0, 0, "Calculating game size", true, true);
                final ObjectPlaceholder obj = new ObjectPlaceholder();
                SwingWorker worker = new SwingWorker<Long, Void>() {

                    @Override
                    public Long doInBackground() throws IOException {
                        MainFrame.lockInterface();
                        l.trace("Checking size");
                        MainFrame.updateProgressBar(0, 0, 0, "Analyzing game size", true, true);
                        obj.payload = FileUtils.sizeOfDirectory(new File(g.gameAbsoluteFolderPath));
                        l.trace("Checking files");
                        MainFrame.updateProgressBar(0, 0, 0, "Analyzing game files", true, true);
                        g.gameFileNumber = FileUtils.listFiles(new File(g.gameAbsoluteFolderPath), null, true)
                                .size();
                        l.trace("Checking CRC32");
                        MainFrame.updateProgressBar(0, 0, 0, "Analyzing game signature", true, true);
                        g.gameExecCRC32 = FileUtils.checksumCRC32(new File(g.gameAbsoluteExecPath));
                        return ((Long) obj.payload);
                    }

                    @Override
                    public void done() {
                        l.trace("Finishing game check");
                        MainFrame.updateProgressBar(0, 0, 0, "Finishing game edit", false, false);
                        g.gameSize = ((Long) obj.payload);
                        /*
                        double mbsize = Math.ceil(g.gameSize / (1024 * 1024));
                        jTable1.getModel().setValueAt(mbsize, row, 2);
                         *
                         */
                        g.copyTo(temp);
                        Shared.lastCreatedGame = null;
                        l.trace("Done editing game");
                        MainFrame.updateGameInterfaceFromStorage();
                        MainFrame.unlockInterface();
                        MainFrame.setReportingIdle();
                    }
                };
                worker.execute();
            }
            //we are trusting the size task to finish here ELSE TROUBLE
            /*
            GamelistStorage.removeGame(temp.gameName);
            GamelistStorage.addGame(g);
             * 
             */
            if (!changed) {
                MainFrame.unlockInterface();
                MainFrame.setReportingIdle();
            }
            MainFrame.updateGameInterfaceFromStorage();
        } else {
            MainFrame.unlockInterface();
            MainFrame.setReportingIdle();
            MainFrame.updateGameInterfaceFromStorage();
        }
    } else {
        l.trace("Game edit - bad selection or empty table");
        JOptionPane.showMessageDialog(this, "Invalid selection - can't edit", "Edit error",
                JOptionPane.WARNING_MESSAGE);
        MainFrame.unlockInterface();
        MainFrame.setReportingIdle();
        MainFrame.updateGameInterfaceFromStorage();
    }
}