• Post Reply Bookmark Topic Watch Topic
  • New Topic

Problems in using Threads in JAVA SWING program

 
Rohan Chaudhari
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have written a java program in which I have created a panel containing some text fields and buttons. In the program I am trying to set the focus on the first text field ousing the requestFocus() method.For this I am using multithreading, so that on 1 thread the components are being created and in the other thread I am invoking the focus logic. Below is my implementation for the focus setting:

public void forceFocus()
{
Runnable myRunnable = new Runnable()
{
public void run()
{
try
{
//I am making it to sleep so that other activities like enabling all
//the text fields all the buttons in the JPanel.
Thread.sleep(250);


compMandToReceiveFocus.requestFocus();
}
catch(Exception e)
{}
}
};

//As the implementation of thread sceduling is OS dependent, I am
//setting the New Thread priority to minum. This is being for all
// OS except windows.

int osType = BrowserServices.getBrowserServices().getOSID();
if((osType != BrowserServices.OS_WINDOWS_95) &&
(osType != BrowserServices.OS_WINDOWS_NT) &&
(osType != BrowserServices.OSTYPE_WINDOWS))
thread.setPriority(Thread.MIN_PRIORITY);

thread.start();
}


The above code was working fine on all OSes on the java 1.3.1_08. However, when I ported this program to java 1.5.1, it's giving strange results...

On jdk1.5.1 and UNIX OS, the above code is working fine. However, it's not working on Windows. When I tried to increase the sleep duration, although the cursor comes in the text filed, but the panel is frozen... I cannot enter anything on the field.

Can anybody please help me on how to solve this issue?

Thanks
 
Henry Wong
author
Sheriff
Posts: 22518
109
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Once the Swing set is displayed, only the event dispatching thread is allowed to called methods of the components. Calling methods from any other thread may *not* work, as it is *not* thread safe.

You have two options...

- Once your thread has calculated what needs to be done, it can call the SwingUtilities class to dispatch a runnable to be executed by the event dispatching thread. Take a look at the invokeLater() and invokeAndWait() methods.

- Since all you are doing is sleeping and then calling focus, you can also use this version of the Timer class instead. The swing timer will use the event dispatching thread to execute the action listener specifed.

Henry
 
Rohan Chaudhari
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The SwingUtilities logic worked in my case

Thanks a lot.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!