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.config.init.PrintTableHelper.java

/**
 * @param table/* w ww. j a  v  a 2  s  .com*/
 * @param pageTitle
 */
public void printGrid(final String pageTitle) {
    final PageSetupDlg pageSetup = new PageSetupDlg();
    pageSetup.createUI();
    pageSetup.setPageTitle(pageTitle);

    pageSetup.setVisible(true);
    if (pageSetup.isCancelled()) {
        return;
    }

    UIRegistry.writeSimpleGlassPaneMsg(getResourceString("JasperReportFilling"), 24);

    SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() {
        protected JasperPrint jp = null;

        /* (non-Javadoc)
         * @see javax.swing.SwingWorker#doInBackground()
         */
        @Override
        protected Integer doInBackground() throws Exception {
            if (printTable != null) {
                try {
                    DynamicReport dr = buildReport(printTable.getModel(), pageSetup);
                    JRDataSource ds = new JRTableModelDataSource(printTable.getModel());
                    jp = DynamicJasperHelper.generateJasperPrint(dr, new ClassicLayoutManager(), ds);

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void done() {
            super.done();

            UIRegistry.clearSimpleGlassPaneMsg();

            if (jp != null) {
                reportFinished(jp, pageTitle);
            }
        }
    };

    backupWorker.execute();
}

From source file:com.tascape.qa.th.android.driver.App.java

/**
 * The method starts a GUI to let an user inspect element tree and take screenshot when the user is interacting
 * with the app-under-test manually. Please make sure to set timeout long enough for manual interaction.
 *
 * @param timeoutMinutes timeout in minutes to fail the manual steps
 *
 * @throws Exception if case of error/*from w ww . j  a v  a2 s.c  om*/
 */
public void interactManually(int timeoutMinutes) throws Exception {
    LOG.info("Start manual UI interaction");
    long end = System.currentTimeMillis() + timeoutMinutes * 60000L;

    AtomicBoolean visible = new AtomicBoolean(true);
    AtomicBoolean pass = new AtomicBoolean(false);
    String tName = Thread.currentThread().getName() + "m";
    SwingUtilities.invokeLater(() -> {
        JDialog jd = new JDialog((JFrame) null, "Manual Device UI Interaction - " + device.getProductDetail());
        jd.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);

        JPanel jpContent = new JPanel(new BorderLayout());
        jd.setContentPane(jpContent);
        jpContent.setPreferredSize(new Dimension(1088, 828));
        jpContent.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        JPanel jpInfo = new JPanel();
        jpContent.add(jpInfo, BorderLayout.PAGE_START);
        jpInfo.setLayout(new BorderLayout());
        {
            JButton jb = new JButton("PASS");
            jb.setForeground(Color.green.darker());
            jb.setFont(jb.getFont().deriveFont(Font.BOLD));
            jpInfo.add(jb, BorderLayout.LINE_START);
            jb.addActionListener(event -> {
                pass.set(true);
                jd.dispose();
                visible.set(false);
            });
        }
        {
            JButton jb = new JButton("FAIL");
            jb.setForeground(Color.red);
            jb.setFont(jb.getFont().deriveFont(Font.BOLD));
            jpInfo.add(jb, BorderLayout.LINE_END);
            jb.addActionListener(event -> {
                pass.set(false);
                jd.dispose();
                visible.set(false);
            });
        }

        JLabel jlTimeout = new JLabel("xxx seconds left", SwingConstants.CENTER);
        jpInfo.add(jlTimeout, BorderLayout.CENTER);
        jpInfo.add(jlTimeout, BorderLayout.CENTER);
        new SwingWorker<Long, Long>() {
            @Override
            protected Long doInBackground() throws Exception {
                while (System.currentTimeMillis() < end) {
                    Thread.sleep(1000);
                    long left = (end - System.currentTimeMillis()) / 1000;
                    this.publish(left);
                }
                return 0L;
            }

            @Override
            protected void process(List<Long> chunks) {
                Long l = chunks.get(chunks.size() - 1);
                jlTimeout.setText(l + " seconds left");
                if (l < 850) {
                    jlTimeout.setForeground(Color.red);
                }
            }
        }.execute();

        JPanel jpResponse = new JPanel(new BorderLayout());
        JPanel jpProgress = new JPanel(new BorderLayout());
        jpResponse.add(jpProgress, BorderLayout.PAGE_START);

        JTextArea jtaJson = new JTextArea();
        jtaJson.setEditable(false);
        jtaJson.setTabSize(4);
        Font font = jtaJson.getFont();
        jtaJson.setFont(new Font("Courier New", font.getStyle(), font.getSize()));

        JTree jtView = new JTree();

        JTabbedPane jtp = new JTabbedPane();
        jtp.add("tree", new JScrollPane(jtView));
        jtp.add("json", new JScrollPane(jtaJson));

        jpResponse.add(jtp, BorderLayout.CENTER);

        JPanel jpScreen = new JPanel();
        jpScreen.setMinimumSize(new Dimension(200, 200));
        jpScreen.setLayout(new BoxLayout(jpScreen, BoxLayout.PAGE_AXIS));
        JScrollPane jsp1 = new JScrollPane(jpScreen);
        jpResponse.add(jsp1, BorderLayout.LINE_START);

        JPanel jpJs = new JPanel(new BorderLayout());
        JTextArea jtaJs = new JTextArea();
        jpJs.add(new JScrollPane(jtaJs), BorderLayout.CENTER);

        JSplitPane jSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, jpResponse, jpJs);
        jSplitPane.setResizeWeight(0.88);
        jpContent.add(jSplitPane, BorderLayout.CENTER);

        JPanel jpLog = new JPanel();
        jpLog.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0));
        jpLog.setLayout(new BoxLayout(jpLog, BoxLayout.LINE_AXIS));

        JCheckBox jcbTap = new JCheckBox("Enable Click", null, false);
        jpLog.add(jcbTap);
        jpLog.add(Box.createHorizontalStrut(8));

        JButton jbLogUi = new JButton("Log Screen");
        jpResponse.add(jpLog, BorderLayout.PAGE_END);
        {
            jpLog.add(jbLogUi);
            jbLogUi.addActionListener((ActionEvent event) -> {
                jtaJson.setText("waiting for screenshot...");
                Thread t = new Thread(tName) {
                    @Override
                    public void run() {
                        LOG.debug("\n\n");
                        try {
                            WindowHierarchy wh = device.loadWindowHierarchy();
                            jtView.setModel(getModel(wh));

                            jtaJson.setText("");
                            jtaJson.append(wh.root.toJson().toString(2));
                            jtaJson.append("\n");

                            File png = device.takeDeviceScreenshot();
                            BufferedImage image = ImageIO.read(png);

                            int w = device.getDisplayWidth();
                            int h = device.getDisplayHeight();

                            BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
                            Graphics2D g2 = resizedImg.createGraphics();
                            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                    RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                            g2.drawImage(image, 0, 0, w, h, null);
                            g2.dispose();

                            JLabel jLabel = new JLabel(new ImageIcon(resizedImg));
                            jpScreen.removeAll();
                            jsp1.setPreferredSize(new Dimension(w + 30, h));
                            jpScreen.add(jLabel);

                            jLabel.addMouseListener(new MouseAdapter() {
                                @Override
                                public void mouseClicked(MouseEvent e) {
                                    LOG.debug("clicked at {},{}", e.getPoint().getX(), e.getPoint().getY());
                                    if (jcbTap.isSelected()) {
                                        device.click(e.getPoint().x, e.getPoint().y);
                                        device.waitForIdle();
                                        jbLogUi.doClick();
                                    }
                                }
                            });
                        } catch (Exception ex) {
                            LOG.error("Cannot log screen", ex);
                            jtaJson.append("Cannot log screen");
                        }
                        jtaJson.append("\n\n\n");
                        LOG.debug("\n\n");

                        jd.setSize(jd.getBounds().width + 1, jd.getBounds().height + 1);
                        jd.setSize(jd.getBounds().width - 1, jd.getBounds().height - 1);
                    }
                };
                t.start();
            });
        }
        jpLog.add(Box.createHorizontalStrut(38));
        {
            JButton jbLogMsg = new JButton("Log Message");
            jpLog.add(jbLogMsg);
            JTextField jtMsg = new JTextField(10);
            jpLog.add(jtMsg);
            jtMsg.addFocusListener(new FocusListener() {
                @Override
                public void focusLost(final FocusEvent pE) {
                }

                @Override
                public void focusGained(final FocusEvent pE) {
                    jtMsg.selectAll();
                }
            });
            jtMsg.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(java.awt.event.KeyEvent e) {
                    if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
                        jbLogMsg.doClick();
                    }
                }
            });
            jbLogMsg.addActionListener(event -> {
                Thread t = new Thread(tName) {
                    @Override
                    public void run() {
                        String msg = jtMsg.getText();
                        if (StringUtils.isNotBlank(msg)) {
                            LOG.info("{}", msg);
                            jtMsg.selectAll();
                        }
                    }
                };
                t.start();
                try {
                    t.join();
                } catch (InterruptedException ex) {
                    LOG.error("Cannot take screenshot", ex);
                }
                jtMsg.requestFocus();
            });
        }
        jpLog.add(Box.createHorizontalStrut(38));
        {
            JButton jbClear = new JButton("Clear");
            jpLog.add(jbClear);
            jbClear.addActionListener(event -> {
                jtaJson.setText("");
            });
        }

        JPanel jpAction = new JPanel();
        jpContent.add(jpAction, BorderLayout.PAGE_END);
        jpAction.setLayout(new BoxLayout(jpAction, BoxLayout.LINE_AXIS));
        jpJs.add(jpAction, BorderLayout.PAGE_END);

        jd.pack();
        jd.setVisible(true);
        jd.setLocationRelativeTo(null);

        jbLogUi.doClick();
    });

    while (visible.get()) {
        if (System.currentTimeMillis() > end) {
            LOG.error("Manual UI interaction timeout");
            break;
        }
        Thread.sleep(500);
    }

    if (pass.get()) {
        LOG.info("Manual UI Interaction returns PASS");
    } else {
        Assert.fail("Manual UI Interaction returns FAIL");
    }
}

From source file:com.hammurapi.jcapture.CaptureFrame.java

protected void capture() throws Exception {
    try {// w w  w  .ja  v a 2  s  . com
        Thread.sleep(200); // For Ubuntu.
    } catch (InterruptedException ie) {
        // Ignore
    }

    BufferedImage screenShot = captureConfig.createScreenShot(null, null).call().getRegions().get(0).getImage()
            .getImage();

    String prefix = getDatePrefix();

    String defaultImageFormat = applet.getParameter("imageFormat");
    if (defaultImageFormat == null || defaultImageFormat.trim().length() == 0) {
        defaultImageFormat = "PNG";
    }
    final String defaultFileExtension = defaultImageFormat.toLowerCase();

    final String fileName = JOptionPane.showInputDialog(CaptureFrame.this, "Upload as",
            applet.getParameter("pageName") + "-capture-" + prefix + "-" + nextCounter() + "."
                    + defaultFileExtension);
    if (fileName != null) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int idx = fileName.lastIndexOf('.');
            String imageFormat = idx == -1 ? defaultImageFormat : fileName.substring(idx + 1).toUpperCase();
            ImageIO.write(screenShot, imageFormat, baos);
            final byte[] imageBytes = baos.toByteArray();
            System.out.println("Image size: " + imageBytes.length);
            // Uploading
            SwingWorker<Boolean, Long> task = new SwingWorker<Boolean, Long>() {

                @Override
                protected Boolean doInBackground() throws Exception {

                    System.out.println("Uploading in background");
                    try {
                        HttpResponse iResponse = applet.post(CaptureFrame.this,
                                new ByteArrayInputStream(imageBytes), imageBytes.length, fileName,
                                "application/octet-stream");

                        System.out.println("Response status line: " + iResponse.getStatusLine());
                        if (iResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                            errorMessage = iResponse.getStatusLine();
                            errorTitle = "Error saving image";
                            return false;
                        }
                        return true;
                    } catch (Error e) {
                        errorMessage = e.toString();
                        errorTitle = "Upload error";
                        e.printStackTrace();
                        return false;
                    }
                }

                private Object errorMessage;
                private String errorTitle;

                protected void done() {
                    try {
                        if (get()) {
                            JSObject window = JSObject.getWindow(applet);
                            String toEval = "insertAtCarret('" + applet.getParameter("edid") + "','{{:"
                                    + fileName + "|}}')";
                            System.out.println("Evaluating: " + toEval);
                            window.eval(toEval);
                            CaptureFrame.this.setVisible(false);
                        } else {
                            JOptionPane.showMessageDialog(CaptureFrame.this, errorMessage, errorTitle,
                                    JOptionPane.ERROR_MESSAGE);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        JOptionPane.showMessageDialog(CaptureFrame.this, e.toString(), "Exception",
                                JOptionPane.ERROR_MESSAGE);
                    }
                };

            };

            task.execute();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(applet, ex.toString(), "Error saving image",
                    JOptionPane.ERROR_MESSAGE);
        }
    }
}

From source file:es.emergya.ui.plugins.admin.aux1.SummaryAction.java

@Override
public void actionPerformed(ActionEvent e) {
    // Utilizamos un lock sobre el objeto para evitar abrir varias fichas
    // del mismo objeto ya que las acciones a realizar se lanzan en un
    // SwingWorker
    // sobre el que no tenemos garantizado el instante de ejecucin, lo que
    // puede hacer que se llame varias veces a getSummaryDialog().
    synchronized (this) {
        if (abriendo) {
            if (log.isTraceEnabled()) {
                log.trace("Ya hay otra ventana " + this.getClass().getName() + " abrindose...");
            }/* www.ja v  a2 s  .  c  o m*/

            return;
        }
        abriendo = true;
    }
    SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {

        @Override
        protected Object doInBackground() throws Exception {
            try {
                if (d == null || !d.isShowing()) {
                    d = getSummaryDialog();
                }
                if (d != null) {
                    d.pack();
                    int x;
                    int y;

                    Container myParent = window.getPluginContainer().getDetachedTab(0);
                    Point topLeft = myParent.getLocationOnScreen();
                    Dimension parentSize = myParent.getSize();

                    Dimension mySize = d.getSize();

                    if (parentSize.width > mySize.width) {
                        x = ((parentSize.width - mySize.width) / 2) + topLeft.x;
                    } else {
                        x = topLeft.x;
                    }

                    if (parentSize.height > mySize.height) {
                        y = ((parentSize.height - mySize.height) / 2) + topLeft.y;
                    } else {
                        y = topLeft.y;
                    }

                    d.setLocation(x, y);
                } else {
                    log.error("No pude abrir la ficha por un motivo desconocido");
                }
                return null;
            } catch (Throwable t) {
                log.error("Error al abrir la ficha", t);
                return null;
            }
        }

        @Override
        protected void done() {
            if (d != null) {
                d.setVisible(true);
                d.setExtendedState(JFrame.NORMAL);
                d.setAlwaysOnTop(true);
                d.requestFocus();
            }
            abriendo = false;
            if (log.isTraceEnabled()) {
                log.info("Swingworker " + this.getClass().getName() + " finalizado. Abriendo = false");
            }
        }
    };

    sw.execute();
}

From source file:com.mirth.connect.manager.ManagerController.java

public void stopMirthWorker() {
    PlatformUI.MANAGER_DIALOG.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    setEnabledOptions(false, false, false, false);

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        private String errorMessage = null;

        public Void doInBackground() {
            errorMessage = stopMirth();/*  ww  w .ja va 2 s  .c o m*/
            return null;
        }

        public void done() {
            if (errorMessage == null) {
                PlatformUI.MANAGER_TRAY.alertInfo("The Mirth Connect Service was stopped successfully.");
            } else {
                PlatformUI.MANAGER_TRAY.alertError(errorMessage);
            }

            updateMirthServiceStatus();
            PlatformUI.MANAGER_DIALOG.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        }
    };

    worker.execute();
}

From source file:net.openbyte.gui.WorkFrame.java

private void menuItem3ActionPerformed(ActionEvent e) {
    if (this.api == ModificationAPI.BUKKIT) {
        showBukkitIncompatibleFeature();
        return;//  www  . j  av  a  2 s  .  c  o m
    }
    System.out.println("Building modification JAR.");
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            GradleConnector.newConnector().forProjectDirectory(workDirectory).connect().newBuild()
                    .forTasks("build").run();
            return null;
        }
    };
    if (this.api == ModificationAPI.MCP) {
        // recompile and reobfuscate
        worker = new SwingWorker<Void, Void>() {
            @Override
            protected Void doInBackground() throws Exception {
                if (System.getProperty("os.name").startsWith("Windows")) {
                    Runtime.getRuntime().exec("cmd /c recompile.bat", null, workDirectory);
                    Runtime.getRuntime().exec("cmd /c reobfuscate.bat", null, workDirectory);
                    return null;
                }
                try {
                    CommandLine recompile = CommandLine.parse("python "
                            + new File(new File(workDirectory, "runtime"), "recompile.py").getAbsolutePath()
                            + " $@");
                    CommandLine reobfuscate = CommandLine.parse("python "
                            + new File(new File(workDirectory, "runtime"), "reobfuscate.py").getAbsolutePath()
                            + " $@");
                    File recompilePy = new File(new File(workDirectory, "runtime"), "recompile.py");
                    File reobfuscatePy = new File(new File(workDirectory, "runtime"), "reobfuscate.py");
                    CommandLine authRecompile = CommandLine.parse("chmod 755 " + recompilePy.getAbsolutePath());
                    CommandLine authReobfuscate = CommandLine
                            .parse("chmod 755 " + reobfuscatePy.getAbsolutePath());
                    DefaultExecutor executor = new DefaultExecutor();
                    executor.setWorkingDirectory(workDirectory);
                    executor.execute(authRecompile);
                    executor.execute(authReobfuscate);
                    executor.execute(recompile);
                    executor.execute(reobfuscate);
                    System.out.println("Finished building modification JAR.");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        };
    }
    worker.execute();
}

From source file:net.sourceforge.atunes.kernel.modules.search.SearchHandler.java

/**
 * Generic method to update any searchable object.
 * //from   w w  w  .ja  va2s .c om
 * @param searchableObject
 *            the searchable object
 */

private void updateSearchIndex(final SearchableObject searchableObject) {
    SwingWorker<Void, Void> refreshSearchIndex = new SwingWorker<Void, Void>() {
        private IndexWriter indexWriter;

        @Override
        protected Void doInBackground() {
            ReadWriteLock searchIndexLock = indexLocks.get(searchableObject);
            try {
                searchIndexLock.writeLock().lock();
                initSearchIndex();
                updateSearchIndex(searchableObject.getElementsToIndex());
                finishSearchIndex();
                return null;
            } finally {
                searchIndexLock.writeLock().unlock();
                currentIndexingWorks.put(searchableObject, Boolean.FALSE);
            }
        }

        @Override
        protected void done() {
            // Nothing to do
        }

        private void initSearchIndex() {
            getLogger().info(LogCategories.HANDLER, "Updating index for " + searchableObject.getClass());
            try {
                FileUtils.deleteDirectory(new File(searchableObject.getPathToIndex()));
                indexWriter = new IndexWriter(searchableObject.getPathToIndex(), new SimpleAnalyzer(),
                        IndexWriter.MaxFieldLength.UNLIMITED);
            } catch (CorruptIndexException e) {
                getLogger().error(LogCategories.HANDLER, e);
            } catch (LockObtainFailedException e) {
                getLogger().error(LogCategories.HANDLER, e);
            } catch (IOException e) {
                getLogger().error(LogCategories.HANDLER, e);
            }
        }

        private void updateSearchIndex(List<AudioObject> audioObjects) {
            getLogger().info(LogCategories.HANDLER, "update search index");
            if (indexWriter != null) {
                for (AudioObject audioObject : audioObjects) {
                    Document d = searchableObject.getDocumentForElement(audioObject);
                    // Add dummy field
                    d.add(new Field(INDEX_FIELD_DUMMY, INDEX_FIELD_DUMMY, Field.Store.YES,
                            Field.Index.NOT_ANALYZED_NO_NORMS));

                    try {
                        indexWriter.addDocument(d);
                    } catch (CorruptIndexException e) {
                        getLogger().error(LogCategories.HANDLER, e);
                    } catch (IOException e) {
                        getLogger().error(LogCategories.HANDLER, e);
                    }
                }
            }
        }

        private void finishSearchIndex() {
            getLogger().info(LogCategories.HANDLER,
                    StringUtils.getString("Update index for ", searchableObject.getClass(), " finished"));
            if (indexWriter != null) {
                try {
                    indexWriter.optimize();
                    indexWriter.close();

                    indexWriter = null;
                } catch (CorruptIndexException e) {
                    getLogger().error(LogCategories.HANDLER, e);
                } catch (IOException e) {
                    getLogger().error(LogCategories.HANDLER, e);
                }
            }
        }

    };
    if (currentIndexingWorks.get(searchableObject) == null || !currentIndexingWorks.get(searchableObject)) {
        currentIndexingWorks.put(searchableObject, Boolean.TRUE);
        refreshSearchIndex.execute();
    }

}

From source file:com.mirth.connect.plugins.datapruner.DataPrunerPanel.java

public void doStart() {
    final MutableBoolean saveChanges = new MutableBoolean(false);

    if (isSaveEnabled()) {
        if (JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this,
                "Settings changes must be saved first, would you like to save the settings and prune now?",
                "Select an Option", JOptionPane.OK_CANCEL_OPTION)) {
            if (!validateFields()) {
                return;
            }//from  w  w w .  j a va2s .  c  om

            saveChanges.setValue(true);
        } else {
            return;
        }
    }

    setStartTaskVisible(false);
    final String workingId = parent.startWorking("Starting the data pruner...");

    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() {
            if (saveChanges.getValue()) {
                try {
                    plugin.setPropertiesToServer(getProperties());
                } catch (Exception e) {
                    getFrame().alertThrowable(getFrame(), e);
                    return null;
                }
            }

            try {
                parent.mirthClient.getServlet(DataPrunerServletInterface.class).start();
            } catch (Exception e) {
                parent.alertThrowable(parent, e,
                        "An error occurred while attempting to start the data pruner.");
                return null;
            }

            return null;
        }

        @Override
        public void done() {
            if (saveChanges.getValue()) {
                setSaveEnabled(false);
            }

            parent.stopWorking(workingId);
            updateStatus();
        }
    };

    worker.execute();
}

From source file:edu.ku.brc.specify.config.FixAttachments.java

/**
 * @param resultsHashMap//from   w w  w .  ja  v a 2s . c o  m
 * @param tableHash
 * @param totalFiles
 */
private void doAttachmentRefCleanup(final HashMap<Integer, Vector<Object[]>> resultsHashMap,
        final HashMap<Integer, AttchTableModel> tableHash, final int totalFiles) {
    final int numAttachs = getNumberofBadAttachments();

    final String CNT = "CNT";
    final SwingWorker<Integer, Integer> worker = new SwingWorker<Integer, Integer>() {
        int filesCnt = 0;
        int errs = 0;

        @Override
        protected Integer doInBackground() throws Exception {
            try {
                for (int tblId : resultsHashMap.keySet()) {
                    DBTableInfo ti = DBTableIdMgr.getInstance().getInfoById(tblId);
                    AttchTableModel model = tableHash.get(tblId);
                    for (int r = 0; r < model.getRowCount(); r++) {
                        int attachId = model.getAttachmentId(r);
                        int attachJoinId = model.getAttachmentJoinId(r);

                        String sql = String.format("DELETE FROM %s WHERE %s = %d", ti.getName(),
                                ti.getIdColumnName(), attachJoinId);
                        int rv = BasicSQLUtils.update(sql);
                        if (rv == 1) {
                            rv = BasicSQLUtils
                                    .update("DELETE FROM attachment WHERE AttachmentID = " + attachId);
                            if (rv == 1) {
                                filesCnt++;
                            } else {
                                errs++;
                            }
                        } else {
                            errs++;
                        }

                        firePropertyChange(CNT, 0, (int) ((double) filesCnt / (double) totalFiles * 100.0));
                    }
                }

            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return null;
        }

        @Override
        protected void done() {
            UIRegistry.clearSimpleGlassPaneMsg();
            UIRegistry.displayInfoMsgDlg(String.format("Attachments removed: %d / %d", filesCnt, numAttachs));

            if (errs > 0) {
                UIRegistry.displayErrorDlg(
                        String.format("There were %d errors when deleting the attachments.", errs));
            } else {
                if (getNumberofBadAttachments() == 0) {
                    AppPreferences.getGlobalPrefs().putBoolean("CHECK_ATTCH_ERR", false);
                }
            }
            super.done();
        }
    };

    final SimpleGlassPane glassPane = UIRegistry
            .writeSimpleGlassPaneMsg(String.format("Removing %d attachments.", numAttachs), 24);
    glassPane.setProgress(0);

    worker.addPropertyChangeListener(new PropertyChangeListener() {
        public void propertyChange(final PropertyChangeEvent evt) {
            if (CNT.equals(evt.getPropertyName())) {
                glassPane.setProgress((Integer) evt.getNewValue());
            }
        }
    });

    worker.execute();
}

From source file:es.emergya.ui.gis.popups.SDSDialog.java

public SDSDialog(Recurso r) {
    super();/*from   w  w  w.  ja  v a 2  s  . com*/
    setAlwaysOnTop(true);
    setResizable(false);
    iconTransparente = LogicConstants.getIcon("48x48_transparente");
    iconEnviando = LogicConstants.getIcon("anim_enviando");
    destino = r;
    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            super.windowClosing(e);
            cancel.doClick();
        }
    });

    // setPreferredSize(new Dimension(400, 150));
    setTitle(i18n.getString("window.sds.titleBar") + " " + r.getIdentificador());
    try {
        setIconImage(((BasicWindow) GoClassLoader.getGoClassLoader().load(BasicWindow.class)).getFrame()
                .getIconImage());
    } catch (Throwable e) {
        LOG.error("There is no icon image", e);
    }

    JPanel base = new JPanel();

    base.setBackground(Color.WHITE);
    base.setLayout(new BoxLayout(base, BoxLayout.Y_AXIS));

    // Icono del titulo
    JPanel title = new JPanel(new FlowLayout(FlowLayout.LEADING));
    final JLabel titleLabel = new JLabel(i18n.getString("window.sds.title"),
            LogicConstants.getIcon("tittleventana_icon_enviarsds"), JLabel.LEFT);

    titleLabel.setFont(LogicConstants.deriveBoldFont(12f));
    title.add(titleLabel);
    title.setOpaque(false);
    base.add(title);

    // Espacio para el mensaje
    sds = new JTextArea(7, 40);
    sds.setLineWrap(true);

    final JScrollPane sdsp = new JScrollPane(sds);

    sdsp.setOpaque(false);
    sdsp.setBorder(new TitledBorder(BorderFactory.createLineBorder(Color.BLACK),
            i18n.getString("Admin.message") + "\t (0/" + maxChars + ")"));
    sds.setDocument(new PlainDocument() {
        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            if (this.getLength() + str.length() <= maxChars) {
                super.insertString(offs, str, a);
            }
        }
    });
    sds.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
            updateChars(e);
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            updateChars(e);
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            updateChars(e);
        }

        private void updateChars(DocumentEvent e) {
            ((TitledBorder) sdsp.getBorder()).setTitle(
                    i18n.getString("Admin.message") + "\t (" + sds.getText().length() + "/" + maxChars + ")");
            sdsp.repaint();
            send.setEnabled(!sds.getText().isEmpty());
            notification.setForeground(Color.WHITE);
            notification.setText("PLACEHOLDER");
        }
    });
    base.add(sdsp);

    // Area para mensajes
    JPanel notificationArea = new JPanel();

    notificationArea.setOpaque(false);
    notification = new JLabel("TEXT");
    notification.setForeground(Color.WHITE);
    notificationArea.add(notification);
    base.add(notificationArea);

    JPanel buttons = new JPanel();

    buttons.setOpaque(false);
    buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
    send = new JButton(i18n.getString("Buttons.send"),
            LogicConstants.getIcon("ventanacontextual_button_enviarsds"));
    send.addActionListener(this);
    send.setEnabled(false);
    buttons.add(send);
    buttons.add(Box.createHorizontalGlue());
    progressIcon = new JLabel(iconTransparente);
    buttons.add(progressIcon);
    buttons.add(Box.createHorizontalGlue());
    cancel = new JButton(i18n.getString("Buttons.cancel"), LogicConstants.getIcon("button_cancel"));
    cancel.addActionListener(this);
    buttons.add(cancel);
    base.add(buttons);
    getContentPane().add(base);
    pack();

    int x;
    int y;
    Container myParent;
    try {
        myParent = ((BasicWindow) GoClassLoader.getGoClassLoader().load(BasicWindow.class)).getFrame()
                .getContentPane();
        java.awt.Point topLeft = myParent.getLocationOnScreen();
        Dimension parentSize = myParent.getSize();

        Dimension mySize = getSize();

        if (parentSize.width > mySize.width)
            x = ((parentSize.width - mySize.width) / 2) + topLeft.x;
        else
            x = topLeft.x;

        if (parentSize.height > mySize.height)
            y = ((parentSize.height - mySize.height) / 2) + topLeft.y;
        else
            y = topLeft.y;

        setLocation(x, y);
    } catch (Throwable e1) {
        LOG.error("There is no basic window!", e1);
    }
    this.addWindowListener(new WindowAdapter() {
        @Override
        public void windowOpened(WindowEvent arg0) {
            deleteErrorMessage();
        }

        @Override
        public void windowClosed(WindowEvent arg0) {
            deleteErrorMessage();
        }

        private void deleteErrorMessage() {
            SwingWorker<Object, Object> sw = new SwingWorker<Object, Object>() {
                @Override
                protected Object doInBackground() throws Exception {
                    if (bandejaSalida != null) {
                        MessageGenerator.remove(bandejaSalida.getId());
                    }

                    bandejaSalida = null;

                    return null;
                }

                @Override
                protected void done() {
                    super.done();
                    SDSDialog.this.sds.setText("");
                    SDSDialog.this.sds.setEnabled(true);
                    SDSDialog.this.sds.repaint();
                    SDSDialog.this.progressIcon.setIcon(iconTransparente);
                    SDSDialog.this.progressIcon.repaint();
                    SDSDialog.this.notification.setText("");
                    SDSDialog.this.notification.repaint();
                }
            };

            sw.execute();
        }
    });
}