Solved

Problems with Swing and threads...

Posted on 2004-08-03
10
319 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
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
java 8 lambda expresssions exception handling 3 88
thymeleaf natural templating vs JSP 2 95
eclipse java  build path 6 56
maven module vs maven project 3 21
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…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

808 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