0

I'm using POI in a function to fill the content of my excel document (it takes 10 seconds) and when i call my function I want to use a JProgressBar to see the progress, but the button and the program is block, i need to to make in other thread? and how can I do it? an example of my code:

btnEjecutar.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0) {
        //the function
        generarDocumento(nombre);
            }
centic
  • 15,565
  • 9
  • 68
  • 125
marcss
  • 253
  • 2
  • 14
  • 1
    Take a look at this doc: http://stackoverflow.com/a/782309/32090 – Boris Pavlović Feb 01 '16 at 08:29
  • This is a rather generic question and has nothing to do with Apache POI in particular. Take a look at Oracle's [tutorial](https://docs.oracle.com/javase/tutorial/uiswing/components/progress.html) - it covers your use-case quite well. – morido Feb 01 '16 at 09:00
  • 1
    Take a look at [Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/) for more details about the problem and [Worker Threads and SwingWorker](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html) for a possible solution – MadProgrammer Feb 01 '16 at 09:01
  • 1
    And [for example](http://stackoverflow.com/questions/23125642/swingworker-in-another-swingworkers-done-method/23126410#23126410), [example](http://stackoverflow.com/questions/20739488/swingworker-in-multithreaded-jframes/20739571#20739571), [exampe](http://stackoverflow.com/questions/24835638/issues-with-swingworker-and-jprogressbar/24835935#24835935), [example](http://stackoverflow.com/questions/15199091/progress-bar-java/15199220#15199220), [example](http://stackoverflow.com/questions/22031086/jprogressbar-not-working-properly/22031159#22031159) ... – MadProgrammer Feb 01 '16 at 09:04
  • 1
    Avoid using `MouseListener` with buttons, instead use an `ActionListener` – MadProgrammer Feb 01 '16 at 09:05

2 Answers2

1

Event listeners are executed in the UI thread. If an event listener takes a long time, the UI will stop working/lock up/block/hang.

My guess is that the method generarDocumento() takes a long time. If you want the UI to continue working, you must run it in a worker thread. The Java documentation contains several examples how to do that: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html

The last example in the tutorial contains demo code how to update a progress bar: https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/uiswing/examples/components/ProgressBarDemoProject/src/components/ProgressBarDemo.java

Note: The linked content is copyrighted; therefore I can't copy it here.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
1

Try to use an invokeLater, like the example bellow:

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        generarDocumento(nombre);
    });