SwingWorker void,void ????

I have the following class declaration:
public class blah extends SwingWorker<void,void>and I get the following error:
Syntax error on token "void", Dimensions expected after this token.
What is the problem?

can't use int either?????? why can't it be a
primative type?Generics does not work on the primitive type level, so it must be something that derives from Object. You can use Integer instead, and if you want you can take advantage of autoboxing so that your code deals only with ints and not with Integer:
// Silly example to give you an idea of what I mean
class MySwingWorker extends SwingWorker<Integer, Object> {
    @Override
    public Integer doInBackground() {
        return 1 + 2 + 3 + 4;
    @Override
    protected void done() {
        int value = get();
}

Similar Messages

  • Wrongly input void payment date

    Hi! When I void a payment for an invoice with GL date 20-JUL, i wrongly inputted the date to 30-AUG.
    What I see now in "Payment Overview" window is:
    amount: 2000
    status: voided
    voide date: 30-AUG
    Invoices:
    Amount Paid GL Date
    2000 20-JUL
    (2000) 30-AUG
    Can anyone suggest what should I do now?

    leave the status of this voided payment as (NO)
    at the bottom of the payment form u will find ( Accounted -> NO) , so leave it at this status and make new payment @ right date then fire action button then check create account.
    -------------other solution------------------
    create account for this ( wrongly input void payment date) and transfer it to GL
    and from GL Reverse it but in the date/period you voided.

  • Stumped with SwingWorker -- code compiles but doesn't run right

    Okay, sorry to post a ton of code, but I'm creating a swing gui that will use swing worker to create an object of the followng class, one method that sleeps and returns a random number:
    public class BigJob{
         public int doBigJob(){
              try {
              Thread.sleep(15000);
              } catch (InterruptedException e){
              e.printStackTrace();
         int number = (int)(Math.random() * 50);
         return number;
    }I can get the gui program below to run without the SwingWorker, but am having trouble getting it to run properly. The code posted below compiles and starts up ok, but when I click the "click to do big job" button, it just doesn't do anything.
    I created a runnable in the main method, and invoked the method to build the gui, so that's working.
    I have the SwingWorker defined in an inner class that implements ActionListener; I'm guessing that's the problem. I should probably put the SwingWorkder in its own inner class, and invoke it from the first listener class?
    here's the code:
    import javax.swing.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.BorderLayout;
    import javax.swing.SwingWorker;
    public class WorkerTest{
         private JFrame frame;
         private JButton button1;
         private JButton button2;
         private JButton button3;
         private JPanel topPanel;
         public static void main (String[] args){
         SwingUtilities.invokeLater(new Runnable() {
              public void run(){
              WorkerTest wtest = new WorkerTest();
              wtest.buildGui();
         } // end main
         public void buildGui(){
         frame = new JFrame("frame to test swing worker");
         frame.setSize(700,200);
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setLayout(new BorderLayout());
         topPanel = new JPanel();
         frame.add(topPanel, BorderLayout.NORTH);
         button1 = new JButton("click to change text");
         button1.addActionListener(new Button1Listener());
         button2 = new JButton("click to do big thing");
         button1.addActionListener(new Button2Listener());
         button3 = new JButton("click to change text");
         button3.addActionListener(new Button3Listener());
         topPanel.add(button1);
         topPanel.add(button2);
         topPanel.add(button3);
         frame.setVisible(true);
    // inner classes to add listeners
         class Button1Listener implements ActionListener{
              public void actionPerformed(ActionEvent e){
              button1.setText("i've been clicked");
         class Button2Listener implements ActionListener{
              public void actionPerformed(ActionEvent e){
              // execute job in main thread
              //BigJob job = new BigJob();
              //button2.setText("big job is done: " + job.doBigJob());
              // execute job in its own thread:
              SwingWorker worker = new SwingWorker<BigJob, Void>(){
              BigJob job;
              int resultNum;
                   public BigJob doInBackground(){
                   job = new BigJob();
                   resultNum = job.doBigJob();
                   button2.setText("big job done: " + resultNum);
                   return job;
         class Button3Listener implements ActionListener{
              public void actionPerformed(ActionEvent e){
              button3.setText("i've been clicked also");
    } // end WorkerTestthanks,
    bp

    badperson wrote:
    where in the code should that go, in the listener class?
    SwingWorker worker = new SwingWorker<BigJob, Void>() {
        public BigJob doInBackground() {
            // code
         return job;
    worker.execute();

  • Set TimeOut for SwingWorker

    nice day,
    1/ how can I get real Html size in kB with intention to set as maxValue to ProgressMonitor
    2/ how can I set/synchronize current valueOfDownLoadedHtml in kB to ProgressMonitor throught downloading Html content
    3/ how can I set TimeOut for this Tast, (maybe ... could I use Timer)
    import java.awt.BorderLayout;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import java.net.URLConnection;
    import java.nio.charset.Charset;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.ProgressMonitor;
    import javax.swing.SwingWorker;
    public class ProgressMonitorDemo extends JPanel implements ActionListener, PropertyChangeListener {
        private static final long serialVersionUID = 1L;
        private ProgressMonitor progressMonitor;
        private JButton startButton;
        private JTextArea taskOutput;
        private Task task;
        private int sizeIn_kB = 0;
        class Task extends SwingWorker<Void, Void> {
            private String str;
            int progress = 0;
            public Task(String str) {
                this.str = str;
            @Override
            public Void doInBackground() {
                if (str.equals("Loads")) {
                    addBackgroundLoadsData();
                    setProgress(0);
                    while (progress < sizeIn_kB && !isCancelled()) {
                        progress += sizeIn_kB;
                        setProgress(Math.min(progress, sizeIn_kB));
                return null;
            @Override
            public void done() {
                if (str.equals("Loads")) {
                    Toolkit.getDefaultToolkit().beep();
                    startButton.setEnabled(true);
                    progressMonitor.setProgress(0);
        public void addBackgroundLoadsData() {
            InputStream in = null;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            String charset ="";
            try {
                String UrlString = "http://java.sun.com/";
                URL url = new URL(UrlString);
                URLConnection conn = url.openConnection();
                sizeIn_kB = conn.getContentLength();
                charset = conn.getContentEncoding();
                conn.setRequestProperty("Accept-Charset", charset);
                in = conn.getInputStream();
                int len;
                byte[] buf = new byte[1024];
                while ((len = in.read(buf)) > 0) {
                    bos.write(buf, 0, len);
                in.close();
                String charEncoding = Charset.defaultCharset().name();
                //String fileEncoding = System.getProperty("file.encoding");
                //System.out.println("File Encoding: " + fileEncoding);
                //System.out.println("Char Encoding: " + charEncoding);
                //System.out.println("Char Encoding: " + Charset.availableCharsets());
                charEncoding = "cp1250";
                String groupImport = new String(bos.toByteArray(), charEncoding);
                conn = null;
            } catch (IOException ioException) {
                ioException.printStackTrace();
                JOptionPane.showMessageDialog(null, ioException.getMessage(), "Htlm error", JOptionPane.ERROR_MESSAGE);
            } catch (StringIndexOutOfBoundsException ioException) {
                ioException.printStackTrace();
                JOptionPane.showMessageDialog(null, ioException.getMessage(), "InputStream error", JOptionPane.ERROR_MESSAGE);
        public ProgressMonitorDemo() {
            super(new BorderLayout());
            startButton = new JButton("Start");
            startButton.setActionCommand("start");
            startButton.addActionListener(this);
            taskOutput = new JTextArea(5, 20);
            taskOutput.setMargin(new Insets(5, 5, 5, 5));
            taskOutput.setEditable(false);
            add(startButton, BorderLayout.PAGE_START);
            add(new JScrollPane(taskOutput), BorderLayout.CENTER);
            setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        @Override
        public void actionPerformed(ActionEvent evt) {
            progressMonitor = new ProgressMonitor(ProgressMonitorDemo.this, "Running a Long Task", "", 0, 100);
            progressMonitor.setProgress(0);
            task = new Task("Loads");
            task.addPropertyChangeListener(this);
            task.execute();
            startButton.setEnabled(false);
        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if ("progress" == null ? evt.getPropertyName() == null : "progress".equals(evt.getPropertyName())) {
                int progress = (Integer) evt.getNewValue();
                progressMonitor.setProgress(progress);
                String message = String.format("Completed %d%%.\n", progress);
                progressMonitor.setNote(message);
                taskOutput.append(message);
                if (progressMonitor.isCanceled() || task.isDone()) {
                    Toolkit.getDefaultToolkit().beep();
                    if (progressMonitor.isCanceled()) {
                        task.cancel(true);
                        taskOutput.append("Task canceled.\n");
                    } else {
                        taskOutput.append("Task completed.\n");
                    startButton.setEnabled(true);
        private static void createAndShowGUI() {
            JFrame frame = new JFrame("ProgressMonitorDemo");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JComponent newContentPane = new ProgressMonitorDemo();
            newContentPane.setOpaque(true);
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    See the session-descriptor element of weblogic.xml deployment descriptor:
    http://download.oracle.com/docs/cd/E21764_01/web.1111/e13712/weblogic_xml.htm#i1071981

  • SwingWorker asynchronous PropertyChangeEvent problems

    I'm using a SwingWorker to execute a task that I am keeping progress on. I have a JDialog that I show and dispose of based on events from the SwingWorker. These events are generated asynchronously on the EDT which is fine. I understand that it may be the case I could call setProgress a few times before a PropertyChangeEvent actually happens, however what I don't understand is why a "state" event is never making it as the event when the SwingWorker completes. If I cancel the task it will reach it, but when it finishes by itself there is nothing. This state event should be getting fired and listened to and handled on the EDT but its not. Attached is my code for three classes and an example of how to use it. Basically it just takes a .lst whose format is an IP address on each line, nothing else.
    public class OpenSwingWorker extends SwingWorker<Object[], Object> {
        private FILETYPE _fileType = null;
        private File[] _files = null;
        private DefaultListModel _listModel = null;
        private List<Object> _objects = null;
        private int _progress = 0;
        public OpenSwingWorker(FILETYPE fileType, File[] files, ListModel listModel) {
            _fileType = fileType;
            _files = files;
            _listModel = (DefaultListModel) listModel;
            _objects = new ArrayList<Object>();
        @Override
        protected Object[] doInBackground() {
            int progress = 0;
            if (_fileType == FILETYPE.LST) {
                BufferedReader bufferedReader = null;
                String line = null;
                for (File file : _files) {
                    if (isCancelled()) {
                        break;
                    try {
                        bufferedReader = new BufferedReader(new FileReader(file));
                        while ((line = bufferedReader.readLine()) != null) {
                            InetAddress inetAddress = InetAddress.getByName(line);
                            _objects.add(inetAddress);
                            publish(inetAddress);
                    } catch (FileNotFoundException ex) {
                        Logger.getLogger(OpenSwingWorker.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (IOException ex) {
                        Logger.getLogger(OpenSwingWorker.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (Exception ex) {
                        Logger.getLogger(OpenSwingWorker.class.getName()).log(Level.SEVERE, null, ex);
                    } finally {
                        try {
                            bufferedReader.close();
                        } catch (IOException ex) {
                            Logger.getLogger(OpenSwingWorker.class.getName()).log(Level.SEVERE, null, ex);
                    setProgress(++_progress * 100 / _files.length);
            } else if (_fileType == FILETYPE.MSG) {
                MsgParser msgParser = Main.getMsgParser();
                for (File file : _files) {
                    if (isCancelled()) {
                        break;
                    try {
                        MessageRecord messageRecord = new MessageRecord(msgParser.parseMsg(file));
                        _objects.add(messageRecord);
                        publish(messageRecord);
                    } catch (IOException ex) {
                        Logger.getLogger(OpenSwingWorker.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (UnsupportedOperationException ex) {
                        Logger.getLogger(OpenSwingWorker.class.getName()).log(Level.SEVERE, null, ex);
                    setProgress(++progress * 100 / _files.length);
            return _objects.toArray();
        @Override
        protected void process(List<Object> chunks) {
            for (Object object : chunks) {
                _listModel.addElement(object);
    public class SwingWorkerPropertyChangeListener implements PropertyChangeListener {
        private ProgressJDialog _progressJDialog = null;
        private SwingWorker _swingWorker = null;
        public SwingWorkerPropertyChangeListener(ProgressJDialog progressJDialog, SwingWorker swingWorker) {
            _progressJDialog = progressJDialog;
            _swingWorker = swingWorker;
        public void propertyChange(PropertyChangeEvent evt) {
            String propertyName = evt.getPropertyName();
            if (propertyName.equals("state")) {
                SwingWorker.StateValue stateValue = (StateValue) evt.getNewValue();
                if (stateValue.equals(SwingWorker.StateValue.STARTED)) {
                    _progressJDialog.setVisible(true);
                } else if (stateValue.equals(SwingWorker.StateValue.DONE)) {
                    _progressJDialog.dispose();
            } else if (propertyName.equals("progress")) {           
                if (_progressJDialog.isCancelled()) {
                    _swingWorker.cancel(true);
                } else {
                    _progressJDialog.setProgress((Integer) evt.getNewValue());
    public class ProgressJDialog extends JDialog {
        private boolean _cancelled = false;
        private JButton _jButton = null;
        private JProgressBar _jProgressBar = null;
        public ProgressJDialog(boolean indeterminate, String taskName) {
            super((JDialog) null, "Performing Task...", true);
            _jProgressBar = new JProgressBar();
            _jProgressBar.setBorder(BorderFactory.createTitledBorder(taskName));
            _jProgressBar.setIndeterminate(indeterminate);
            _jProgressBar.setStringPainted(true);
            initComponents();
        private void createJButton() {
            _jButton = new JButton("Cancel");
            _jButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    dispose();
            _jButton.setMnemonic(KeyEvent.VK_C);
        private void initComponents() {
            createJButton();
            add(_jProgressBar, BorderLayout.CENTER);
            add(_jButton, BorderLayout.LINE_END);
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosed(WindowEvent e) {
                    _cancelled = true;
            pack();
            setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        public boolean isCancelled() {
            return _cancelled;
        public void setProgress(int progress) {
            _jProgressBar.setValue(progress);
    /* EXAMPLE USAGE BELOW */
    if (jFileChooser1.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                SwingWorker openSwingWorker = new OpenSwingWorker(Main.FILETYPE.valueOf(jFileChooser1.getFileFilter().getDescription()), jFileChooser1.getSelectedFiles(), jList1.getModel());
                openSwingWorker.addPropertyChangeListener(new SwingWorkerPropertyChangeListener(new ProgressJDialog(false, "Opening files..."), openSwingWorker));
                openSwingWorker.execute();
    }

    I figured out the problem. It's not that the PropertyChangeEvent's weren't occuring it's that they were occuring too quickly. I placed a sleep before setting progress and now it works nicely. I hope if anyone else runs into this problem I save them some time this was bugging me forever. Thanks again.

  • SwingWorker problem!!! How can I run it 2 times or more?

    Hello!!
    I am new in Java. I use the following code:
    SwingWorker SWorker = new SwingWorker<String, Void>()
       public String doInBackground() {
       return CargarInformacion();
    public void done() {
       try {
          JTextAreaReport.append(get());
       } catch(InterruptedException ie)
          System.out.println(ie.toString());
       } catch(java.util.concurrent.ExecutionException ee)
          System.out.println(ee.toString());
    private String CargarInformacion()
       try
          in = new BufferedReader(new FileReader(file));
          <read file...>
       return StrMessage;
    }The problem is that when this code runs for the first time it works perfect!!! but I need to use it several times with other file names. In the java docs I found the following text:
    "SwingWorker is only designed to be executed once. Executing a SwingWorker more than once will not result in invoking the doInBackground method twice."
    How can I resolve this?
    thank's.
    David.
    Edited by: davigre on Oct 1, 2008 8:42 PM

    I am trying to do this as well. For some reason, it is not working for me. I have a class "Task" that extends Swingworker with a doInBackground() and done(). Each time I click "submit" I create a new "Task" and call task.execute(). But the second time around, the doInBackground() never gets called. Can someone help me out? Here are a couple of the relevant functions.
    Thanks
    Mike
    Here is where the thread is started:
    public void readDataLogger() {
            jButton.setEnabled(false);
            jBox.setEnabled(false);
            String deleteData = JOptionPane.showInputDialog("Would you like to erase all the data off this logger after it is downloaded? (y/n)");
            if (deleteData == null || deleteData.equalsIgnoreCase("n") || deleteData.equalsIgnoreCase("no")) {
                // user clicked cancel or typed n/no
            } else if (deleteData.equalsIgnoreCase("y") || deleteData.equalsIgnoreCase("yes")) {
                erase = true;
            routeNum.setText("Route Num: " + (String) jBox.getSelectedItem());
            waiting.setText("Please wait a moment...");
            Thread stepper = new BarThread(progressBar);
            stepper.start();
            this.add(progressBar);
            Task task = new Task();
            task.execute();
        }And the thread classes:
    class BarThread extends Thread {
            JProgressBar progressBar;
            public BarThread(JProgressBar bar) {
                progressBar = bar;
            public void run() {
        class Task extends SwingWorker<Void, Void>{
            boolean wrongPort;
            long timeGoneBy = 0;
             * Main task. Executed in background thread.
            public Void doInBackground() {
                wrongPort = true;
                try {
                    logWriter.append("starting new thread");
                    logWriter.flush();
                } catch (IOException ex) {
                    Logger.getLogger(DDAGPS.class.getName()).log(Level.SEVERE, null, ex);
                Runtime rt = Runtime.getRuntime();
                File propertiesFile = new File("port.properties");
                Properties properties = new Properties();
                String command = "";
                int portTry = 0;
                boolean propPort = false;
                if (propertiesFile.exists()) {
                    try {
                        properties.load(new FileInputStream("port.properties"));
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    if (properties.containsKey("port")) {
                        portTry = Integer.parseInt((String) properties.get("port"));
                        try {
                            logWriter.append("port from properties: " + portTry + "\r\n");
                            logWriter.flush();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        command = baseDir + "GPSBabel/gpsbabel.exe -p \"\" -w -t -i mtk";
                        if (erase) {
                            command += ",erase";
                        command += " -f com" + portTry + ": -o gpx,gpxver=1.0 -F " + baseDir + "Temp/" + jBox.getSelectedItem() + "-" + numbLoggers + ".gpx";
                        launching.setText("trying it on COM" + portTry);
                        try {
                            logWriter.append("command using port from props: " + command + "\r\n");
                            logWriter.flush();
                            Process p = rt.exec(command);
                            File bin = new File(baseDir + "data.bin");
                            boolean fileExists = false;
                            double time = 0.0;
                            while (!procDone(p) && !fileExists && time < 10) {
                                logWriter.append("waiting and looking for bin file: " + time + "\r\n");
                                logWriter.flush();
                                Thread.sleep(200);
                                time += .2;
                                if (bin.exists() && bin.length() > 0) {
                                    wrongPort = false;
                                    launching.setText("it worked on COM" + portTry + ", building data file...");
                                    propPort = true;
                                    fileExists = true;
                            if (!fileExists) {
                                logWriter.append("it did not work using the port from the properties file");
                                logWriter.flush();
                        } catch (IOException ex) {
                            try {
                                logWriter.append("error: " + ex.getMessage() + " trying to use GPSBabel with port from properties file\r\n");
                                logWriter.flush();
                            } catch (IOException ex1) {
                                ex1.printStackTrace();
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                //if (!propPort) {
                    try {
                        Process p = rt.exec("mode.com");
                        String s = null;
                        ArrayList<Integer> ports = new ArrayList<Integer>();
                        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
                        logWriter.append("Here is the standard output of the command:\r\n");
                        logWriter.flush();
                        int lines = 0;
                        int po = -1;
                        while ((s = stdInput.readLine()) != null) {
                            String port = "";
                            logWriter.append("line: " + s + "\r\n");
                            logWriter.flush();
                            if (lines > 0) {
                                if (s.contains("Baud") && s.contains("115200")) {
                                    logWriter.append("adding port: " + po + "\r\n");
                                    logWriter.flush();
                                    ports.add(po);
                                lines--;
                            if (s.startsWith("Status for device COM")) {
                                port = s.substring(s.indexOf("M") + 1, s.indexOf(":"));
                                po = Integer.parseInt(port);
                                lines = 2;
                        stdInput.close();
                        portTry = 0;
                        logWriter.append("wrongPort: " + wrongPort);
                        logWriter.flush();
                        while (portTry < ports.size() && wrongPort) {
                            command = baseDir + "GPSBabel/gpsbabel.exe -p \"\" -w -t -i mtk";
                            if (erase) {
                                command += ",erase";
                            command += " -f com";
                            command += ports.get(portTry) + ": -o gpx,gpxver=1.0 -F " + baseDir + "Temp/" + jBox.getSelectedItem() + "-" + numbLoggers + ".gpx";
                            System.out.println("command: " + command);
                            Long currentTime1 = System.currentTimeMillis();
                            launching.setText("trying it on COM" + ports.get(portTry));
                            logWriter.append("command: " + command + "\r\n");
                            logWriter.flush();
                            p = rt.exec(command);
                            boolean fileExists = false;
                            while (!procDone(p) && wrongPort && !fileExists) {
                                Thread.sleep(100);
                                long currentTime2 = System.currentTimeMillis();
                                timeGoneBy = (currentTime2 - currentTime1);
                                Long seconds = timeGoneBy / 1000;
                                int hundreds = (int) (timeGoneBy / 100) % 10;
                                timer.setText(seconds + "." + hundreds + " s");
                                logWriter.append("still working: " + seconds + " seconds\r\n");
                                logWriter.flush();
                                File bin = new File(baseDir + "data.bin");
                                if (!(bin.exists() && bin.length() > 0)) {
                                    wrongPort = true;
                                } else {
                                    logWriter.append("bin exists: " + bin.exists() + "\r\n");
                                    logWriter.flush();
                                    //File port = new File(baseDir + "port.properties");
                                    //FileWriter fw = new FileWriter(port);
                                    //fw.append("port=" + String.valueOf((ports.get(portTry))));
                                    //fw.flush();
                                    //fw.close();
                                    launching.setText("it worked on COM" + ports.get(portTry) + ", building data file...");
                                    wrongPort = false;
                                if (seconds > 15) {
                                    takeAWhile.setText("This could take a minute or two depending on how much data you have to pull off.");
                                File file = new File(baseDir + "Temp/" + jBox.getSelectedItem() + "-" + numbLoggers + ".gpx");
                                if (file.exists()) {
                                    fileExists = true;
                                logWriter.append("wrongPort: " + wrongPort + "\r\n");
                                logWriter.flush();
                                logWriter.append("fileExists: " + fileExists + "\r\n");
                                logWriter.flush();
                                logWriter.append("procDone: " + procDone(p) + "\r\n");
                                logWriter.flush();
                            portTry++;
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                return null;
            private boolean procDone(Process p) {
                try {
                    int v = p.exitValue();
                    return true;
                } catch (IllegalThreadStateException e) {
                    return false;
             * Executed in event dispatch thread
            public void done() {
                try {
                    logWriter.append("in done!\r\n");
                    logWriter.append("wrongPort: " + wrongPort);
                    logWriter.flush();
                } catch (IOException ex) {
                    Logger.getLogger(DDAGPS.class.getName()).log(Level.SEVERE, null, ex);
                launching.setText("");
                ddagps.repaint();
                File bin = new File(baseDir + "data.bin");
                if (wrongPort) {
                    //wrongPort = false;
                    String message = "Something went wrong.  Please make sure the device is turned on and replug the " +
                            "device into the USB port and hit OK.";
                    int response = redo(message);
                    if (response == 1) {
                        System.exit(0);
                    } else {
                        timer.setText("");
                        readDataLogger();
                } else {
                    try {
                        logWriter.append("i am in done's else!\r\n");
                        logWriter.flush();
                    } catch (IOException ex) {
                        Logger.getLogger(DDAGPS.class.getName()).log(Level.SEVERE, null, ex);
                    launching.setText("creating gpx file");
                    ddagps.repaint();
                    File file = new File(baseDir + "Temp/" + jBox.getSelectedItem() + "-" + numbLoggers + ".gpx");
                    while (!file.exists()) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                    //System.out.println("f1 does not exist");
                    numbLoggers++;
                    ddagps.remove(progressBar);
                    takeAWhile.setText("");
                    Toolkit.getDefaultToolkit().beep();
                    jBox.setEnabled(true);
                    jButton.setEnabled(true);
                    waiting.setText("Done!\n");
                    String moreDevices = JOptionPane.showInputDialog("Do you have any more devices to enter in? (y/n)");
                    if (moreDevices == null) {
                        // user clicked cancel
                    } else if (moreDevices.equalsIgnoreCase("y") || moreDevices.equalsIgnoreCase("yes")) {
                        JOptionPane.showMessageDialog(null, "Hit OK when the next logger is plugged in.");
                        timer.setText("");
                        bin.delete();
                        readDataLogger();
                    } else if (moreDevices.equalsIgnoreCase("n") || moreDevices.equalsIgnoreCase("no")) {
                        launching.setText("Merging files...");
                        ddagps.repaint();
                        int numb = numbLoggers - 1;
                        File f = new File(baseDir + "Temp/" + jBox.getSelectedItem() + "-" + numb + ".gpx");
                        while (!f.exists()) {
                            try {
                                Thread.sleep(200);
                            } catch (InterruptedException ex) {
                                ex.printStackTrace();
                        //System.out.println("f2 does not exist");
                        //System.out.println("found " + f.getName());
                        ParseAndCombineKMLs pack = new ParseAndCombineKMLs(numbLoggers, jBox.getSelectedItem());
                        if (pack.parseAndCombine()) {
                            f = new File(baseDir + "Output/" + jBox.getSelectedItem() + ".kml");
                            while (!f.exists()) {
                                try {
                                    Thread.sleep(100);
                                } catch (InterruptedException ex) {
                                    ex.printStackTrace();
                            //System.out.println("f3 does not exist");
                            Uploader up = new Uploader(upload);
                            if (up.pushFile(baseDir + "Output/" + jBox.getSelectedItem() + ".kml")) {
                                launching.setText("Upload Successful");
                                Runtime rt = Runtime.getRuntime();
                                try {
                                    rt.exec("C:/Program Files/Mozilla Firefox/firefox.exe " + view + "?route=" + jBox.getSelectedItem());
                                    bin = new File(baseDir + "data.bin");
                                    bin.delete();
                                    launching.setText("Launching browswer with your data...");
                                } catch (IOException ex) {
                                    ex.printStackTrace();
                        try {
                            logWriter.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
        }Edited by: dmikester1 on Nov 5, 2008 8:50 AM

  • SwingWorker don't start immediately - question

    Given: two SwingWorkers (SW). I want them BOTH to start working immediately upon execute(). However, it seems that the second SW waits for the first SW to complete. Below is a working example. When you run it, you will see that it pauses ten seconds between debug print statements FIRST and SECOND. Why does it pause? Should not FIRST and SECOND appear nearly simultaneously? How do I make both SW start immediately? Thanks.
    import javax.swing.SwingWorker;
    public class Test {
    private void test() {
    new SwingWorker<Object, Void>()
    @Override
    protected Object doInBackground() throws Exception
    System.out.println("FIRST");
    System.out.flush();
    Thread.sleep(10000);
    return null;
    @Override
    protected void done()
    }.execute();
    new SwingWorker<Object, Void>()
    @Override
    protected Object doInBackground() throws Exception
    System.out.println("SECOND");
    System.out.flush();
    return null;
    @Override
    protected void done()
    }.execute();          
    public static void main(String[] args) {
    System.out.println("START");
    System.out.flush();
    new Test().test();
    try {
    Thread.sleep(20000);
    catch(InterruptedException e) {
    System.out.println("STOP");
    }

    Turns out I found a bug: http://forums.sun.com/thread.jspa?threadID=5434659. This works great:
    import javax.swing.SwingWorker;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Executor;
    public class Test {
        private void test() {
         Executor executor = Executors.newCachedThreadPool();
         executor.execute(
         new SwingWorker<Object, Void>()
             @Override
             protected Object doInBackground() throws Exception
              System.out.println("FIRST");
              System.out.flush();
              Thread.sleep(10000);
              return null;
             @Override
             protected void done()
         executor.execute(
         new SwingWorker<Object, Void>()
              @Override
              protected Object doInBackground() throws Exception
                   System.out.println("SECOND");
                   System.out.flush();
                   // Thread.sleep(10000);
                   return null;
              @Override
              protected void done()
        public static void main(String[] args) {
         System.out.println("START");
         System.out.flush();
         new Test().test();
         try {
             Thread.sleep(20000);
         catch(InterruptedException e) {
         System.out.println("STOP");
    }

  • SwingWorker done() is called before doInBackground is finished

    Hi,
    I'm having a problem understanding how the SwingWorker works. According to java docs: "After the doInBackground method is finished the done method is executed" and there is a happens before relationship. But if I run the code below:
       public class A extends SwingWorker<Void, Void>
             protected Void doInBackground() throws InterruptedException
                  String k = "this is a test";
                  String j = k;
                  while(true)
                       for(int i=0; i<1000; i++)
                            j = j + k;
                            j.replaceAll("nothing", "something");
                       System.out.println("going");
             protected void done()
                  try
                       get();
                  catch(InterruptedException ex){System.out.println("interrupted");}
                  catch(CancellationException ex){System.out.println("cancelled");}
                  System.out.println("done");
    }and call cancel(true) while the thread is running the output I get is
    going
    going
    cancelled
    done
    going
    going
    So that means that done() get's fired after I called cancel(), not after doInBackground() is finished.
    This is causing some serious problems in my actual application, as I do some clean up in done(), but doInBackground() keeps going until it hits my Thread.sleep() code.
    Thanks a lot.

    Hello,
    I think I have a workaround to your problem. By the way, I am the one who submitted [bug 6826514|http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6826514] in April of 2009.
    My solution takes advantage of firePropertyChange() and related methods in SwingWorker.
    Here I completely refrain from using done() method to detect the end of doInBackground()'s execution.
    Please bear with me the fact that the code is a little bit long.
    /* GoodWorker.java  */
    package solve;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.SwingWorker;
    * @author Sumudu
    public class GoodWorker extends SwingWorker<Void, Void> {
        private MainFrame mainFrame = null;
        private final String prReallyDone = "ReallyDone";
        private void whenReallyDone() {
            mainFrame.afterWorkerFinishes();
            System.out.println("done");
        public GoodWorker(MainFrame mainFrame) {
            this.mainFrame = mainFrame;
            getPropertyChangeSupport().addPropertyChangeListener(prReallyDone,
                new PropertyChangeListener() {
                public void propertyChange(PropertyChangeEvent e) {
                    if (e.getNewValue().equals(true)) {
                        whenReallyDone();
        protected Void doInBackground() throws Exception {
            String k = "this is a test";
            String j = k;
            while (!isCancelled()) {
                for (int i = 0; i < 1000; i++) {
                    j = j + k;
                    j.replaceAll("nothing", "something");
                System.out.println("going");
            firePropertyChange(prReallyDone, false, true);
            return null;
    // -- The End --
    /* BadWorker.java */
    package solve;
    import javax.swing.SwingWorker;
    public class BadWorker extends SwingWorker<Void, Void> {
        private MainFrame mainFrame = null;
        public BadWorker(MainFrame mainFrame) {
            this.mainFrame = mainFrame;
        protected Void doInBackground() throws Exception {
            String k = "this is a test";
            String j = k;
            while (!isCancelled()) {
                for (int i = 0; i < 1000; i++) {
                    j = j + k;
                    j.replaceAll("nothing", "something");
                System.out.println("going");
            return null;
        @Override
        protected void done() {
            mainFrame.afterWorkerFinishes();
            System.out.println("done");
    // -- The End --
    /* MainFrame.java */
    package solve;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.concurrent.CancellationException;
    import java.util.concurrent.ExecutionException;
    import javax.swing.SwingWorker;
    public class MainFrame extends javax.swing.JFrame {
        private BadWorker badWorker = null;
        private GoodWorker goodWorker = null;
        private boolean useGoodWoker;
        private void initialize() {
            this.setLocationRelativeTo(null);
            btnStop.setEnabled(false);
            useGoodWoker = chkUseGoodWorker.isSelected();
            btnStart.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    chkUseGoodWorker.setEnabled(false);
                    btnStart.setEnabled(false);
                    btnStop.setEnabled(true);
                    useGoodWoker = chkUseGoodWorker.isSelected();
                    System.out.println("Starting SwingWorker...");
                    if (useGoodWoker) {
                        goodWorker = new GoodWorker(MainFrame.this);
                        goodWorker.execute();
                    } else {
                        badWorker = new BadWorker(MainFrame.this);
                        badWorker.execute();
            btnStop.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    SwingWorker worker = (useGoodWoker ? goodWorker : badWorker);
                    if (worker != null && !worker.isDone()) {
                        btnStop.setEnabled(false);
                        worker.cancel(true);
        public void afterWorkerFinishes() {
            SwingWorker worker = (useGoodWoker ? goodWorker : badWorker);
            try {
                worker.get();
            } catch (InterruptedException ie) {
                System.out.println("Got interrupted while waiting in get().");
            } catch (ExecutionException ee) {
                System.out.print("An exception was thrown inside doInBackground(). ");
                Throwable t = ee.getCause();
                System.out.printf("More specifically, %s %n", t.getMessage());
            } catch (CancellationException ce) {
                System.out.println("SwingWorker got cancelled by you.");
            chkUseGoodWorker.setEnabled(true);
            btnStart.setEnabled(true);
        /** Creates new form MainFrame */
        public MainFrame() {
            initComponents();
            initialize();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
        private void initComponents() {
            chkUseGoodWorker = new javax.swing.JCheckBox();
            buttonPanel = new javax.swing.JPanel();
            btnStart = new javax.swing.JButton();
            btnStop = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("SwingWorkers");
            chkUseGoodWorker.setText("Check this to use Good Worker");
            chkUseGoodWorker.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
            chkUseGoodWorker.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            chkUseGoodWorker.setMargin(new java.awt.Insets(0, 0, 0, 0));
            getContentPane().add(chkUseGoodWorker, java.awt.BorderLayout.CENTER);
            btnStart.setText("Start");
            buttonPanel.add(btnStart);
            btnStop.setText("Stop");
            buttonPanel.add(btnStop);
            getContentPane().add(buttonPanel, java.awt.BorderLayout.SOUTH);
            pack();
        }// </editor-fold>//GEN-END:initComponents
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MainFrame().setVisible(true);
        // Variables declaration - do not modify//GEN-BEGIN:variables
        private javax.swing.JButton btnStart;
        private javax.swing.JButton btnStop;
        private javax.swing.JPanel buttonPanel;
        private javax.swing.JCheckBox chkUseGoodWorker;
        // End of variables declaration//GEN-END:variables
    // -- The End --

  • Inconsistent ArrayIndexOutOfBoundsException using SwingWorker worker thread

    On occasions I will get the following exception thrown whenever I happen to be using SimpleBrowser.this.processor.processTask() method to run a SwingWorker<Void, Void>-based class Task worker thread (within doInBackground()) :
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
            at javax.swing.text.BoxView.getOffset(BoxView.java:1076)
            at javax.swing.text.BoxView.childAllocation(BoxView.java:670)
            at javax.swing.text.CompositeView.getChildAllocation(CompositeView.java:215)
            at javax.swing.text.BoxView.getChildAllocation(BoxView.java:428)
            at javax.swing.plaf.basic.BasicTextUI$UpdateHandler.calculateViewPosition(BasicTextUI.java:1978)
            at javax.swing.plaf.basic.BasicTextUI$UpdateHandler.layoutContainer(BasicTextUI.java:1954)
            at java.awt.Container.layout(Container.java:1432)
            at java.awt.Container.doLayout(Container.java:1421)
            at java.awt.Container.validateTree(Container.java:1519)
            at java.awt.Container.validateTree(Container.java:1526)
            at java.awt.Container.validateTree(Container.java:1526)
            at java.awt.Container.validate(Container.java:1491)
            at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:639)
            at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:127)
            at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)I haven't found much reliable online information to illustrate this issue any further so I'm a bit in the dark. Following is my code that runs within the aforementioned worker thread which I believe throws the exception:
             * Use {@link #setWebBrowserURL} using a local {@link com.ppowell.tools.ObjectTools.SwingTools.Task}
            protected void processTask() {
                Task task = new Task() {
                    public Void doInBackground() {
                        int progress = 0;
                        while (!SimpleBrowser.this.builder.hasLoadedWebpage && progress < 100) {
                            SimpleBrowser.this.statusBar.setMessage("Attempting to load " + SimpleBrowser.this.getURL().toString());
                            this.setProgress(progress);
                            progress++;
                        SimpleBrowser.this.setWebBrowserURL();
                        try {
                            Thread.sleep(2500);
                        } catch (InterruptedException ignore) {} // DO NOTHING
                        if (SimpleBrowser.this.builder.hasLoadedWebpage) {
                            SimpleBrowser.this.statusBar.setMessage("Done");
                        return null;
                task.addPropertyChangeListener(SimpleBrowser.this);
                task.execute();
            }Is there a way I might at least be able to suppress this error (the GUI application browser functions just fine in spite of it), or, even better, solve this inconsistent problem?
    Thanks
    Phil

    I suspect that you need to "clean" your html priorto
    calling super.setText(). My guess is that you're
    yanking nodes from beaneath Swing while it'strying
    to render.
    In addition to that, you may want to use JTidy to
    clean up your html, and convert it to xhtml --again
    prior to calling super.setText().Problem is that however I clean up the HTML, the
    moment I try to reinsert back into the JEditorPane
    using setText(), I get EmptyStackException or I'll
    get NullPointerException or it just might work - same
    problem, different exception(s).Ok this time I am simply using setText() instead of setPage(), but the results are, while consistent, they are consistently completely wrong. The browser appears blank every time, no HTML can be retrieved (you get a NullPointerException if you try), all the while I can verify that that original HTML from the remote site is correct, it never, ever, inserts into JEditorPane.
    Here is my code:
    * SimpleHTMLRenderableEditorPane.java
    * Created on March 13, 2007, 3:39 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package com.ppowell.tools.ObjectTools.SwingTools;
    import java.io.*;
    import java.net.*;
    import javax.swing.JEditorPane;
    import javax.swing.text.html.HTMLEditorKit;
    * A safer version of {@link javax.swing.JEditorPane}
    * @author Phil Powell
    * @version JDK 1.6.0
    public class SimpleHTMLRenderableEditorPane extends JEditorPane {
        //--------------------------- --* CONSTRUCTORS *--
        // <editor-fold defaultstate="collapsed" desc=" Constructors ">
        /** Creates a new instance of SimpleHTMLRenderableEditorPane */
        public SimpleHTMLRenderableEditorPane() {
            super();
         * Creates a new instance of SimpleHTMLRenderableEditorPane
         * @param url {@link java.lang.String}
         * @throws java.io.IOException Thrown if an I/O exception occurs
        public SimpleHTMLRenderableEditorPane(String url) throws
    IOException {
            super(url);
         * Creates a new instance of SimpleHTMLRenderableEditorPane
         * @param type {@link java.lang.String}
         * @param text {@link java.lang.String}
        public SimpleHTMLRenderableEditorPane(String type, String text) {
            super(type, text);
         * Creates a new instance of SimpleHTMLRenderableEditorPane
         * @param url {@link java.net.URL}
         * @throws java.io.IOException Thrown if an I/O exception occurs
        public SimpleHTMLRenderableEditorPane(URL url) throws IOException
            super(url);
        // </editor-fold>
        //----------------------- --* GETTER/SETTER METHODS *--
        // <editor-fold defaultstate="collapsed" desc=" Getter/Setter
    Methods ">
         * Retrieve HTML content
         * @return html {@link java.lang.String}
        public String getText() {
            try {
                 * I decided to use {@link java.net.HttpURLConnection} to
    retrieve the
                 * HTML code from the remote site instead of using
    super.getText() because
                 * of the HTML code return constantly being stripped to
    primitive HTML
                 * template formatting irregardless of the original HTML
    source code
                HttpURLConnection conn =
    (HttpURLConnection)getPage().openConnection();
                conn.setUseCaches(false);
                conn.setDefaultUseCaches(false);
                conn.setDoOutput(false); // READ-ONLY
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(
                        conn.getInputStream()));
                int data;
                StringBuffer sb = new StringBuffer();
                char[] ch = new char[512];
                while ((data = in.read(ch)) != -1) {
                    sb.append(ch, 0, data);
                in.close();
                conn.disconnect();
                return sb.toString();
            } catch (IOException e) {
                return super.getText(); // DEFAULT TO USING
    super.getText() IF NO I/O CONNECTION
         * Overloaded to fix HTML rendering bug Bug ID: 4695909.
         * @param text {@link java.lang.String}
        public void setText(String text) {
            // Workaround for bug Bug ID: 4695909 in java 1.4
            // JEditorPane does not handle the META tag in the html HEAD
            if (isJava14() && "text/
    html".equalsIgnoreCase(getContentType())) {
                text = stripMetaTag(text);
            super.setText(text);
        // </editor-fold>
        //--------------------------- --* OTHER METHODS *--
        // <editor-fold defaultstate="collapsed" desc=" Methods ">
         * Clean HTML to remove things like <link>, <script>,
         * <style>, <object>, <embed>, and <!-- -->
         * Based upon <a href="http://bugs.sun.com/bugdatabase/view_bug.do?
    bug_id=4695909">bug report</a>
        public void cleanHTML() {
            try {
                setText(cleanHTML(getText()));
            } catch (Exception e) {} // DO NOTHING
         * Clean HTML
         * @param html {@link java.lang.String}
         * @return html {@link java.lang.String}
        public String cleanHTML(String html) {
            String[] tagArray = {"<LINK", "<SCRIPT", "<STYLE", "<OBJECT",
    "<EMBED", "<!--"};
            String upperHTML = html.toUpperCase();
            String endTag;
            int index = -1, endIndex = -1;
            for (int i = 0; i < tagArray.length; i++) {
                index = upperHTML.indexOf(tagArray);
    endTag = "</" + tagArray[i].substring(1,
    tagArray[i].length());
    endIndex = upperHTML.indexOf(endTag, index);
    while (index >= 0) {
    if (endIndex >= 0) {
    html = html.substring(0, index) +
    html.substring(html.indexOf(">", endIndex)
    + 1,
    html.length());
    upperHTML = upperHTML.substring(0, index) +
    upperHTML.substring(upperHTML.indexOf(">",
    endIndex) + 1,
    upperHTML.length());
    } else {
    html = html.substring(0, index) +
    html.substring(html.indexOf(">", index) +
    1,
    html.length());
    upperHTML = upperHTML.substring(0, index) +
    upperHTML.substring(upperHTML.indexOf(">",
    index) + 1,
    upperHTML.length());
    index = upperHTML.indexOf(tagArray[i]);
    endIndex = upperHTML.indexOf(endTag, index);
    // REF: http://forum.java.sun.com/thread.jspa?threadID=213582&messageID=735120
    html = html.substring(0, upperHTML.indexOf(">",
    upperHTML.indexOf("</HTML")) + 1);
    // REF: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5042872
    return html.trim();
    * This actually only obtains the URL; this serves as a retriever
    for cleanHTML(String html)
    * @param url {@link java.net.URL}
    * @return html {@link java.lang.String}
    public String cleanHTML(URL url) {
    try {
    HttpURLConnection conn =
    (HttpURLConnection)url.openConnection();
    conn.setUseCaches(false);
    conn.setDefaultUseCaches(false);
    conn.setDoOutput(false); // READ-ONLY
    BufferedReader in = new BufferedReader(
    new InputStreamReader(
    conn.getInputStream()));
    int data;
    StringBuffer sb = new StringBuffer();
    char[] ch = new char[512];
    while ((data = in.read(ch)) != -1) {
    sb.append(ch, 0, data);
    in.close();
    conn.disconnect();
    return cleanHTML(sb.toString());
    } catch (IOException e) {
    e.printStackTrace();
    return null;
    * Determine if java version is 1.4.
    * @return true if java version is 1.4.x....
    private boolean isJava14() {
    if (System.getProperty("java.version") == null) return false;
    return System.getProperty("java.version").startsWith("1.4");
    * Workaround for Bug ID: 4695909 in java 1.4, fixed in 1.5
    * JEditorPane fails to display HTML BODY when META tag included
    in HEAD section.
    * Code modified by Phil Powell
    * <html>
    * <head>
    * <META http-equiv="Content-Type" content="text/html;
    charset=UTF-8">
    * </head>
    * <body>
    * @param text html to strip.
    * @return same HTML text w/o the META tag.
    private String stripMetaTag(String text) {
    // String used for searching, comparison and indexing
    String textUpperCase = text.toUpperCase();
    int indexHead = textUpperCase.indexOf("<HEAD ");
    int indexMeta = textUpperCase.indexOf("<META ");
    int indexBody = textUpperCase.indexOf("<BODY ");
    // Not found or meta not inside the head nothing to strip...
    if (indexMeta == -1 || indexMeta < indexHead || indexMeta >
    indexBody) {
    return text;
    // Find end of meta tag text.
    int indexHeadEnd = textUpperCase.indexOf(">", indexMeta);
    // Strip meta tag text
    return text.substring(0, indexMeta - 1) +
    text.substring(indexHeadEnd + 1);
    // </editor-fold>
    Instead if you try
    browser.getText()
    You will get a NullPointerException
    If you try
        public void setText(String text) {
            // Workaround for bug Bug ID: 4695909 in java 1.4
            // JEditorPane does not handle the META tag in the html HEAD
            if (isJava14() && "text/
    html".equalsIgnoreCase(getContentType())) {
                text = stripMetaTag(text);
            System.out.println(text); // YOU WILL SEE CNN'S HTML
            super.setText(text);
            System.out.println(super.getText()); // SEE BELOW
        }You see only this:
    <html>
      <head>
      </head>
      <body>
        <p style="margin-top: 0">
        </p>
      </body>
    </html>

  • SwingWorker JavaDB Concurrency problems

    I have an application that computes statistics from values stored in a JavaDB database. I am trying to implement batch job functionality that will allow users to quickly run multiple analyses without the point-and-click of the GUI. Each analysis extends SwingWorker, which adds text to a JTextArea when the done() method is called. My problem is that I get a "java.sql.SQLException: No suitable driver found for jdbc:derby:C:/mydatabase" SQL exception sometimes. the code below illustrates my problem. I'm guessing that this is a concurrency issue, but I don't know how to fix it. Any suggestion?
    The GUI class is:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class MyGui extends JFrame{
         private static final long serialVersionUID = 1L;
         JTextField text = null;
         JPanel main = null;
         String connectionString = "jdbc:derby:C:/mydatabase";
         String tableName="MYTABLE";
         String selectStatement = "SELECT * FROM " + tableName;
         public MyGui(){
              super("Concurrency Test");
              this.setPreferredSize(new Dimension(300,100));
              getContentPane().add(getPanel());
         public JPanel getPanel(){
              JPanel main = new JPanel();
              main.setLayout(new GridLayout(1,1));
              text = new JTextField(30);
              text.setText("Start");
              main.add(text, BorderLayout.CENTER);
              return main;
         public void readDatabase(){     
              int count=0;
              for(int i=0;i<10000;i++){
                   count++;
                   try{
                        ConnectAndRead reader =  new ConnectAndRead(connectionString, selectStatement, text, count);
                        reader.execute();
                   }catch(Exception ex){
         public static void main(String[] args) {
              MyGui gui = new MyGui();
              gui.pack();
              gui.setVisible(true);
              gui.setResizable(false);
              gui.readDatabase();
    }And the Database connection class is:
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import javax.swing.JTextField;
    import javax.swing.SwingWorker;
    public class ConnectAndRead extends SwingWorker<String, Void>{
         String connectionString="";
         String selectStatement="";
         JTextField text=null;
         int count = 0;
         public ConnectAndRead(String connectionString, String selectStatement, JTextField text, int count){
              this.connectionString=connectionString;
              this.selectStatement=selectStatement;
              this.text=text;
              this.count=count;
         public String connectAndRead()throws SQLException{
              Connection conn = null;
              try{
                   conn = DriverManager.getConnection(connectionString);
                   Statement stmt=conn.createStatement(ResultSet.CONCUR_READ_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE);
                   ResultSet rs = stmt.executeQuery(selectStatement);
                   rs.close();
                   stmt.close();
                   conn.close();
                   String text = "Database access " + count + "(should be 10,000)";
                   return text;
              }catch(SQLException ex){
                   count--;
                   throw new SQLException(ex);
         protected String doInBackground() {
              String s = "";
              try{
                   s = connectAndRead();
              }catch(SQLException ex){
                   ex.printStackTrace();
              return s;
         @Override
         protected void done(){
              try{
                   text.setText(get());
              }catch(Exception ex){
                   ex.printStackTrace();
    }

    I believe I found the solution to my problem. It is posted here [http://forum.java.sun.com/thread.jspa?threadID=5298060&tstart=0] . Sorry for the cross posting.

  • SwingWorker button dithering issue

    I am new to swing and java gui development. What I am trying to do is dither some various GUI components (JButton, JSpinner) during one of my processing functions. I found out that I needed to use "SwingWorker" to accomplish this task. I used the following as an example but I am having issues with my implementation. http://java.sun.com/docs/books/tutorial/uiswing/components/progress.html
    The BGuiCtrl (Background Gui Control) class is what I am trying to use to
        class BGuiCtrl extends SwingWorker<Integer, Void>
             public BGuiCtrl()
            public Integer doInBackground()
                            //this dithers all of the gui components
                           //e.g. exitButton.setEnabled(b);
                   setEnableItems(false);
                   return new Integer(0);
         BGuiCtrl bGuiCtrl = new BGuiCtrl();
         bGuiCtrl.execute();I execute the above in my processing function but it doesn't seem to work. The SwingWorker seems to be called correctly as I put in a count and just printed it out to the standard output and it is counting correctly so I know it is being executed. I have googled around and tried to find some different examples but I keep running into the same issue. Any tips or direction would be appreciated.

    Assuming all you want to do is disable some buttons (for example) during a long-running task, then re-enable them, this can also be done without SwingWorker since the amount of GUI-related changes is minimal (and just at the start and end of your processing):
    new Thread(new Runnable() {
       public void run() {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                setEnableItems(false);
          // Do your non-GUI related stuff.
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                setEnableItems(true);
    }).start();If you're doing more updating of the GUI than just at the beginning and the end of your processing, SwingWorker is of course an excellent choice.

  • SwingWorker - why can't I do this

    //StringWorker.java
    package myPackage;
    import javax.swing.SwingWorker;
    public class StringWorker extends SwingWorker<Void, Void>
          public StringWorker(String s)
                s = new String("Today is a sunny day.");
          protected Void doInBackground( ) throws Exception
                return null;
    //Driver.java
    package myPackage;
    public class Driver
          public static void main(String[] args)
               String str = null;
               StringWorker sw = new StringWorker(str);
               sw.execute( );
               while( !sw.isDone( ) )
                   System.out.println("Wait...");
               System.out.println(str);
    }Output:
    Wait...
    null

    Try this:
    //StringWorker.java
    package myPackage;
    import javax.swing.SwingWorker;
    public class StringWorker extends SwingWorker<Void, Void>
          public StringWorker(String[] s)
                s[0] = "Today is a sunny day.";
          protected Void doInBackground( ) throws Exception
                return null;
    //Driver.java
    package myPackage;
    public class Driver
          public static void main(String[] args)
               String[] str = new String[1];
               StringWorker sw = new StringWorker(str);
               sw.execute( );
               while( !sw.isDone( ) )
                   System.out.println("Wait...");
               System.out.println(str[0]);
    }You have quite some reading to do. Here is something about Strings. Here is something about Objects. No claim as to completeness.

  • Cancelling one SwingWorker and starting another

    Hi,
    I have a SwingWorker that does something in the background. When the user presses a button, I want the old worker to get canceled and I want to start a new one. The old worker should do some clean up/logging and close.
    This is the code in my main dispatcher thread:
    public void keyTyped(KeyEvent e)
         if(_controlThread != null)
              _controlThread.cancel(true);
                    java.util.logging.Logger.getLogger("something").fine("output_here");
         _controlThread = new SwingWorker(...);
         _controlThread.execute();
    }The Swing Worker has
    if(this.isCancelled())
        Logger.getLogger("something").fine("closing");
        return;
    }The problem is that the new Worker never starts. Also I noticed that
    Logger.getLogger("something").fine("output_here");
    never logs, I wonder why that is.
    Anyone know what is going on here?
    Thanks

    While trying to reproduce my problem with SSCCE I found the problem.
    import java.awt.event.*;
    import java.util.concurrent.CancellationException;
    import java.util.concurrent.ExecutionException;
    import java.util.logging.*;
    import javax.swing.JFrame;
    import javax.swing.SwingWorker;
    import java.io.*;
    public class main
          * @param args
         public static void main(String[] args) throws IOException
              main a = new main();
              Manager b = a.new Manager();
         class Manager implements KeyListener
              private ControlThread _controlThread;
              Manager()
                   JFrame frame = new JFrame();
                   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frame.setVisible(true);
                   frame.addKeyListener(this);
                   frame.setSize(300,300);
              public void keyTyped(KeyEvent e)
                   if(_controlThread != null)
                        _controlThread.cancel(true);
                        System.out.println("cancelled thread");
                   _controlThread = new ControlThread();
                   _controlThread.execute();
              public void keyPressed(KeyEvent e){}
             public void keyReleased(KeyEvent e){}
         class ControlThread extends SwingWorker<Void, Void>
              public Void doInBackground()
                   System.out.println("I'm running");
                   try
                        //do some stuff
                        Thread.sleep(10000);
                   catch (InterruptedException ex)
                        System.out.println("I got cancelled");
                        return null;
                   System.out.println("I finished");
                   return null;
              public void done()
                   try
                        System.out.println("dd");
                        get();
                        System.out.println("ee");
                   catch(InterruptedException ie)
                        System.out.println(": Canceled in done()");
                   catch(ExecutionException ex)
                        System.out.println("Exception in ControlThread: done");
    }This code will fail with a CancellationException in done(). I never saw this exception because I was using loggers and didn't look at the console output. The solution is to catch the CancellationException in done(). The problem is that it is not-documented that get() can throw a CancellationException, because then eclipse would require me to catch it.
    Thanks for helping petes1234.

  • SwingWorker's execute consumes Errors?!

    I made a SwingWorker class ("Task") to get a progress bar. But after Hours of debugging i noticed that Task.execute() consumes all errors thrown while doing the Task but the done() method is executed fine. In my case the doInBackground Method could throw a OutOfMemoryError. So i tried the following to proove this strange behavior:
    class Task extends SwingWorker<Integer, Void> {
              @Override
              protected Integer doInBackground() {
                   System.out.println("here");
                   throw new OutOfMemoryError();
              @Override
              public void done() {
                   System.out.println("done");
              }the Task is executed like that:
    task = new Task;
    task.execute();all i see on console is "here" and "done" and no hint about an error (isCanceled=false, isDone()=true). So how to correctly handle possible Errors/Exceptions thrown on executing the Task? I don't want a ... catch(throwable) in my code?!

    You'll have to write a try/catch although you can just add a throw new RuntimeException(e) there of course.
    @Override
    public void done() {
      if(isCanceled()) {
        System.out.println("Canceled.");
      else {
        try {
          get();
          System.out.println("Completed.");
        catch(ExecutionException e) {
          System.out.println("Errored.");
          e.printStackTrace();
        catch(InterruptedException e) {
          System.out.println("Interrupted.");
    }

  • Cancel anonymous SwingWorker thread?

    Hello,
    A beginner question.
    I have a button (A) calling a method, lets call it private void B().
    Inside the method B() I have this:
    SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() { do some stuff }
    Anyway when I click the A button it calls the method b() and it works fine, the worker thread goes off and does what it needs to do.
    If I want to implement a Cancel button to cancel the SwingWorker thread started by private void B(), how should I do it?
    Thanks :)

    Using SwingWorker is rather neat, and surprisingly studious for a beginner. Make sure that you do non-Swing related work in doInBackground() and Swing-related stuff in done(), that mostly what SwingWorker is for.Yes, that is the way I'm using it together with setProgress to update a progress bar.Great. I hadn't even ever noticed the existence of this method! I learn someting new everyday.
    So, you're well ahead of me in terms of using the SwingWorker API! ;)
    Your problem is definitely with the Java lanuage, not the SwingWorker.
    Instead of using a local variable, make worker an attribute (of the class in which method b() is defined). Then in the action listener for the "Cancel" button, you can invoke the worker's cancel(boolean) method.
    I'm not quite sure what you mean exactly when you say an attribute. The method b() is defined within the class that displays the Swing GUI:
    public class ResyncWindow extends javax.swing.JFrame { } Do you want me to put the worker outside any methods?Yes, like this:
    public class ResyncWindow extends javax.swing.JFrame {
        SwingWorker<Void, Void> worker;
        public ResyncWindow() {
            ... // create launchButton, and wire its actionListener to trigger b()
            ... // create cancelButton, and wire its actionListener to trigger cancel()
        private void b() {
            worker = new SwingWorker<Void,Void>() {
                public void doInBackground() {
                    while (!isCancelled() { ..do stuff and set progress... }
            worker.execute();
            cancelButton.setEnabled(true);
            launchButton.setEnabled(false);
        private void cancel() {
             if (!worker.cancel()) {
                 ... // display error
             cancelButton.setEnabled(false);
             launchButton.setEnabled(true);
    }

Maybe you are looking for

  • Convert ALV report into PDF and mail ( Hierarchical List View )

    Hi All, I see many posts of PDF download but none resolve my issue. I am writing a report in APO SNP which fetches data and displays an alv using REUSE_ALV_HIERSEQ_LIST_DISPLAY as i need to show the result as a Hierarchical sequential list. I need to

  • Getting error while running baseline_update.sh

    Hi, getting the below error while running baseline_update script: [10.22.13 16:57:17] INFO: Pushing authoring content to dgraph: AuthoringDgraph [10.22.13 16:57:17] SEVERE: Service Unavailable (503): Occurred while executing line 5 of valid BeanShell

  • TS1559 Wifi still greyed out?

    Solutions i've tried to fix this problem: - Reset All Settings - Reset Network Settings - Turning iPhone off and back on - Restoring iPhone on iTunes - Turning Airplane mode on and back off This problem started happening after the 6.1.1 and 6.1.2 upd

  • Solaris 10 X86 With Symbios 22801 is not detecting harddisk

    HI I have installed Solaris x86 on SUN FIRE V20z Machine. I have added additional Scsi card SYMBIOS 22801 before installation. At bios level I can see the disks getting intialised but at os level it is not. I tried booting with fail safe ( 32 bit ker

  • Content Engine on PIX DMZ

    Can we place content engine outside interface on PIX DMZ interface. At this moment both the WCCP router and content Engine are on outside. I want to place Content Engine Outside interface on PIX DMZ and then to run WCCP between Content Engine and Out