开发者

How to display a "Loading..." message that closes automatically when processing is over (similar to Progress Bar)?

开发者 https://www.devze.com 2023-03-07 04:02 出处:网络
I have a comboBox jComboBox1 that contains names of all countries in the world...Upon selection of one of the countries a second combobox jComboBox2 is populated with all the states in the country sel

I have a comboBox jComboBox1 that contains names of all countries in the world...Upon selection of one of the countries a second combobox jComboBox2 is populated with all the states in the country selected in jComboBox1. Now I want to display a Progress Bar or "Loading..." message when the states in the selected country is populated and closes automatically once it's done.

The code is like this...

 public void actionPerformed(ActionEvent e){
    if(e.getSource()==jComboBox1){
            if(jCombobox1.setSelectedIndex()!=-1){
                   Country country=new Country();
                   country.populateStates(jComboBox2,label,this);
                  //"label" is of type JLabel whose text is is set to show the progress
                  //"this" refers to the current frame to repaint once label is changed
            }
    }
 }

I thought I can use a JLabel in the frame whose visibilty and text can be set using setVisible() and setText. Note that "Country" is a different class and I pass this label to its method populateStates where I use label.setText("Loading details of state:"+state) and do frame.repaint(). (That's why I pass the frame object "this"). Even then, label does not change.

But the only change that appears in the label's initial text after selection 开发者_JAVA技巧of a country is the last text that it is set to, once country's selection is over. Intermediate changes in the label do not appear in the GUI. Why's this happening and what's wrong with my approach? Do I have to use another approach using threads??? If so, how??


First of all, since that seems to be a long task, you need to populate the list of country states OUTSIDE the EDT.

For this, you can use SwingWorker. SwingWorker provides some methods that can be used to give feedback to the user.

But you will have some work to perform to display that feedback.


I have to use get() to retrieve the value, but get() stops all GUI updates.

Yes, "calling get() on the Event Dispatch Thread blocks all events, including repaints, from being processed until this SwingWorker is complete." Instead, publish() results as they accumulate and process() them on the EDT. See the examples here and here.

Addendum: The get() API shows an example of using a modal dialog in this context. Your PropertyChangeListener can update a JProgressBar in the dialog.

0

精彩评论

暂无评论...
验证码 换一张
取 消