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
Solved

Problems with Swing and threads...

Posted on 2004-08-03
10
324 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
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
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…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

860 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