SwingWorker in JDK6

Hello,
We have written the application (everything works great in command line version), but now we need to create a GUI version. The user can run several processes of his choice in the order of his choice in the Worker thread in the doInBackground() method. Each consequtive SwingWorker accepts the Object which the previous one returns.
I can not put the SwingWorker2 in SwingWorker1 done() method to wait until SwingWorker1 finishes to grab the object returned, as I do not know in which order they execute, that is up to user to decide.
The problem is that I can not call them like this in the Event Dispatch Thread either:
SwingWorker sw1 = MySwingWorker1( ....);
sw1.execute;
Object obj2 = sw1.get();
SwingWorker sw2 = MySwingWorker2(obj1);
sw2.execute;
Object obj2 = sw1.get();
SwingWorker sw3 = MySwingWorker3(obj3);
sw3.execute;
Object obj3 = sw2.get();
and so on. They would not wait for each other.
Any idea how to approach that?
Thanks,
Vlad

Thank you for reply, but I am using this:
SwingWorker sw2 = MySwingWorker2(obj1);
sw2.execute;
Object obj2 = sw1.get();
SwingWorker sw3 = MySwingWorker3(obj3);
sw3.execute;
Object obj3 = sw2.get();
When I call get(), it freezes the gui. And it is expected to, according to
http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html#get()
"Note: calling get on the Event Dispatch Thread blocks all events, including repaints, from being processed until this SwingWorker is complete."
I need gui to be interactive, so user can monitor the process.
In order to avoid this, I need to call it from the done() method, but I have no way of knowing in which order the processes are executed.
Vlad

Similar Messages

  • SwingWorker JDK6 ... "event" missing on EDT

    Following strange behaviour I came accross, while I migrated from "classic"
    SwingWorker to the new SwingWorker in JDK6.
    A subclass of SwingWorker queries data from a server on the worker thread
    and then sets JTable data in it's EDT method.
    There ( at the end of the done() method) it calls directly
    firePropertyChange("data123", null, null)
    ... and this "event" was never seen again with JDK6.
    The properly registered PropertyChangeListener is simply nerver called.
    No error message shown whatsoever.
    It is reproducible.
    Whereby other PropertyChangeListeners on the same component,
    of which the "events" where also called direclty on EDT,
    do get their callbacks, e.g.
    firePropertyChange("rowinx", old, newrowinx);
    is propagated correctly to the very same JTable component.
    If I simply revert to extending "classic" SwingWorker in JDK6,
    everyting works fine, as it did before under JDK5.
    Did anyone observe similar strange behaviour with SwingWorker in JDK6?
    Any advice on this?
    Greetings,
    Lophiomys
    PS:
    If I can put up some spare time, I'll try to create a simplified test case.

    I don't have 1.6 source to hand but it sounds like the code is now checking that "oldValue" and "newValue" are the same and thus no event needs to be propagated, regardless of what that actual value is - ie without realising that nulls have specific meaning in this context. It's worth downloading the source code to double check this - or if anyone else has it to hand maybe they can look.
    I've seen more than one bug appear on the database related to null property names and/or values in PropertyChangeEvents - seems there's some lack of clarity within Sun about the slightly unusual semantics of 'null' here (I seem to recall I've tripped over it myself, as well), so I wouldn't be surprised if this was a new bug.

  • Using a SwingWorker in an Executor class?

    Here's some code that works and does what I want but I don't know if its a good idea....
    I have a program that may run one of a couple dozen long operations. I want to bring up a progress dialog to show the user how these operations are coming along.
    I was using a swing worker every time I ran a long task but its a pain to make changes in so many different places. So I set up the approach below.
    import java.util.concurrent.Executor;
    import javax.swing.JOptionPane;
    import com.sun.java.help.impl.SwingWorker;
    * This class takes a long task as a Runnable and
    * runs it while showing a progress dialog
    public class MyExecutor implements Executor
         public void execute(Runnable r)
              final MySmallProgressWindow dialog;
              dialog = new MySmallProgressWindow();
              final Runnable fr = r;
              dialog.show("Testing Executor ") ;
              final SwingWorker worker = new SwingWorker()
                   public Object construct()
                        try
                            fr.run();
                       catch(Exception g)
                             System.err.println(g);
                             JOptionPane.showMessageDialog(null, "Error: " + g.toString(), "Error", JOptionPane.ERROR_MESSAGE);
                       finally
                            dialog.hide();
                            System.out.println("Clean up here in finally");
                       return null;
                   public void finished()
                           dialog.hide();
             worker.start();
    I call it this way
    MyExecutor execute = new MyExecutor();                   
    Runnable runnableCopy = new Runnable() {
    public void run() {
         someLongTask();
    execute.execute(runnableCopy);Comments?
    Message was edited by:
    legoqueen

    import javax.swing.*;
    public class MyApplet extends JApplet {
         public void init() {
              //init stuff here
         public void start() {
              //start stuff here
         public static void main(String[] args) {
              JFrame f = new JFrame();
              JApplet a = new MyApplet();
              f.getContentPane().add(a);
              f.setSize(600, 400);
              f.setVisible(true);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              a.init();
              a.start();
    }Excuse me, but is there a way to do this on Applet only instead of JApplet... I was told we need to use Applet only...

  • Problems with SwingWorker and classes in my new job, ;), can you help me?

    Hi all, ;)
    First of all, sorry about my poor English.
    I have a problem with Swing and Threads, I hope you help me (because I'm in the firsts two weeks in my new job)
    I have two classes:
    Form1: Its a JPanel class with JProgressBar and JLabel inside.
    FormularioApplet: (the main) Its a JPanel class with a form1 inside.
    I have to download a file from a server and show the progress of the download in the JProgressBar. To make it I do this:
    In Form1 I make a Thread that update the progress bar and gets the fole from the server.
    In FormularioApplet (the main) I call to the method getDownloadedFile from Form1 to get the File.
    THE PROBLEM:
    The execution of FormularioApplet finishes before the Thread of Form1 (with download the file) download the file. Then, when I call in FormularioApplet the variable with the file an Exception: Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException is generated.
    First main begins his execution, then call to Form1 (a thread) then continues his execution and when the execution is finished ends the execution os Form1 and his thread.
    How can I do for main class call the function and the Thread download his file after main class assign the file of return method?
    How can I pass information froma class include an a main class. Form1 can't send to main (because main class made a Form1 f1 = new Form1()) any information from his end of the execution. I think if Form1 can say to main class that he finishes is job, then main class can gets the file.
    I put in bold the important lines.
    Note: My level of JAVA, you can see, is not elevated.
    THANKS A LOT
    Form1 class:
    package es.cambrabcn.signer.gui;
    import java.awt.HeadlessException;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.StringTokenizer;
    import java.util.Vector;
    import javax.swing.SwingUtilities;
    public class Form1 extends javax.swing.JPanel {
        //Variables relacionadas con la clase original DownloadProgressBar
        private InputStream file;
        private int totalCicles;
        private int totalFiles;
        private int currentProgress;
        private SwingWorker worker;
        private ByteArrayOutputStream byteArray;
        private boolean done;
        /** Creates new form prueba */
        public Form1() {
            initComponents();
            this.byteArray = new ByteArrayOutputStream();
            progressBar.setStringPainted(true);
            //this.totalFiles = totalFiles;
            currentProgress = 0;
        /** 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=" C�digo Generado ">                         
        private void initComponents() {
            label1 = new javax.swing.JLabel();
            progressBar = new javax.swing.JProgressBar();
            statusLabel = new javax.swing.JLabel();
            setBackground(new java.awt.Color(255, 255, 255));
            setMaximumSize(new java.awt.Dimension(300, 150));
            setMinimumSize(new java.awt.Dimension(300, 150));
            setPreferredSize(new java.awt.Dimension(300, 150));
            label1.setFont(new java.awt.Font("Arial", 1, 18));
            label1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            label1.setText("Barra de progreso");
            statusLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            statusLabel.setText("Cargando");
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                    .addContainerGap()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, statusLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, progressBar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, label1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE))
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(label1)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(statusLabel)
                    .addContainerGap(73, Short.MAX_VALUE))
        }// </editor-fold>                       
        // Declaraci�n de variables - no modificar                    
        private javax.swing.JLabel label1;
        private javax.swing.JProgressBar progressBar;
        private javax.swing.JLabel statusLabel;
        // Fin de declaraci�n de variables                  
        public byte[] getDownloadedFile(String documentToSign){
             //Variables locales
             byte puente[] = null;
             try{
                //Leemos el documento a firmar
                StringTokenizer st = new StringTokenizer(documentToSign, ";");
                Vector<URL> fileURL = new Vector<URL>();
                HttpSender sender = new HttpSender(null);
                //Introducimos la lista de URLs de archivos a bajar en el objeto Vector
                for(; st.hasMoreTokens(); fileURL.add(new URL(st.nextToken())));
                //Para cada URL descargaremos un archivo
                for(int i = 0; i < fileURL.size(); i++) {
                    file = sender.getMethod((URL)fileURL.get(i));
                    if(file == null) {
                        Thread.sleep(1000L);
                        throw new RuntimeException("Error descarregant el document a signar.");
                    System.out.println("Form1 Dentro de getDownloadFile, Antes de startDownload()");
                    //Fijamos el valor del n�mero de ciclos que se har�n seg�n el tama�o del fichero
                    this.totalCicles = sender.returnCurrentContentLength() / 1024;
                    this.progressBar.setMaximum(totalCicles);
                    //Modificamos el texto del JLabel seg�n el n�mero de fichero que estemos descargando
                    this.statusLabel.setText((new StringBuilder("Descarregant document ")).append(i + 1).append(" de ").append(fileURL.size()).toString());
                    statusLabel.setAlignmentX(0.5F);
                    *//Iniciamos la descarga del fichero, este m�todo llama internamente a un Thread*
                    *this.startDownload();*
                    *System.out.println("Form1 Dentro de getDownloadFile, Despu�s de startDownload()");*
                    *//if (pane.showProgressDialog() == -1) {*
                    *while (!this.isDone()){*
                        *System.out.println("No est� acabada la descarga");*
                        *if (this.isDone()){*
                            *System.out.println("Thread ACABADO --> Enviamos a puente el archivo");*
                            *puente = this.byteArray.toByteArray();*
                            *System.out.println("Form1 getDownloadFile() tama�o puente: " + puente.length);*
                        *else{*
                            *Thread.sleep(5000L);*
    *//                        throw new RuntimeException("Proc�s de desc�rrega del document a signar cancel�lat.");*
            catch (HeadlessException e) {
                    //javascript("onSignError", new String[] {
                    //(new StringBuilder("UI: ")).append(e.getMessage()).toString()});
            e.printStackTrace();
            catch (MalformedURLException e) {
                    //javascript("onSignError", new String[] {
                    //(new StringBuilder("CMS: ")).append(e.getMessage()).toString()});
            e.printStackTrace();
            catch (HttpSenderException e) {
                    //javascript("onSignError", new String[] {
                    //(new StringBuilder("CMS: ")).append(e.getMessage()).toString()});
            e.printStackTrace();
            catch (InterruptedException e) {
                    //javascript("onSignError", new String[] {
                    //(new StringBuilder("CMS: ")).append(e.getMessage()).toString()});
            e.printStackTrace();
            //System.out.println("Form1 getDownloadFile() tama�o puente: " + puente.length);
            return puente;
        public void updateStatus(final int i){
            Runnable doSetProgressBarValue = new Runnable() {
                public void run() {
                    progressBar.setValue(i);
            SwingUtilities.invokeLater(doSetProgressBarValue);
        public void startDownload() {
            System.out.println("Form1 Inicio startDownload()");
            System.out.println("Form1 Dentro de startDownload, antes de definir la subclase SwingWorker");
            System.out.println(done);
            worker = new SwingWorker() {
                public Object construct() {
                    System.out.println("Form1 Dentro de startDownload, dentro de construct(), Antes de entrar en doWork()");
                    return doWork();
                public void finished() {
                    System.out.println("Form1 Dentro de startDownload, dentro de finished(), Antes de asignar done = true");
                    System.out.println(done);
                    done = true;
                    System.out.println("Form1 Dentro de startDownload, dentro de finished(), Despu�s de asignar done = true");
                    System.out.println(done);
                    statusLabel.setText("Completado, tama�o del archivo: " + (byteArray.size() / 1024) + "KB");
            System.out.println("Form1 Dentro de startDownload, antes de worker.start()");
            worker.start();
            System.out.println("Form1 Dentro de startDownload, antes de salir de startDownload");
            System.out.println(done);
            System.out.println("Form1 Dentro de startDownload, despu�s de worker.start()");
         * M�todo doWork()
         * Este m�todo descarga por partes el archivo que es necesario descargar, adem�s de actualizar
         * la barra de carga del proceso de carga de la GUI.
        public Object doWork() {
            System.out.println("Form1 doWork() this.byteArray.size(): " + this.byteArray.size());
            try {
                byte buffer[] = new byte[1024];
                for(int c = 0; (c = this.file.read(buffer)) > 0;) {
                    this.currentProgress++;
                    updateStatus(this.currentProgress);
                    this.byteArray.write(buffer, 0, c);
                this.byteArray.flush();
                this.file.close();
                this.currentProgress = totalCicles;
                updateStatus(this.currentProgress);
            } catch(IOException e) {
                e.printStackTrace();
            System.out.println("Form1 doWork() FINAL this.byteArray.size(): " + this.byteArray.size());
            //done = true;
            System.out.println("AHORA DONE = TRUE");
            return "Done";
        public boolean isDone() {
            return this.done;
    FormularioApplet class (main)
    package es.cambrabcn.signer.gui;
    import java.awt.Color;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.net.URL;
    import java.security.Security;
    import java.util.StringTokenizer;
    import java.util.Vector;
    import javax.swing.SwingUtilities;
    import netscape.javascript.JSObject;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    import sun.security.provider.Sun;
    import be.cardon.cryptoapi.provider.CryptoAPIProvider;
    public class FormularioApplet extends java.applet.Applet {
        //Variables globales
        int paso = 0;
        private static final String JS_ONLOAD = "onLoad";
        private static final String JS_ONLOADERROR = "onLoadError";
        private static final int SIGNATURE_PDF = 1;
        private static final int SIGNATURE_XML = 2;
        //private String signButtonValue;
        private int signatureType;
        private String documentToSign;
        private String pdfSignatureField;
        private Vector<String> outputFilename;
        private Color appletBackground = new Color(255, 255, 255);
        private Vector<byte[]> ftbsigned;
         * Initializes the applet FormularioApplet
        public void init(){
            try {
                SwingUtilities.invokeLater(new Runnable() {
                //SwingUtilities.invokeAndWait(new Runnable() {
                //java.awt.EventQueue.invokeAndWait(new Runnable() {
                    public void run() {
                        try{
                            readParameters();
                            initComponents();
                        catch(FileNotFoundException e){
                            javascript(JS_ONLOADERROR, new String[] {
                                (new StringBuilder("Init: ")).append(e.getMessage()).toString()});
                            e.printStackTrace();                       
                        catch(IOException e) {
                            javascript(JS_ONLOADERROR, new String[] {
                                (new StringBuilder("Init: ")).append(e.getMessage()).toString()});
                            e.printStackTrace();
            catch (Exception e) {
                javascript(JS_ONLOADERROR, new String[] {
                    (new StringBuilder("Init: ")).append(e.getMessage()).toString()});
                e.printStackTrace();
            javascript(JS_ONLOAD, null);
        /** This method is called from within the init() method 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=" C�digo Generado ">
        private void initComponents() {
            this.setSize(350, 450);
            appletPanel = new javax.swing.JPanel();
            jPanel1 = new javax.swing.JPanel();
            jTextField1 = new javax.swing.JLabel();
            jPanel2 = new javax.swing.JPanel();
            label = new javax.swing.JLabel();
            jPanel3 = new javax.swing.JPanel();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            setLayout(new java.awt.BorderLayout());
            appletPanel.setBackground(new java.awt.Color(255, 255, 255));
            appletPanel.setMaximumSize(new java.awt.Dimension(350, 430));
            appletPanel.setMinimumSize(new java.awt.Dimension(350, 430));
            appletPanel.setPreferredSize(new java.awt.Dimension(350, 430));
            jPanel1.setBackground(new java.awt.Color(255, 255, 255));
            jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 102, 204)));
            jTextField1.setFont(new java.awt.Font("Arial", 1, 18));
            jTextField1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            jTextField1.setText("SIGNATURA ELECTRONICA");
            org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                    .addContainerGap())
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE)
                    .addContainerGap())
            jPanel2.setBackground(new java.awt.Color(255, 255, 255));
            jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 102, 204)));
            label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            label.setIcon(new javax.swing.ImageIcon("C:\\java\\workspaces\\cambrabcn\\firmasElectronicas\\logo.gif"));
            org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(label, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                    .addContainerGap())
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(label)
                    .addContainerGap(229, Short.MAX_VALUE))
            jPanel3.setBackground(new java.awt.Color(255, 255, 255));
            jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 102, 204)));
            //this.jButton1.setVisible(false);
            //this.jButton2.setVisible(false);
            jButton1.setText("Seg\u00fcent");
            jButton1.setAlignmentX(0.5F);
            //Cargamos el primer formulario en el JPanel2
            loadFirstForm();
            //Modificamos el texto del bot�n y el contador de pasos.
            //this.jButton1.setText("Siguiente");
            //this.jButton1.setVisible(true);
            //this.jButton2.setVisible(true);
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            jButton2.setText("Cancel\u00b7lar");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
            org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
            jPanel3.setLayout(jPanel3Layout);
            jPanel3Layout.setHorizontalGroup(
                jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 94, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 112, Short.MAX_VALUE)
                    .add(jButton2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 102, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
            jPanel3Layout.setVerticalGroup(
                jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jButton2)
                        .add(jButton1))
                    .addContainerGap())
            org.jdesktop.layout.GroupLayout appletPanelLayout = new org.jdesktop.layout.GroupLayout(appletPanel);
            appletPanel.setLayout(appletPanelLayout);
            appletPanelLayout.setHorizontalGroup(
                appletPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, appletPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .add(appletPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addContainerGap())
            appletPanelLayout.setVerticalGroup(
                appletPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, appletPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
            add(appletPanel, java.awt.BorderLayout.CENTER);
        }// </editor-fold>
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
            this.destroy();
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            changeForms(this.paso);
        // Declaraci�n de variables - no modificar
        private javax.swing.JPanel appletPanel;
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JPanel jPanel2;
        private javax.swing.JPanel jPanel3;
        private javax.swing.JLabel jTextField1;
        private javax.swing.JLabel label;
        // Fin de declaraci�n de variables
         * M�todo readParameters
         * M�todo que inicializa los valores de los par�metros internos, recibidos por par�metro.
        private void readParameters() throws FileNotFoundException, IOException {
             ???????????????? deleted for the forum
            addSecurityProviders();
         * M�tode loadFirstForm
         * Aquest m�tode carrega a jPanel2 el formulari que informa sobre la c�rrega dels arxius
        private void loadFirstForm(){
            //Form1 f1 = new Form1(stream, i + 1, fileURL.size(), sender.returnCurrentContentLength(), appletBackground);
            //Form1 f1 = new Form1(fileURL.size(), sender.returnCurrentContentLength());
            Form1 f1 = new Form1();
            //Lo dimensionamos y posicionamos
            f1.setSize(310, 150);
            f1.setLocation(10, 110);
            //A�adimos el formulario al JPanel que lo contendr�
            this.jPanel2.add(f1);
            //Validem i repintem el JPanel
            jPanel2.validate();
            jPanel2.repaint();
            //Descarreguem l'arxiu a signar
            *System.out.println("FormularioApplet Dentro de loadFirstForm(), antes de llamar a getDownloadFile()");*
            *byte obj[] = f1.getDownloadedFile(this.documentToSign);*
            if (obj == null){
                System.out.println("Lo que devuelve f1.getDownloadedFile(this.documentToSign) es NULL");
            else{
                System.out.println("Lo que devuelve f1.getDownloadedFile(this.documentToSign) NO es NULL");
                System.out.println("obj: " + obj.length);
            this.ftbsigned.add(obj);
            System.out.println("FormularioApplet Dentro de loadFirstForm(), despu�s de llamar a getDownloadFile()");
            //Indicamos que el primer paso ya se ha efectuado
            this.paso++;
         * M�tode changeForms
         * Aquest m�tode carrega a jPanel2 un formulari concret segons el valor de la variable global "paso"
        private void changeForms(int paso){
            /*A cada paso se cargar� en el JPanel y formulario diferente
             * Paso previo: Se realiza en la inicializaci�n, carga el formulario, descarga el archivo y muestra la barra de carga.
             * Case 1: Se carga el formulario de selecci�n de tipo de firma.
             * Case 2: Se carga el formulario de datos de la persona que firma.
            this.paso = paso;
            switch(paso){
                case 1:
                    //Creamos un objeto de formulario (seleccion de tipo de firma)
                    Form2 f2 = new Form2();
                    //Lo dimensionamos y posicionamos
                    f2.setSize(310, 185);
                    f2.setLocation(10, 110);
                    //Quitamos el formulario 1 y a�adimos el formulario 2 al JPanel
                    this.jPanel2.remove(1);
                    this.jPanel2.add(f2);
                    //Validem i repintem el JPanel
                    jPanel2.validate();
                    jPanel2.repaint();
                    //Modificamos el contador de pasos.
                    this.paso++;
                    break;
                case 2:
                    //Creamos un objeto de formulario (seleccion de tipo de firma)
                    Form3 f3 = new Form3();
                    //Lo dimensionamos y posicionamos
                    f3.setSize(310, 175);
                    f3.setLocation(15, 130);
                    //Quitamos el formulario 1 y a�adimos el formulario 3 al JPanel
                    this.jPanel2.remove(1);
                    this.jPanel2.add(f3);
                    //Validem i repintem el JPanel
                    jPanel2.validate();
                    jPanel2.repaint();
                    //Modificamos el texto del bot�n y el contador de pasos.
                    this.jButton1.setText("Finalizar");
                    this.paso++;
                    break;
                default:
                    //Finalizar el Applet
                    //C�digo que se encargue de guardar el archivo en el disco duro del usuario
                    break;
        private void addSecurityProviders() throws FileNotFoundException, IOException {
            Security.addProvider(new CryptoAPIProvider());
            if (signatureType == SIGNATURE_PDF) {
                Security.addProvider(new BouncyCastleProvider());
            else {
                Security.addProvider(new Sun());
        private File createOutputFile(String filename, int index) {
            return new File((String)outputFilename.get(index));
        protected Object javascript(String function, String args[]) throws RuntimeException {
            //Remove
            if (true) return null;
            try {
                Vector<String> list = new Vector<String>();
                if(args != null) {
                    for(int i = 0; i < args.length; i++) {
                        list.addElement(args);
    if(list.size() > 0) {
    Object objs[] = new Object[list.size()];
    list.copyInto(objs);
    return JSObject.getWindow(this).call(function, objs);
    } catch(UnsatisfiedLinkError e) {
    e.printStackTrace();
    throw new RuntimeException((new StringBuilder()).append(e).append("\nFunci�: ").append(function).toString());
    } catch(Throwable e) {
    e.printStackTrace();
    throw new RuntimeException((new StringBuilder()).append(e).append("\nFunci�: ").append(function).toString());
    return JSObject.getWindow(this).call(function, new Object[0]);
    Edited by: Kefalegereta on Oct 31, 2007 3:54 AM
    Edited by: Kefalegereta on Oct 31, 2007 4:00 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    Look at iOS Troubleshooting Wi-Fi networks and connections  http://support.apple.com/kb/TS1398
    iPad: Issues connecting to Wi-Fi networks  http://support.apple.com/kb/ts3304
    iOS: Recommended settings for Wi-Fi routers and access points  http://support.apple.com/kb/HT4199
    Additional things to try.
    Try this first. Turn Off your iPad. Then turn Off (disconnect power cord) the wireless router & then back On. Now boot your iPad. Hopefully it will see the WiFi.
    Go to Settings>Wi-Fi and turn Off. Then while at Settings>Wi-Fi, turn back On and chose a Network.
    Change the channel on your wireless router. Instructions at http://macintoshhowto.com/advanced/how-to-get-a-good-range-on-your-wireless-netw ork.html
    Another thing to try - Go into your router security settings and change from WEP to WPA with AES.
    How to Quickly Fix iPad 3 Wi-Fi Reception Problems
    http://osxdaily.com/2012/03/21/fix-new-ipad-3-wi-fi-reception-problems/
    If none of the above suggestions work, look at this link.
    iPad Wi-Fi Problems: Comprehensive List of Fixes
    http://appletoolbox.com/2010/04/ipad-wi-fi-problems-comprehensive-list-of-fixes/
    Fix iPad Wifi Connection and Signal Issues  http://www.youtube.com/watch?v=uwWtIG5jUxE
    ~~~~~~~~~~~~~~~
    If any of the above solutions work, please post back what solved your problem. It will help others with the same problem.
     Cheers, Tom

  • How to return more than one object from SwingWorker

    I am using a SwingWorker to call 3 different methods of another class (data fetch class). Each of these 3 methods returns a String array. I am able to get the first array outside the thread code using the get() method of the SwingWorker class,
    final String tmpOrdNum = OrderNum;
    SwingWorker worker = new SwingWorker() {
         DATA_FETCH_TO_ARRAY data_fetch = new DATA_FETCH_TO_ARRAY(tmpOrdNum);
         public Object construct(){
              String [] orderArr = data_fetch.getHeaderArray();
              //String [] detailArr = data_fetch.getDetailArray();
              //String [] storeArr = data_fetch.getStoreArray();                    
              return orderArr;
         //Runs on the event-dispatching thread.
         public void finished(){     }
    worker.start() ;
    String[] testArr = (String[])worker.get();      //gets the header array
    /* HOW DO I GET THE DETAIL AND STORE ARRAYS HERE?*/I want to be able to call the other 2 methods of the data fetch class - getDetailArray() and getStoreArray() shown commented in the above code one by one.
    Can someone please suggest a way of doing this? Thank you.

    Return String[][] from construct method.
    Here is an example (observe test method):
    import java.util.*;
    public class ArrayTest{
         public static void main(String[] args){
              String[][] result=(String[][])new ArrayTest().test();          
              System.out.println("result1: "+Arrays.toString(result[0]));
              System.out.println("result2: "+Arrays.toString(result[1]));
              System.out.println("result3: "+Arrays.toString(result[2]));
         public Object test(){
              String[] str1={"A","B","C"};
              String[] str2={"M","N","O"};
              String[] str3={"X","Y","Z"};          
              String[][] out=new String[3][];
              out[0]=str1;
              out[1]=str2;
              out[2]=str3;
              return out;
    }Thanks,
    Mrityunjoy

  • Should I use a SwingWorker or SwingUtilities.invokeLater() to update my UI?

    Are there specific situations where you want to use method above the other? This whole swing concurrency is very new to me, and I don't really know where to begin.

    When executing long running code you don't want the GUI to freeze. Therefore you have two things to be concerned about. First, you want the long running task to execute in a separate Thread. Secondly, when you need to update the GUI from this code you need to make sure the code executes on the Event Dispatch Thread (EDT).
    You can code this manually by creating a separate Thread and then use SwingUtilities.invokeLater() when necessary.
    A SwingWorker tries to simplify this process by having a simple API where you can add code that executes on a separate Thread or where you can add code that executes on the EDT.
    So in the case of managing long running tasks, the end result should be the same.
    Hwever, there are times when I know code is already executing on the EDT, but I sometimes use invokeLater(..) to force my code to the end of the EDT. This is used in special situations when code doesn't execute in the order you want.
    For example, I've tried to add a FocusListener to a JFormattedTextField to "select the text" when it gains focus. The problem is the the UI also adds a FocusListener. Because of the way listeners are handled the last listener added to the component executes first. Therefore, using the invokeLater() forces my listener code to execute last.
    You can try this code to see what I mean:
    KeyboardFocusManager.getCurrentKeyboardFocusManager()
         .addPropertyChangeListener("permanentFocusOwner", new PropertyChangeListener()
         public void propertyChange(final PropertyChangeEvent e)
              if (e.getNewValue() instanceof JTextField)
                   //  invokeLater needed for JFormattedTextField
                   SwingUtilities.invokeLater(new Runnable()
                        public void run()
                             JTextField textField = (JTextField)e.getNewValue();
                             textField.selectAll();
    });Edited by: camickr on Mar 5, 2011 2:36 PM

  • Output not appearing when using SwingWorker?

    Hi guys,
    I'm desperate here. Any help would be great.
    I'm using SwingWorker to append info into a Text Area, but when I run the code, nothing happens in the TextArea. Here's the code
    public class RLGUIFrame extends javax.swing.JFrame implements ActionListener{
        private final GridBagConstraints constraints;
        JTextArea movementText;
        private final Border border =
            BorderFactory.createLoweredBevelBorder();
        private final JButton startButton, stopButton;
        private RobotTask robTask;
         public static final int GRID_SIZE=10;
         public static final int NUMBER_OF_TIMES=1000;
        private JTextArea makeText() {
            JTextArea t = new JTextArea();
            t.setEditable(false);
            t.setAlignmentX(RIGHT_ALIGNMENT);
            t.setBorder(border);
            getContentPane().add(t, constraints);
            return t;
        private JButton makeButton(String caption) {
            JButton b = new JButton(caption);
            b.setActionCommand(caption);
            b.addActionListener(this);
            getContentPane().add(b, constraints);
            return b;
        public RLGUIFrame() {
            super("RL");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Make text boxes
            getContentPane().setLayout(new GridBagLayout());
            constraints = new GridBagConstraints();
            constraints.insets = new Insets(3, 10, 3, 10);
            movementText = makeText();
            //Make buttons
            startButton = makeButton("Start");
            stopButton = makeButton("Stop");
            stopButton.setEnabled(false);
            //Display the window.
            pack();
            setVisible(true);
        private class LocReport{
             private Location loc;
             private double val, rand;
             private boolean KS;
             LocReport(Location L, double value, boolean KillSpot, double random){
                  this.loc = L;
                  this.val = value;
                  this.KS = KillSpot;
                  this.rand = random;
    private class RobotTask extends SwingWorker<Void, LocReport> {
        @Override
        protected Void doInBackground() {
            Grid grid = new Grid( GRID_SIZE );
             Location startPosition = grid.getLoc( 8, 8 );
             Robot jerry = new Robot( startPosition );
             Random rand = new Random();
             grid.fillGrid();
            //EastWestSentry ews = new EastWestSentry( grid.getLoc(5, 5));
             grid.getLoc( 3 , 3 ).setValue( 1.0 );
             grid.getLoc( 7 , 7 ).setValue( 0.0 );
             for( int i = 0; i < GRID_SIZE; i++){
                  grid.getLoc( i, 4 ).isKillSpot = true;
             grid.getLoc(4, 5).isWindy    = true;
             grid.getLoc(7, 5).isKillSpot = true;
             grid.getLoc( 6, 4 ).isKillSpot = false;
             for( int i=0; i < NUMBER_OF_TIMES; i++ ){
             while ( jerry.getLocation() != grid.getLoc( 3 , 3 ) ){
             Location L = jerry.getLocation();
             double value = L.value;
             double random = rand.nextDouble();
             boolean isKS = L.KillSpot();
             publish( new LocReport(L,value,isKS,random) );
              if(jerry.getLocation().isWindy == true)
                   jerry.move( grid.getLoc(7, 5) );
              if( jerry.getLocation().hasSentry )
                        jerry.getLocation().isKillSpot = true;     
              if(jerry.getLocation().isKillSpot == true){
                   if( rand.nextDouble() > 0.5 ){
                        System.out.printf("Lucky this time. This killspot didn't kill me.\n");
                   }else{
                   grid.getLoc(jerry.getXCoord(), jerry.getYCoord()).setValue(-1);
                   jerry.regenerate( startPosition );
              if(rand.nextDouble()>0.8){
                   System.out.printf("I'm going exploring!\n");
                   jerry.exploratoryMove();
              else{
                   //ews.patrol();
                   jerry.move();
                   if( jerry.getMyPreviousLocation().isKillSpot &&
                        jerry.getMyPreviousLocation().getValue() > 0.0 ){
                        jerry.getMyPreviousLocation().setValue(-1);
             return null;
        protected void process(List<LocReport> locs) {
             LocReport location = locs.get( locs.size() - 1);
             movementText.append("========================\n");
             movementText.append("Robot is at location : " + location.loc.getXCoord() +
                                   ", " + location.loc.getYCoord() + "\n");
             movementText.append("It's value is : " + location.val + "\n");
    public void actionPerformed(ActionEvent e) {
        if ("Start" == e.getActionCommand()) {
            startButton.setEnabled(false);
            stopButton.setEnabled(true);
            (robTask = new RobotTask()).execute();
        } else if ("Stop" == e.getActionCommand()) {
            startButton.setEnabled(true);
            stopButton.setEnabled(false);
            robTask.cancel(true);
            robTask = null;
        * @param args the command line arguments
        public static void main(String args[]) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new RLGUIFrame();
    }Edited by: zimmerPlease on Mar 23, 2010 3:58 PM

    You're adding both components with the same GridBagConstraints without setting any of its attributes. Follow the link to the Swing tutorial efrom the topic listing page for this forum and click through to the Layouts section where you can learn how to use GridBagLayout and GridBagConstraints properly.
    As an aside, there is no need to extend JFrame to create a GUI that has to show a JFrame. Favor composition over inheritance. And in this case, it leads to add(...) coode being all over the place where it can't be easily found.
    db

  • Unable to change the thread's priority at linux jdk6

    i try to set the thread's priority to value like Thread.MIN_PRIORITY
    i observe the thread's priority by "threadump"
    the setting is ok at windows (XP + jdk5 build 1.5.0_12-b04)
    but not at linux jdk6 (build 1.6.0_04-b12)
    at linux, i see all threads at my server are with priority "10"
    (e.g. gc, finalizer, http listener etc)
    i am using tomcat (running as root), i have tried to set the "default thread priority", but still can't change the thread's priority
    and i have tried to add jvm options to "turn on" thread priority:
    -XX:+UseThreadPriorities -XX:ThreadPriorityPolicy=1
    but still no use
    so i guess this should be a problem of "linux" or jvm
    is there any hint if it is about jvm problem?
    thanks

    Hi David,
    >
    > > #com.sapportals.wcm.repository.manager.reporting.RPRepositoryManager#sap.com/irj#com.sapportals.wcm.repository.manager.reporting.RPRepositoryManager#Guest#0##n/a##9056c970715111de8591000c2942fce3#SAPEngine_Application_Thread[impl:3]_14##0#0#Error##Plain###setting initial ACL on /reporting_backend/reports/Content Administration/User related Cleanup/actioninbox.cleanup - com.sap.security.api.NoSuchRoleException: Role with uniqueName content_admin_role not found!
    >  at com.sap.security.core.imp.RoleFactory.getRoleByUniqueName(RoleFactory.java:1783)
    >  at com.sapportals.wcm.repository.RMAdapter.getResource(RMAdapter.java:228)
    >  at com.sapportals.wcm.repository.runtime.CmAdapter.findResource(CmAdapter.java:1349)
    >  at com.sapportals.portal.prt.dispatcher.Dispatcher.initDispatcher(Dispatcher.java:361)
    >
    Have you check this content_admin_role not found ?
    Thanks
    Sunny

  • How to get the errors thrown during SwingWorkes-doInBackground-method

    Hi,
    I got an annoying problem.
    I use a SwingWorker to do some operations in background...
    Now it could be, that some of those operations throw an exception...
    but the SwingWorker do not throw those...
    The only exception i get is a final Exception cause of an object who
    wants to display the result of the background activity...
    In detail : a method done in background throws an index out of bounds exception
    but how i can get this error?
    I try to surround the swing worker object with a try and catch for general exceptions but
    this don't work.
    regards
    Olek

    There are two things you can do. First, you might wrap the code in doInBackground() in try/catch. I'd discourage this since it will make your code more complicated. Secondly, if an exception occurs, the SwingWorker will switch its state to 'done'. If you invoke the get() method (even if you're returning null in doInBackground()), an ExecutionException will be risen. Using Exception#getCause(), you will get the original exception that occured, in your case the ArrayIndexOutOfBoundsException.

  • Using SwingWorker more than five times

    Hi there,
    I'm having a problem with the SwingWorker.
    A SwingWorker class is called for loading a large file into the database. After I have loaded five files to the database, the sixth loading isn't working and the GUI isn't responsing anymore. Is there a maximum number of SwingWorker Threads that can be used at a time?
    Everything else works fine, and sometimes I can even load more than five files, if the loadings are long enough after each other.
    Can anybody help?

    Darryl.Burke wrote:
    Could also be a problem arising out of not closing database connections when done with them.
    dbHighly probably--about 5 orphaned connections seems to be where things have gone bonkers for me in various languages in the past--C, C++, VB, C#, Pascal, Basic... argh! The mind dizzies.

  • Referencing an inner swingworker class in a JPanel class...?

    Hi,
    I've got an inner swingworker class defined inside an extended JPanel (we'll call it middleJ) class. Basically the swingworker class runs off a filtered file chooser. I have a method in the JPanel class that instantiates the inner class and kicks off the swing worker (we'll call it kickOffSwing). Now if I instantiate middleJ in an outer class and call the kickOffSwing() method, that should run the filtered filechooser right? Is this the right way to go about running a lengthy background process inside a nested class structure, or is there a more organised way of doing things?
    Cheers!

    Never mind. Got it working fine! I often find the act of putting together a question helps focus on the task at hnad.

  • Can not fine symbol... class SwingWorker is not working...

    Hi ,
    my code is like this. I am using netbeans ide 5.5.
    package concurrency;
    import java.util.List;
    import java.util.Random;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.GridBagLayout;
    import java.awt.GridBagConstraints;
    import java.awt.Insets;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.border.Border;
    import javax.swing.BorderFactory;
    import javax.swing.*;
    public class Flipper extends JFrame
    implements ActionListener {
    private final GridBagConstraints constraints;
    private final JTextField headsText, totalText, devText;
    private final Border border =
    BorderFactory.createLoweredBevelBorder();
    private final JButton startButton, stopButton;
    private FlipTask flipTask;
    private JTextField makeText() {
    JTextField t = new JTextField(20);
    t.setEditable(false);
    t.setHorizontalAlignment(JTextField.RIGHT);
    t.setBorder(border);
    getContentPane().add(t, constraints);
    return t;
    private JButton makeButton(String caption) {
    JButton b = new JButton(caption);
    b.setActionCommand(caption);
    b.addActionListener(this);
    getContentPane().add(b, constraints);
    return b;
    public Flipper() {
    super("Flipper");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Make text boxes
    getContentPane().setLayout(new GridBagLayout());
    constraints = new GridBagConstraints();
    constraints.insets = new Insets(3, 10, 3, 10);
    headsText = makeText();
    totalText = makeText();
    devText = makeText();
    //Make buttons
    startButton = makeButton("Start");
    stopButton = makeButton("Stop");
    stopButton.setEnabled(false);
    //Display the window.
    pack();
    setVisible(true);
    private static class FlipPair {
    private final long heads, total;
    FlipPair(long heads, long total) {
    this.heads = heads;
    this.total = total;
    private class FlipTask extends SwingWorker<Void, FlipPair> {
    @Override
    protected Void doInBackground() {
    long heads = 0;
    long total = 0;
    Random random = new Random();
    while (!isCancelled()) {
    total++;
    if (random.nextBoolean()) {
    heads++;
    publish(new FlipPair(heads, total));
    return null;
    @Override
    protected void process(List<FlipPair> pairs) {
    FlipPair pair = pairs.get(pairs.size() - 1);
    headsText.setText(String.format("%d", pair.heads));
    totalText.setText(String.format("%d", pair.total));
    devText.setText(String.format("%.10g",
    ((double) pair.heads)/((double) pair.total) - 0.5));
    public void actionPerformed(ActionEvent e) {
    if ("Start" == e.getActionCommand()) {
    startButton.setEnabled(false);
    stopButton.setEnabled(true);
    (flipTask = new FlipTask()).execute();
    } else if ("Stop" == e.getActionCommand()) {
    startButton.setEnabled(true);
    stopButton.setEnabled(false);
    flipTask.cancel(true);
    flipTask = null;
    public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    new Flipper();
    Though this code is taken from java.sun.com.
    but this code is not working.. It shows :
    Compiling 1 source file to F:\ ...\FlipperProject\build\classes
    F:\....\FlipperProject\src\concurrency\Flipper.java:73: cannot find symbol
    symbol : class SwingWorker
    location: class concurrency.Flipper
    private class FlipTask extends SwingWorker<Void, FlipPair> {
    F:\.......\FlipperProject\src\concurrency\Flipper.java:79: cannot find symbol
    symbol : method isCancelled()
    location: class concurrency.Flipper.FlipTask
    while (!isCancelled()) {
    F:\.....\FlipperProject\src\concurrency\Flipper.java:84: cannot find symbol
    symbol : method publish(concurrency.Flipper.FlipPair)
    location: class concurrency.Flipper.FlipTask
    publish(new FlipPair(heads, total));
    F:\.......\FlipperProject\src\concurrency\Flipper.java:74: method does not override a method from its superclass
    @Override
    F:\.......\FlipperProject\src\concurrency\Flipper.java:89: method does not override a method from its superclass
    @Override
    F:\......1\FlipperProject\src\concurrency\Flipper.java:105: cannot find symbol
    symbol : method execute()
    location: class concurrency.Flipper.FlipTask
    (flipTask = new FlipTask()).execute();
    F:\............\FlipperProject\src\concurrency\Flipper.java:109: cannot find symbol
    symbol : method cancel(boolean)
    location: class concurrency.Flipper.FlipTask
    flipTask.cancel(true);
    7 errors
    BUILD FAILED (total time: 4 seconds)
    please help...

    try right-clicking on the source and select fix imports.

  • SwingWorker behaviour on the Mac

    Hi everyone,
    I am fairly new to swing applications and am having a problem.
    I have written an app that fires off a SwingWorker thread and processes some work. The main thread has a Swing timer that fires, reads a ptogress value from the SwingWorker and updates a progressbar. When I run this on a Windows XP client it all behaves as expected. When I run it on a Mac OSX 10.2.8 the Timer event fires once and then the thread runs through and the Timer never fires again. When it did fires once it look as if something goes wrong when it accesses the SwingWorker.
    So it appears that I have a threading issue (only on the mac). The methods I access are synchronized. Is there anything else I should try.
    Thanks
    Pete

    can we have some code sample to look into it

  • Using jdk6 with oracle database

    hi..
    i've installed jdk6 into my pc. i would like to write a simple program using jdk6. then i would like to load it into oracle database. is that okay if i use jdk6 version to write my program? is it compatible with oracle 10g when we want load the java class file into oracle?please help..thanks..

    Hi,
    Oracle JVM in 11gR2 (the latest release) supports Java 1.5 only. So no, you won't be able to load classes compiled with target class level 1.6 into DB. But you surely may explicitly set target class level of 1.5 in javac and then load compiled classes. Or you may not use 1.6 features in your code and then CREATE JAVA SOURCE from it.

  • 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();

Maybe you are looking for

  • How to stop the subject field displaying in list of mail?

    Sorry for the spelling I am dyslex.. I like the new layout all virtical in mail 7 BUT in the list of messages it shows the "subject field" how do I stop this field from showing up? In the clasic view I can change what fields show up (menu "View" - "M

  • Depreciation for an Asset

    Hi Gurus, How can make a capitalised asset not depreciate or put the depreciation on hold for a year but the asset still forms part of my asset register. Please advise, Thanks, Themba

  • Bean-Managed vs. Container-Managed Persistence

    Hello, I would like the real world skinny on bean-managed persistence vs. container-managed persistence. I have heard the bean-managed offers higher scalability and performance, while container-managed offers simplicity but with a cost. Can someone g

  • ISight on MacBook die

    I have a problem like Gabe with him iSight. After PRAM and PMU reseting, camera works few weeks and stop again. After that work just one day and stop again I think that a problem appears after new EFI firmware update and/or BootCamp Beta instalation,

  • Upgrading from OCSG4.1.0 to OCSG4.1.1

    Hi, We have currently OCSG4.1.0 installed. How can we upgrade it OCSG4.1.1. Are there any patches available with which we can upgrade from OCSG4.1.0 to OCSG4.1.1. Thanks Anubhav