Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Problems with Swing and threads...

Posted on 2004-08-03
10
Medium Priority
?
346 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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

Tech or Treat!

Submit an article about your scariest tech experience—and the solution—and you’ll be automatically entered to win one of 4 fantastic tech gadgets.

Question has a verified solution.

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

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses

618 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