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.

Similar Messages

  • 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.

  • RFC Sender Asynchronous -- File Problem

    Hi all,
    I want to sent an asynchronous RFC to a file but when I execute my scenario in R3 it always returns a dump. In the XI monitoring I get the response error from the file: "Unable to read the payload from the message object".
    I think its strange because I even don't want the file adapter to send a response but he does. I suspect that the problem is on R3 side because it sends a synchronous RFC call, but I don't have any idea how to send an Asynchronous RFC call to XI (via the RFC adapter).
    Steps I made:
    - Created on R3 a TCP/IP entry as registered server program
    - Created in XI an RFC adapter with registered server program name
    - rest of the configuration...
    I think my main problem is that R3 expects an answer back because it throws a synchronous call to XI, but I don't have any clue how to set up an asynchronouss RFC call in R3 to XI (so my ABAP program doesn't dump).
    TIA

    Hi Peter,
    first, if you didn't already have done that, load up a RFC function module to XI Repository, where you have only the XSD, no abap source code.
    In a ABAP program code:
    CALL FUNCTION 'MyFunction'
    DESTIONATION 'mySM59Destination'
    IN BACKGROUND TASK
    ...  "the normal call
    COMMIT WORK.  
    Regards,
    Udo

  • Asynchronous method Problem?

    Hi
       I created one customized Business Object.
    In That BO i created one Asynchronous method.
    But i need to export some data's from that method. but export option is not possible for Asynchronous method.
    so i created same object and raised the event for that created object with the event container.
    For ur reference
    DATA: z_zassign TYPE SWC_OBJECT.
    swc_container a_container.
    swc_set_element a_container 'Sourcer' z_zsourcer.
    swc_create_object z_zassign 'zassign' OBJECT-KEY.
    swc_raise_event z_zassign 'Sourcer_assigned' a_container.
    " z_zsourcer getting from One Function Module
    " zassign is my Customized BO.
    It is working when i excute first time, it is passing the container (a_container)element to the task container.
    when i execute the second time it is not passing the value to the task container.
    plz give me some solution for this problem?

    Hello ,
    for your coding itself I had the following variation/suggestion:
    METHOD dialog_with_asynchronous_call.
       swc_container cont.
       REFRESH cont.
       swc_set_element cont 'Sourcer' source.
       swc_raise_event self 'Sourcer_assigned' cont.
       COMMIT WORK.
    ENDMETHOD.
    After the commit work statement, leave method immediatly.
    Best regards,
    Florin

  • Asynchronous Notifications problem

    Hi all,
    Now I am developing with Oracle Advance Queuing.
    In order to dequeue message from queue automatically when it arrives I have procedure dequeue as following:
    PROCEDURE dequeue(CONTEXT RAW
    ,reginfo sys.aq$_reg_info
    ,descr sys.aq$_descriptor
    ,payload RAW
    ,payloadl NUMBER) IS
    dq_opt dbms_aq.dequeue_options_t;
    msg_pro dbms_aq.message_properties_t;
    msg_id RAW(16);
    msg xmltype;
    Begin
    dq_opt.msgid := descr.msg_id;
    dq_opt.consumer_name := descr.consumer_name;
    dbms_aq.dequeue(queue_name => descr.queue_name
    ,dequeue_options => dq_opt
    ,message_properties => msg_pro
    ,payload => msg
    ,msgid => msg_id);
    End;
    Register dequeue procedure:
    declare
    reginfolist sys.aq$_reg_info_list;
    reginfo sys.aq$_reg_info;
    Begin
    reginfo := sys.aq$_reg_info(queue_in||':'||subscriber_name
    ,dbms_aq.namespace_aq
    ,'plsql://DEMO.dequeue'
    ,HEXTORAW('FF'));
    reginfolist := sys.aq$_reg_info_list(reginfo);
    dbms_aq.register(reginfolist, 1);
    End;
    subscriber_name is name of subscriber created as following command:
    s:=sys.aq$_agent(subscriber_name,queue_in||db_link,NULL);
    dbms_aqadm.add_subscriber(queue_name => qname, subscriber => s);
    queue_in: queue to receive message named DEMO.QUEUEIN
    qname : queue to send message named DEMO.QUEUEOUT
    But when DEMO.QUEUEOUT propagated messages to DEMO.QUEUEIN it
    was same no action in DEMO.QUEUEIN (message was stil in QUEUEIN until when I ran dequeue manually).
    Please show me How to debug this problem?

    Hello ,
    for your coding itself I had the following variation/suggestion:
    METHOD dialog_with_asynchronous_call.
       swc_container cont.
       REFRESH cont.
       swc_set_element cont 'Sourcer' source.
       swc_raise_event self 'Sourcer_assigned' cont.
       COMMIT WORK.
    ENDMETHOD.
    After the commit work statement, leave method immediatly.
    Best regards,
    Florin

  • VI Server Asynchronous VI Problems

    Hey everyone!
    I've attached some example VIs that I've been playing with, trying to understand how VI server works.  Could someone please take a quick look at them?  It's 3 counters, running at different rates, which write to global vars, these global vars are then monitored by another VI.  All of these VIs are loaded from a different VI through VI server, but I can't get them to run right.
    The main "loader" VI which makes all the VI server calls is called Main, the VI which monitors the counters, and the only VI which should be seen is called CountMain.
    Thanks for the help, and the extended labview development of my brain!
    Jonathan
    Attachments:
    asynch.zip ‏42 KB

    Hi Jonathan,
    I found a few problems with your VI.  The first is that all the paths to the VIs you're calling dynamically need the ".vi" extension on them...remember that when opening a VI reference, the path you specify needs to be the exact file path (including the file extension) to the VI on disk.  Next, I noticed that you have "Wait Until Done" on the "Main" VI set to True.  With this option set, you will never get to the FP.Open property, because the "Run VI" method will be waiting until the VI is finished, which will never happen if you don't have the panel showing so you can click the stop button.  Here are a few other general suggestions to help you along:
    1.  I would recommend using error IO on the nodes to dictate the program flow instead of a Sequence Structure.  In this way, your code is more readable, and you can find out about any errors that occur on your nodes when debugging problems.
    2.  You could have diagnosed the original problem by using Execution Highlighting on your VI...it would have shown you that there were errors on the Open VI Reference nodes because you had the paths specified incorrectly...you would have also seen that the VI was stuck on the Run VI method in the final sequence frame.
    I hope these suggestions help.  Good luck with your application!
    -D
    Darren Nattinger, CLA
    LabVIEW Artisan and Nugget Penman

  • WatchService and SwingWorker: how to do it correctly?

    cross-posted to SOF:
    http://stackoverflow.com/questions/7784909/watchservice-and-swingworker-how-to-do-it-correctly
    For maximum feedback (though many regulars roam everywhere :-), here's a copy
    WatchService sounded like an exciting idea ... unfortunately it seems to be as low-level as warned in the tutorial/api plus doesn't really fit into the Swing event model (or I'm missing something obvious, a not-zero probability ;-)
    Taking the code from WatchDir (simplyfied to handle a single directory only), I basically ended up
    extend SwingWorker
    do the registration stuff in the constructor
    put the endless loop waiting for a key in doInBackground
    publish each WatchEvent when retrieved via key.pollEvents()
    process the chunks by firing propertyChangeEvents with the deleted/created files as newValue
    @SuppressWarnings("unchecked")
    public class FileWorker extends SwingWorker<Void, WatchEvent<Path>> {
        public static final String DELETED = "deletedFile";
        public static final String CREATED = "createdFile";
        private Path directory;
        private WatchService watcher;
        public FileWorker(File file) throws IOException {
            directory = file.toPath();
            watcher = FileSystems.getDefault().newWatchService();
            directory.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        @Override
        protected Void doInBackground() throws Exception {
            for (;;) {
                // wait for key to be signalled
                WatchKey key;
                try {
                    key = watcher.take();
                } catch (InterruptedException x) {
                    return null;
                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();
                    // TBD - provide example of how OVERFLOW event is handled
                    if (kind == OVERFLOW) {
                        continue;
                    publish((WatchEvent<Path>) event);
                // reset key return if directory no longer accessible
                boolean valid = key.reset();
                if (!valid) {
                    break;
            return null;
        @Override
        protected void process(List<WatchEvent<Path>> chunks) {
            super.process(chunks);
            for (WatchEvent<Path> event : chunks) {
                WatchEvent.Kind<?> kind = event.kind();
                Path name = event.context();
                Path child = directory.resolve(name);
                File file = child.toFile();
                if (StandardWatchEventKinds.ENTRY_DELETE == kind) {
                    firePropertyChange(DELETED, null, file);
                } else if (StandardWatchEventKinds.ENTRY_CREATE == kind) {
                    firePropertyChange(CREATED, null, file);
    }The basic idea is to make using code blissfully un-aware of the slimy details: it listens to the property changes and f.i. updates arbitrary models as appropriate:
        String testDir = "D:\\scans\\library";
        File directory = new File(testDir);
        final DefaultListModel<File> model = new DefaultListModel<File>();
        for (File file : directory.listFiles()) {
            model.addElement(file);
        final FileWorker worker = new FileWorker(directory);
        PropertyChangeListener l = new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                if (FileWorker.DELETED == evt.getPropertyName()) {
                    model.removeElement(evt.getNewValue());
                } else if (FileWorker.CREATED == evt.getPropertyName()) {
                    model.addElement((File) evt.getNewValue());
        worker.addPropertyChangeListener(l);
        JXList list = new JXList(model);Seems to work, but I feel uncomfortable
    Outing myself as the thread agnostic I am: all example snippets I have seen so far do block the waiting thread by using watcher.take(). Why do they do it? Would expect at least some use watcher.poll() and sleep a bit.
    the SwingWorker publish method doesn't quite seem to fit: for now it's okay, as I'm watching one directory only (didn't want to galopp too far into the wrong direction :) When trying to watch several directories (as in the original WatchDir example) there are several keys and the WatchEvent relative to one of those. To resolve the path, I would need both the event and the key - but can pass on only one. Most probably got the distribution of logic wrong, though
    Feedback (here or there, will take all :-) highly welcome!
    Cheers
    Jeanette

    finally settled on a version that's good enough (for now, at least), published over at SOF, copied here:
    Actually, @Eels's comment didn't stop knocking in the back of my head - and finally registered: it's the way to go, but there is no need for any "artificial" struct, because we already have the perfect candidate - it's the PropertyChangeEvent itself :-)
    Taking the overall process description from my question, the first three bullets remain the same
    - same: extend SwingWorker
    - same: do the registration stuff in the constructor
    - same: put the endless loop waiting for a key in doInBackground
    - changed: create the appropriate PropertyChangeEvent from each WatchEvent when retrieved via key.pollEvents and publish the PropertyChangeEvent
    - changed: fire the previously created event in process(chunks)
    @SuppressWarnings("unchecked")
    public class FileWorker extends SwingWorker<Void, PropertyChangeEvent> {
        public static final String FILE_DELETED = StandardWatchEventKinds.ENTRY_DELETE.name();
        public static final String FILE_CREATED = StandardWatchEventKinds.ENTRY_CREATE.name();
        public static final String FILE_MODIFIED = StandardWatchEventKinds.ENTRY_MODIFY.name();
        // will change to a map of key/directories, just as the tutorial example
        private Path directory;
        private WatchService watcher;
        public FileWorker(File file) throws IOException {
            directory = file.toPath();
            watcher = FileSystems.getDefault().newWatchService();
            directory.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        @Override
        protected Void doInBackground() throws Exception {
            for (;;) {
                // wait for key to be signalled
                WatchKey key;
                try {
                    key = watcher.take();
                } catch (InterruptedException x) {
                    return null;
                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();
                    // TBD - provide example of how OVERFLOW event is handled
                    if (kind == OVERFLOW) {
                        continue;
                    publish(createChangeEvent((WatchEvent<Path>) event, key));
                // reset key return if directory no longer accessible
                boolean valid = key.reset();
                if (!valid) {
                    break;
            return null;
         * Creates and returns the change notification. This method is called from the
         * worker thread while looping through the events as received from the Watchkey.
         * @param event
         * @param key
        protected PropertyChangeEvent createChangeEvent(WatchEvent<Path> event, WatchKey key) {
            Path name = event.context();
            // evolve into looking up the directoy from the key/directory map
            Path child = directory.resolve(name);
            PropertyChangeEvent e = new PropertyChangeEvent(this, event.kind().name(), null, child.toFile());
            return e;
        @Override
        protected void process(List<PropertyChangeEvent> chunks) {
            super.process(chunks);
            for (PropertyChangeEvent event : chunks) {
                getPropertyChangeSupport().firePropertyChange(event);
    }Feedback still highly welcome, of course, especially if there's something wrong :-)
    Thanks
    Jeanette

  • How to detect is response deliverred to the client?

    Hello everybody...
    I have problem and don't know how to solve.
    My server application runs on apache tomcat 5.5, and deals with some important data transactions.
    After getting the request, server has 5 sec. to send response, after that clients will close their sockets.
    The connection can be very slow, (GPRS), so it is very possible that transaction will not be over in that time.
    I need the way to find out, on my server side, when response isn't get to client in 5 sec.
    Is there any idea how to do that?
    Sorry if my English is not so perfect.
    Thanks

    Yes, but that way of write timeout means that write have 5 sec to send buffer to the underlying protocol.
    I can't know if TCP succeed or not to deliver data in that short time. I think write is asynchron.
    Problem is how to detect when client is disconnect and data are not delivered.
    Once again, sorry if my English is not so good.

  • Trunk config between two 6500 cat switches

    Hi All,
    What is the recommended trunk configuration between 2 cisco 6500 switches including hsrp scenario.
    Thanks

    Hi Samir,
    In almost all scenarios, its recommended to have 'dot1q' encapsulation and a static trunk config 'switchport mode trunk'. Matching the native VLAN on both sides is required and will be VLAN1 by default.
    When configuring trunks, you should be mindful of VTP, trunk and STP states. Reviewing the following for mismatches between your Cat6K will help:
    - show vtp status
    - show interfaces trunk
    - show spanning-tree
    In terms of HSRP, it is also recommended to run HSRP active in the same location as STP Root to avoid any asynchronous routing problems.
    /ijay

  • JTextField update problem when called from PropertyChangeEvent

    Hi,
    I'm trying to create forms that can be dynamically loaded with Class.forname(formName).
    Those forms should always inherit some methods that make it easy to pass data to
    them and receive data from them. The idea is that the data comes from a table which
    sends a hashmap (String column/JTextField-name + String Value pairs) with firePropertyChanged
    as soon as a new row is seleceted. The JTextFields in the form are marked with setName("FieldName") that has to correspond to the name of the columns of the table.
    My problem is that I can't update the fields in my form when I'm calling getRow(HashMap)
    from within propertyChangeEvent but that's necessary to keep the forms flexible.
    JTextFieldName.setText(newText) just won't work. But it works when I call getRow(HashMap)
    from the constructor. SwingWorker and threads to update the form didn't help.
    I don't need to call pack() / update() / repaint() on the JFrame, do I ??
    update() / validate() / repaint() etc. didn't work on the JTextField themselves.
    Below is the code for one of the test-forms (just a JPanel that is inserted in a frame)
    with all of it's methods. Does anybody have a solution to this problem ??
    Thanks for taking time for that !!
    Benjamin
    * testTable.java
    * Created on 15. April 2004, 16:12
    package viewcontrol.GUI;
    * @author gerbarmb
    import javax.swing.*;
    import java.awt.*;
    import java.beans.*;
    import java.util.*;
    public class testTable extends javax.swing.JPanel
              implements
                   java.awt.event.KeyListener,
                   java.beans.PropertyChangeListener {
          * public static void main(String[] argv) { testTable tt = new testTable();
          * JFrame jf = new JFrame(); jf.setContentPane(tt); jf.setVisible(true); }
         /** Creates new customizer testTable */
         public testTable() {
              initComponents();
              HashMap hm = new HashMap();
               * Only for debugging, to see that the method getRow() works when
               * called from the constructor.
               hm.put("ttext", "TEst");
               this.getRow(hm);
          * 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 FormEditor.
         private void initComponents() {//GEN-BEGIN:initComponents
              java.awt.GridBagConstraints gridBagConstraints;
              jLabel1 = new javax.swing.JLabel();
              textIn = new javax.swing.JTextField();
              jLabel2 = new javax.swing.JLabel();
              intIn = new javax.swing.JTextField();
              jLabel3 = new javax.swing.JLabel();
              numIn = new javax.swing.JTextField();
              jLabel4 = new javax.swing.JLabel();
              dateIn = new javax.swing.JTextField();
              jLabel5 = new javax.swing.JLabel();
              dateTimeIn = new javax.swing.JTextField();
              jLabel6 = new javax.swing.JLabel();
              jCheckBox1 = new javax.swing.JCheckBox();
              keepValues = new javax.swing.JCheckBox();
              jButton1 = new javax.swing.JButton();
              setLayout(new java.awt.GridBagLayout());
              jLabel1.setText("Text");
              add(jLabel1, new java.awt.GridBagConstraints());
              textIn.setName("ttext");
              textIn.setPreferredSize(new java.awt.Dimension(100, 21));
              textIn.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent evt) {
                        textInActionPerformed(evt);
              gridBagConstraints = new java.awt.GridBagConstraints();
              gridBagConstraints.gridwidth = 2;
              add(textIn, gridBagConstraints);
              jLabel2.setText("Integer");
              add(jLabel2, new java.awt.GridBagConstraints());
              intIn.setName("tint");
              intIn.setPreferredSize(new java.awt.Dimension(50, 21));
              add(intIn, new java.awt.GridBagConstraints());
              jLabel3.setText("Number");
              add(jLabel3, new java.awt.GridBagConstraints());
              numIn.setName("tnum");
              numIn.setPreferredSize(new java.awt.Dimension(50, 21));
              add(numIn, new java.awt.GridBagConstraints());
              jLabel4.setText("Date");
              gridBagConstraints = new java.awt.GridBagConstraints();
              gridBagConstraints.gridx = 0;
              gridBagConstraints.gridy = 1;
              add(jLabel4, gridBagConstraints);
              dateIn.setName("tdate");
              dateIn.setPreferredSize(new java.awt.Dimension(50, 21));
              gridBagConstraints = new java.awt.GridBagConstraints();
              gridBagConstraints.gridx = 1;
              gridBagConstraints.gridy = 1;
              add(dateIn, gridBagConstraints);
              jLabel5.setText("DateTime");
              gridBagConstraints = new java.awt.GridBagConstraints();
              gridBagConstraints.gridx = 2;
              gridBagConstraints.gridy = 1;
              add(jLabel5, gridBagConstraints);
              dateTimeIn.setName("tidate");
              dateTimeIn.setPreferredSize(new java.awt.Dimension(80, 21));
              gridBagConstraints = new java.awt.GridBagConstraints();
              gridBagConstraints.gridy = 1;
              add(dateTimeIn, gridBagConstraints);
              jLabel6.setText("Bit");
              gridBagConstraints = new java.awt.GridBagConstraints();
              gridBagConstraints.gridy = 1;
              add(jLabel6, gridBagConstraints);
              jCheckBox1.setName("tbit");
              gridBagConstraints = new java.awt.GridBagConstraints();
              gridBagConstraints.gridy = 1;
              add(jCheckBox1, gridBagConstraints);
              keepValues.setText("keep values");
              gridBagConstraints = new java.awt.GridBagConstraints();
              gridBagConstraints.gridx = 7;
              gridBagConstraints.gridy = 3;
              add(keepValues, gridBagConstraints);
              jButton1.setText("Send");
              jButton1.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent evt) {
                        jButton1ActionPerformed(evt);
              gridBagConstraints = new java.awt.GridBagConstraints();
              gridBagConstraints.gridx = 7;
              gridBagConstraints.gridy = 2;
              add(jButton1, gridBagConstraints);
         }//GEN-END:initComponents
         private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
              sendRow();
         }//GEN-LAST:event_jButton1ActionPerformed
         private boolean sendRow() {
              java.util.HashMap hm = new java.util.HashMap();
              Component[] cs = this.getComponents();
              for (int i = 0; i < cs.length; i++) {
                   if (((Component) cs).getName() != null) {
                        if (cs[i] instanceof JCheckBox) {
                             String value = ((JCheckBox) cs[i]).isSelected() ? "1" : "0";
                             hm.put(cs[i].getName(), value);
                        } else if (cs[i] instanceof JCheckBox) {
                             hm.put(cs[i].getName(), ((JTextField) cs[i]).getText());
              } // end for
              firePropertyChange("rowChanged", null, hm);
              return true;
         private void getRow(java.util.HashMap hm) {
              //if (! this.keepValues.isSelected()) {
              Component[] cs = this.getComponents();
              for (int i = 0; i < cs.length; i++) {
                   if (cs[i].getName() != null && hm.containsKey(cs[i].getName())) {
                        Component component = cs[i];
                        String componentName = cs[i].getName();
                        String componentValue = (String) hm.get(component.getName());
                        if (cs[i] instanceof JTextField) {
                             // output for debugging
                             System.out.println("Setting " + cs[i].getName() + " = "
                                       + componentValue);
                             ((JTextField) component).setText(componentValue);
                        } else if (cs[i] instanceof JCheckBox) {
                             // output for debugging
                             System.out.println("JCheckBox found");
                             JCheckBox cb = (JCheckBox) component;
                             boolean selected = (componentValue == null ? false : (componentValue.equals("1")
                                       ? true
                                       : false));
                             ((JCheckBox) component).setSelected(selected);
              } // end for
              /* Uncomment this code snippet to retrieve the text that has been set
              for the components (that means JTextFields)
              This is just for debugging !
              Component[] cs = this.getComponents(); for (int i = 0; i < cs.length;
              i++) { if (cs[i].getName() != null) { if (cs[i] instanceof
              JTextField) { System.out.println("Value of " +cs[i].getName() + " = " +
              ((JTextField) cs[i]).getText()); } } } // end for
         private void textInActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textInActionPerformed
         }//GEN-LAST:event_textInActionPerformed
         public void keyPressed(java.awt.event.KeyEvent e) {
              if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) {
                   sendRow();
         public void keyReleased(java.awt.event.KeyEvent e) {
         public void keyTyped(java.awt.event.KeyEvent e) {
         public void propertyChange(java.beans.PropertyChangeEvent evt) {
              if (evt.getPropertyName().equals("newRow")) {
                   final PropertyChangeEvent finalEvt = evt;
                   Runnable makeChanges = new Runnable () {
                        public void run() {
                             getRow((java.util.HashMap) finalEvt.getNewValue());
         // Variables declaration - do not modify//GEN-BEGIN:variables
         private javax.swing.JTextField dateIn;
         private javax.swing.JTextField dateTimeIn;
         private javax.swing.JTextField intIn;
         private javax.swing.JButton jButton1;
         private javax.swing.JCheckBox jCheckBox1;
         private javax.swing.JLabel jLabel1;
         private javax.swing.JLabel jLabel2;
         private javax.swing.JLabel jLabel3;
         private javax.swing.JLabel jLabel4;
         private javax.swing.JLabel jLabel5;
         private javax.swing.JLabel jLabel6;
         private javax.swing.JCheckBox keepValues;
         private javax.swing.JTextField numIn;
         private javax.swing.JTextField textIn;
         // End of variables declaration//GEN-END:variables

    The problem of the change in the form not being comitted is that
    I forgot SwingUtilities.invokeLater(makeChanges); in the bottom
    part in public void propertyChange(java.beans.PropertyChangeEvent evt)
    after having created a new Runnable.
    Changes to the UI often have to be comitted by SwingUtitlities.invokeLater()
    though I don't know that much about Swing yet.
    Thanks to everybody who tried to solve that problem.
    Benjamin

  • Problems with asynchronous(?) function call before return statement

    I have a function as following inside a class deriving from CustomNode:
    override protected function create () : Node {
                    parseContent();
                    return group;
            }parseContent() executes a HttpRequest and then a PullParser. At least that's what it should do. But actually, it doesn't. Is this because the HttpRequest is asynchronous and is "cancelled" because of the return statement? Or can't this be the problem?

    You would have to update or create the view in the finally block of the onOutput: or onInput methods within the request.
    You could also try
    var viewContent: Node;
    override protected function create () : Node {
                    parseContent();
                    FX.deferAction(function():Void{
                           viewContent = group;
                    return Group{ content: bind viewContent }
            }I never tried that, but it might work.
    Another option is to bind the parsed content to whatever view you are pushing it to. Then whenever the request is done, the view will populate its content on the change of the variable where the content is stored.
    Example:
    var allTables: TableModel[];      
    //***************start of table list decleration****************************\\
    public var list: SwingJList = SwingJList {
        var shortcutKey: Boolean = false;
        focusTraversable: true
        selectedIndex: 0
        action: function(){
            FX.deferAction(function():Void{
                openButton.fire();
        items: bind for( table in allTables ){
            table.name
    var searchDataXml = xmlGenerator.generateSearchXMLString(searchData);
    var contentLength: Integer = searchDataXml.getBytes().length;
    def postRequest: HttpRequest = HttpRequest {
        location: "{WEB_APPLICATION_REQUEST_URL}searchData/?database={DATABASE_KEY}";
        method: HttpRequest.POST;
        headers: [
                HttpHeader {
                    name: HttpHeader.CONTENT_TYPE;
                    value: "application/xml";
                HttpHeader {
                    name: HttpHeader.CONTENT_LENGTH;
                    value: "{contentLength}";
        onStarted: function() {
            println("onStarted - started performing method: {postRequest.method} on location: {postRequest.location}");
        onConnecting: function() { println("onConnecting") }
        onDoneConnect: function() { println("onDoneConnect") }
        onWriting: function() { println("onWriting") }
        onOutput: function(os: java.io.OutputStream) {
            try {
                os.write(searchDataXml.getBytes());
            } finally {
                println("onOutput - about to close output stream.");
                os.close();
                os.flush();
        onToWrite: function(bytes: Long) { println("onToWrite - entire content to be written: {bytes} bytes") }
        onWritten: function(bytes: Long) { println("onWritten - {bytes} bytes has now been written") }
        onDoneWrite: function() { println("doneWrite") }
        onReadingHeaders: function() { println("onReadingHeaders") }
        onResponseCode: function(code:Integer) { println("onResponseCode - responseCode: {code}") }
        onResponseMessage: function(msg:String) { println("onResponseMessage - responseMessage: {msg}") }
        onResponseHeaders: function(headerNames: String[]) {
            println("onResponseHeaders - there are {headerNames.size()} response headers:");
            for (name in headerNames) {
                println("    {name}: {postRequest.getResponseHeaderValue(name)}");
        onReading: function() { println("onReading") }
        onToRead: function(bytes: Long) {
            if (bytes < 0) {
                println("onToRead - Content length not specified by server; bytes: {bytes}");
            } else {
                println("onToRead - total number of content bytes to read: {bytes}");
        onRead: function(bytes: Long) {
            // The toread variable is non negative only if the server provides the content length
            def progress =
            if (postRequest.toread > 0) "({(bytes * 100 / postRequest.toread)}%)" else "";
            println("onRead - bytes read: {bytes} {progress}");
        var parser = new XmlPullParser();
        onInput: function(is: java.io.InputStream) {
            // use input stream to access content here.
            // can use input.available() to see how many bytes are available.
            try {
                allTables = parser.processResults(is);
            } finally {
                is.close();
        onException: function(ex: java.lang.Exception) {
            println("onException - exception: {ex.getClass()} {ex.getMessage()}");
        onDoneRead: function() { println("onDoneRead") }
        onDone: function() { println("onDone") }
    postRequest.start();
    } In this case an array of tableModel names are bound to the list view.
    When the httprequest ends, it sets the parsed tableModel array to the array declared in this class.
    The list view will populate the table names from the array when the request finishes.

  • 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

  • Problem about asynchronous call: subVI front panel doesn't pop up when called.

    Dear All,
    I'm new to LabVIEW, and this is the first time I try to use the asynchronous call.
    I'm using LabVIEW 2011.
    I want to build a directory for several VIs, and it should allow users to open more than one of the VIs at the same time by pushing the buttons. Before building this directory, I simply tried to use asynchronous call to call a VI form another VI, but found a big problem.
    I followed the steps in the help file, created a strictly typed reference, set the option to x80 because I don't need the return. When I run it for the first time, it worked fine: the subVI popped up and run. Then I closed the subVI. But for the sencond time and on, when I run the caller VI, the subVI didn't pop up, instead it seemed to run silently on background because when I manually opened it from the file I found it running. Besides, I didn't find any option like "show front panel when called" of the asynchronous call.
    The caller VI and subVI are attached. The address of subVI in caller VI should be changed accordingly.
    What should I do to make it work properly? Thanks very much for  any idea!
    Solved!
    Go to Solution.
    Attachments:
    asynchronous_call.vi ‏8 KB
    boolean.vi ‏7 KB

    Jeff·Þ·Bohrer wrote:
    A better approach is to set the vi properties programaticly like this:
    Jeff, you will be happy to know that I used this tactic in full force on a project recently (lots of dialogs in this program).  Not sure how many LabVIEW reboots it has saved me from.  Reuse VIs made it even easier to do.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • Asynchronous XI- RFC and RFC- XI scenario - strange problem

    Hello XI-Xperts,
    I've come to really strange problem, which I would like to share with you and possibly get an explanation.
    I have an asynchronous scenario with ending XI->RFC. The RFC function in R/3 has got an optional parameter called SENDER, which when is filled, the another asynchronous RFC->XI scenario should be started. (via ABAP code <i>CALL FUNCTION 'Z_XI_RETURN' DESTINATION gc_xi_destination</i> ... etc.)
    Now, the direction XI->RFC is configured properly, but the way back NO(!). Anyway I thought that it wouldn't make me a trouble, because those two scenarios are IMHO absolutelly separated. So I'd presume that the the data should come to R/3 without problem, it should be processed, and in case the parameter SENDER is filled the R/3 would establish the RFC connection and the "return data" should go back in different XI thread.
    Well I would think like that but the situation is different:
    When the parameter SENDER is empty, all goes OK and I can see in Runtime Workbench Message Monitoring - Adapter engine - Detail - Audit log only "successes". But when SENDER is filled with a value and R/3 does CALL FUNCTION with DESTINATION to a <i>non-existing Sender agreement</i>, the R/3 apparently doesn't send a acknowledgement to Adapter Engine of first thread XI->RFC. Intstead of that there are three messages in audit log:
    <i>MP: exception caught with cause com.sap.aii.af.ra.ms.api.RecoverableException: error while processing message to remote system:com.sap.aii.af.rfc.core.client.RfcClientException: JCO.Exception while calling Z_FIDATA_INPUT in remote system (RfcClient[IS2RFC_SAP_BG]):com.sap.mw.jco.JCO$Exception: (104) RFC_ERROR_SYSTEM_FAILURE: senderAgreement not found: lookup of binding via CPA-cache failed for AdapterType RFC, AdapterNS http://sap.com/xi/XI/System, di: com.sap.aii.af.rfc.afcommunication.RfcAFWException: error while processing message to remote system:com.sap.aii.af.rfc.core.client.RfcClientException: JCO.Exception w
    </i>
    Basically I understand what is happening on the background, but I really can't go over my persuation that in case of the ASYNCHRONOUS SCENARIO this should not happen.
    Or is the RFC call (I mean XI->RFC) "pseudo-synchronous" even in asynchronous scenario ? I mean that Adapter engine waits for the result of RFC everytime ... ?!
    Thank you
    Tomas

    Hello again guys,
    so I've understood it on the end. My ABAP code didn't contain EXCEPTION part of CALL FUNCTION statement.
    <i>CALL FUNCTION 'Z_XI_RETURN'
        DESTINATION gc_xi_destination
        EXPORTING
          <PARS>
        <b>EXCEPTIONS
          communication_failure = 1
          system_failure        = 2.</b></i>
    Without it the RFC short-dumped and AE correctly tried to call it 1+3 times. The thing, that the problem was connected to XI related topic, tricked me. Well it's smart, I must admit on the end
    Reward points for interest.
    THX Tomas

  • 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

Maybe you are looking for