简体   繁体   中英

several times change label text by clicking button in swing not work

I need to change jlabel.text several times by one click button in swing. In this code i need set label text to start before dowork() function and set to in progress in middle and set it to end after dowork() (status type in jlabel and dowork has long time execution) :

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 
        status.setText("start");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException ex) {
            Logger.getLogger(PelakInRFID.class.getName()).log(Level.SEVERE, null, ex);
        }
        status.setText("in progress");
        dowork();
       try {
            Thread.sleep(10000);
        } catch (InterruptedException ex) {
            Logger.getLogger(PelakInRFID.class.getName()).log(Level.SEVERE, null, ex);
        }
        status.setText("end");

 }

In this code status only set to end and start doesn't show.

Never, NEVER use Thread.sleep , Thead.yield in the ETD

Never, NEVER perform any blocking actions in the ETD , such as extended IO or data processing

The reason that the label is not changing is because you are stalling/blocking the ETD , preventing it from processing any repaint requests.

Check out Concurrency in Swing & The Event Dispatching Thread

I would try to use a SwingWorker instance (in particular its doInBackground method) to do what you are currently doing in doWork on a different thread than the main UI thread. The way it's written, your listener method is bound to freeze the user interface during execution, which, as you said, can be a long time, resulting in a bad user experience.

Change to JLabel text can happen in three different places: first, just before invoking execute on (ie starting) the SwingWorker ; second, using the publish / process mechanism that SwingWorker makes available to publish intermediate results on the user interface; third, in the done method, which is called again on the UI thread as soon as the SwingWorker has finished the execution of its doInBackground method.

References: Oracle's tutorial on worker threads and SwingWorker , JavaDoc API documentation of the SwingWorker class .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM