?
Solved

Problems with Swing and threads...

Posted on 2004-08-03
10
Medium Priority
?
339 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 
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 500 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

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
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 tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
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.
Suggested Courses
Course of the Month9 days, 5 hours left to enroll

764 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