Search code examples
javamultithreadingswingjlabelftp-client

How to validate JLabel in Swing while using FTPClient


I want to update a JLabel each time with the name of the file which I am downloading using FTPClient. I tried repaint(), validate(), revalidate(), first invalidate() and immediately validate()/revalidate() but still nothing is working.

My Code goes as follows:

if(ae.getActionCommand()=="Download"){

    int[] row_indexes=table.getSelectedRows();

    notifylb.setText("Downloading files");
    this.validate();

    for(int i=0;i<row_indexes.length;i++)
    {
         String fn=table.getValueAt(row_indexes[i], 0).toString();  

         notifylb.setText("Downloading: "+fn);  // fn contains filename
         this.validate();

         this.downloadFtpfile(fn);  

    }

    notifylb.setText("SUCCESSFULLY DOWNLOADED FILE(s) !");
    this.validate();
}

Solution

  • @Hovercraft-Full-Of-Eels explain very clear, but if you need the code, here it is how to write it.

    final JButton finalButton = button; // this is your button will trigger download
    final JLabel finalLabel = finalLabel;
    final JTable finalTable = table;
    
    
    if(ae.getActionCommand().equals("Download"))
    {
        finalButton.setEnabled(false); //disable button, so user can not start it for twice until ftp finished.
        Thread thread = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                int[] row_indexes = finalTable.getSelectedRows();
    
                SwingUtilities.invokeLater(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        finalLabel.setText("Downloading files");
                    }
                });
    
                for(int i = 0; i < row_indexes.length; i++)
                {
                    final String fn = finalTable.getValueAt(row_indexes[i], 0).toString();
    
                    SwingUtilities.invokeLater(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            finalLabel.setText("Downloading: " + fn);  // fn contains filename
                        }
                    });
    
                    this.downloadFtpfile(fn);
                }
    
                SwingUtilities.invokeLater(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        finalLabel.setText("SUCCESSFULLY DOWNLOADED FILE(s) !");
                        finalButton.setEnabled(true); //enable the button
                    }
                });
            }
        });
        thread.start();
    };