THE EVENT DISPATCHING THREAD
THE EVENT DISPATCHING THREAD
Listeners, as we've mentioned before, process every event and every event is in an event-dispatching thread. In the api, a FIFO queue of events is associated with this thread, an EventQueue instance, that is the system events queue and defined in the java.awt.EventQueue class. This queue is filled in a serial fashion, FIFO-like. As events are executed, this is done serially too, whether the event is a component property update or repainting .
Please ensure that all your events are within this thread and none should be dispatched outside this event dispatching thread. Also ensure that event handling code and painting codes will be executed quickly, i.e keep them simple. Otherwise, one event that takes up time could block the whole queue and your application gets frozen or locked up.
I have written a code here that makes use of the event dispatching threads on two listeners that listen for the same type of event, a mouse click.
package tests;
import java.awt.event.*;
public class FirstListener extends MouseAdapter {
public void mouseClicked(MouseEvent e){
//after this listener processes event, remove from queue
//and just add the second to make sure we did not remove
//it earlier also
Property.simplyText("the first listener at attention.");
Property.jButton1.removeMouseListener(this);
Property.jButton1.addMouseListener(new SecondListener());
}
}
import java.awt.event.*;
public class SecondListener extends MouseAdapter {
public void mouseClicked(MouseEvent e){
//after this listener processes event, remove from queue
//and just add the second to make sure we did not remove
//it earlier also
Property.simplyText("the second listener at attention.");
Property.jButton1.removeMouseListener(this);
Property.jButton1.addMouseListener(new FirstListener());
}
}
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class Property extends JPanel{
EventListenerList listenerList = new EventListenerList();
FirstListener fl = new FirstListener();
SecondListener sl = new SecondListener();
MouseEvent me;
static JButton jButton1 = new JButton(" ");
static JTextArea jText;
/** Creates a new instance of Property */
public Property() {
jButton1 = new JButton("click me");
add(jButton1);
//here are the two listeners added to the event dispatching
//queue
jButton1.addMouseListener(fl);
jButton1.addMouseListener(sl);
jText = new JTextArea("welcome", 5, 50);
add(jText);
}
private static void dButton(){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Property");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Property nProp = new Property();
nProp.setOpaque(true);
frame.setContentPane(nProp);
frame.pack();
frame.setVisible(true);
}
public static void simplyText(String txt){
jText.setText(txt);
}
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
dButton();
}
});
}
}
No comments:
Post a Comment