Friday, December 14, 2007

Use threads to collect user input in forms

How to use threads in Java to get user input in forms?

You have to create a new form, pass the parameters (such as labels to be displayed on the form) and display the form. But how do we get the information input by the user to such forms. You can supply getters in the form implementation class. But the form instance has to first collect the information in the fields in order to access them. So how do we know when these values are obtained?

This is where we have to use threads. Create the form instance and invoke it in a new thread. Then issue a synchronized wait. Once the user inputs all information in the form, it can issue a synchronized notify in order to let the waiting object know that the information entered by the user are now available through the getters.

Eg.

Suppose you have a popupmenu which has an item to enter the information. So when the user clicks this form, the form has to appear. The user submits the information by clicking the OK button. Then the waiting object needs to be notified.

JMenuItem createNew=new JMenuItem("Enter info”);

menuItems.add(createNew);

createNew.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e) {

CollectInfo infoCollector=new CollectInfo ();

Thread t=new Thread(infoCollector);

t.start();

}});

The CollectInfo class implements the Runnable interface.

class CollectInfo implements Runnable

{

WaitObject obj; //just an object to wait on.

public void run()

{

InfoForm form=new InfoForm (obj,"Enter Info”);

form.setEnabled(true);

synchronized(obj)

{

try {

obj.wait();

} catch (InterruptedException ex) {

System.err.println(ex.getMessage());

}


}


//use getters of InfoForm to access the input data


}

}

class InfoForm extends JFrame

{

WaitObject object;

InfoForm(WaitObject obj, String title)

{

this.object=obj;

setTitle(title);

JButton okBtn=new JButton("OK");

okBtn.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e)

{

synchronized (object) {

object.notifyAll();//notifies the obj of CollectInfo class waiting.

done=true;

}

dispose();

}

});

}

…….

….

…..

//other controls on the frame and the getter methods

}

No comments: