Solved

Problems with Swing and threads...

Posted on 2004-08-03
10
310 Views
Last Modified: 2012-06-21
Hello all,
In my Swing application I have a problem with refreshig JLabel component!
In my actionPerformed(ActionEvent evt) method I want after pressing one button a lot of names to be shown/one by one/ in this JLabel, but this must be done with delay between each one of them. In order to delay, I use Thread.Sleep(10);
But as I understood actionPerformed is executed from the dispatch event thread, so my JLabel is not refreshed /because of this that Swing is not thread saved/. I tried to run another thread, but the result is the same!!!
So, how can I get over this problem?
Here is the code that I'm using to do this :

if (evt.getSource() == btnChoose) {
            Runnable disableComponents = new Runnable() {
                public void run() {
                   for (int i=1; i < maxValue; i++) {
                        String name = (String)names.get(new Integer(i));
                        employeesCycle.setText(name);
                        System.out.print(name);
                        try {
                           Thread.sleep(5);
                        } catch(Exception ex) {}
                    }
                }
            };
            SwingUtilities.invokeLater(disableComponents);
        }

In this way the names are not blinking. Nothing appears! Any suggestions?
Thanks in advance and best regards.
Valeri
0
Comment
Question by:Valeri
10 Comments
 
LVL 92

Expert Comment

by:objects
ID: 11702213
youy cannot use sleep() on the ewvent dispatch thread.
you need to move that code into a seperate thread
0
 
LVL 92

Expert Comment

by:objects
ID: 11702228
>  SwingUtilities.invokeLater(disableComponents);

try changing that to:

new Thread(disableComponents).start();
0
 
LVL 92

Expert Comment

by:objects
ID: 11702260
though you should then also change your thread to do the label update from the edt.

EventQueue.invokeLater(new Runnable()
{
   public void run()
   {
     employeesCycle.setText(name);
   }
});
0
 
LVL 35

Expert Comment

by:girionis
ID: 11702269
You could do:

Thread t = new Thread() {

      public void run() {
       for (int i=1; i < maxValue; i++) {
                        String name = (String)names.get(new Integer(i));
                        employeesCycle.setText(name);
                        System.out.print(name);
                        try {
                           Thread.sleep(5);
                        } catch(Exception ex) {}
                    }
      }
    };
  t.start();
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11702915
You don't need to worry about setting the text of a JLabel from the EDT, so girionis' code will be fine
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 92

Expert Comment

by:objects
ID: 11702974
> so girionis' code will be fine

so will mine then, seeing its identical :)
0
 
LVL 3

Expert Comment

by:JohnnyAffa
ID: 11705457
the following code displays a name from the names array and iterates through the array every second.  when the button is initially clicked, it starts displaying. if the button is clicked when its displaying, displaying is stopped.  if its is reclicked, then iteration start from the last name dispayed.

in order fot the code to work, you need to implement Runnable interface and ActionListener ( for button clicked)

      JTextField jtextfield;
      JButton jbutton;

      String names[] = {"affa","chris","steve","bruce","moose","peter","nick","ian","colin","jeff","greg","tervor"};
      int index = 0;
      jtextfield = new JTextField();
      jtextfield.setBounds(10,10,200,30);

      jbutton = new JButton();
      jbutton.addActionListener(this);
      jbutton.setActionCommand("stop");

      public void actionPerformed(ActionEvent action)
      {
            String command = action.getActionCommand();

            if ( command.equals("stop") )
            {
                  ((JButton)action.getSource()).setActionCommand("iterate");
                  (new Thread(this)).start();
            }
            else if ( command.equals("iterate") )
            {
                  ((JButton)action.getSource()).setActionCommand("stop");
            }
      }

      public void run()
      {

            try
            {
                  while ( jbutton.getActionCommand().equals("iterate") )
                  {
                        jtextfield.setText(names[index]);
                        index = ( index < names.length - 1 ) ? index+1 : 0;
                        Thread.sleep(1000);
                  }
            }
            catch ( Exception a)
            {
                  System.out.println(a.toString());
            }
}
0
 
LVL 16

Author Comment

by:Valeri
ID: 11750277
Thanks!
Could you please give me some good article about all of this threads, I mean the main thread, dispatch thread and any other related to Swing, and how they communicate each other?
Because I can't understand in which thread "actionPerformed()" is executed.
Thanks in advance!
0
 
LVL 92

Accepted Solution

by:
objects earned 125 total points
ID: 11750299
> Could you please give me some good article about all of this threads

http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html

> Because I can't understand in which thread "actionPerformed()" is executed.

actionPerformed() will get called by the event dispatch thread.
0
 
LVL 92

Expert Comment

by:objects
ID: 11758561
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
sumHeights2  challenge 7 78
Increment alphanumeric sequence 6 81
How Complex Is This Java Course ? 9 63
json format text only 4 65
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
This video teaches viewers about errors in exception handling.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now