Search code examples
javanetbeansjtextfieldfilechooser

display text in jtextfield takes too long


I would really appreciate your help; I'm using java (netbeans ide), i'm working with filechooser, when i choose a directory, i need to display it's path on a jtextfield. However nothing appears until the program is over (untill all the files of the directory are parsed and treated), I would like it to appear as soon as the program starts. Please help me out, here is my code:

    JFileChooser fch = new JFileChooser("C:\\");
    fch.addChoosableFileFilter(filter);

    fch.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int ret = fch.showOpenDialog(null); 
    int apr=0;
    if (ret==JFileChooser.APPROVE_OPTION)
    {
        apr=1;
        jTextField1.setText(fch.getSelectedFile().toString());
    }
    else jTextField1.setText("Nothing clicked!!!");
.......... the rest of the code .........

when I don't click the msg appears, yet when i do, the path won't apprear till after the program is finished


Solution

  • The code of JFileChooser... probably resides in an ActionListener. This is handled on the sole event handling thread. So do an invokeLater.

    @Override
    public void actionPerformed(ActionEvent event) {
        ...
    
        EventQueue.invokeLater(new Runnable() { // Added
            ... rest of the code
        }); // Added
    }
    

    Here I think "rest of the code" might be causing the delay, but you might try differently.