我想问一下java的事件驱动机制是如何实现的,如何实现自定义的事件驱动?不够再加100!

时间:2022-10-04 20:05:50
我们知道java这样的面向对象是由事件驱动机制来运行的!我想问一下java的事件驱动机制是如何实现的,如何实现自定义的事件驱动?不够再加100!

16 个解决方案

#1


up!

#2


其实java的事件机制十分简单,你完全可以实现自己的事件驱动;
主要涉及到如下几个类(可以参考键盘事件的有关类):
1.事件类XXXEvent,其中包含你所规定的事件的一些信息,如事件源,事件名称等等,如KeyEvent,中有eventSource,keyCode等等
2.事件监听接口,XXXEventListener,其中包含捕获到事件的类要作的事情,如KeyListener,其中包括:keyPress,keyReleased,等等
如:
public interface XXXListener{
   public void doXXXEvent(xxxEvent e);
}
3.发出事件的类:可以是任意的类,在这个类中,可以发出该事件XXXEvent,比如可以在这个类中添加一个fireXXXEvent方法,在这个方法中去手工发出事件,如:
public void fireXXXEvent(){
    java.util.Vector targets; 
    synchronized (this) {
        targets = (java.util.Vector) xxxListeners.clone();
    }
    XXXEvent evt = new XXXEvent(.....);
    for (int i = 0; i < targets.size(); i++) {            
            XXXListener target = (XXXListener) targets.elementAt(i);
            target.doXXXEvent(evt);
    }
}
此外在这个类里要有一个监听列表即上面的xxxlisteners,在这个类中还要实现一个addXXXListrener(XXXListener)方法,来把一个实现了XXXListenr的类作为监听者加到该类中。


这样就基本实现了,讲的可能不大明白,咱们再来讨论。

#3


java的授权事件模型
    在授权事件模型中,源产生一个事件,并将它传送到一个或多个接收器。接受器只是等待,直到它接收到一个事件。一旦它接收到以后,接收器处理该事件然后返回。
    事件接收器在源中注册自己!
类似于vc:
    如果你想实现自己的事件响应函数,你只要在注册监听器的同时调用自己的处理函数,相当于在vc的消息映射池,你只要把消息指向你的处理函数就可以了。如果你想实现自定义事件,你要实现一个事件Event,相当于vc的WM_USER+1,同时你还要实现事件的传递,像实现vc的自定义消息传递Notify()。

下面是一个例子:

#4


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.util.*;

/**
 * This class is a Swing component that presents a choice to the user.  It
 * allows the choice to be presented in a JList, in a JComboBox, or with a
 * bordered group of JRadioButton components.  Additionally, it displays the
 * name of the choice with a JLabel.  It allows an arbitrary value to be
 * associated with each possible choice.  Note that this component only allows
 * one item to be selected at a time.  Multiple selections are not supported.
 **/
public class ItemChooser extends JPanel {
    // These fields hold property values for this component
    String name;           // The overall name of the choice
    String[] labels;       // The text for each choice option
    Object[] values;       // Arbitrary values associated with each option
    int selection;         // The selected choice
    

    // These are the legal values for the presentation field
    public static final int LIST = 1;
    
    // These components are used for each of the 3 possible presentations
    JList list;                     // One type of presentation
    
    // The list of objects that are interested in our state
    ArrayList listeners = new ArrayList();

    // The constructor method sets everything up
    public ItemChooser(String name, String[] labels, Object[] values,
       int defaultSelection)
    {
// Copy the constructor arguments to instance fields
this.name = name;
this.labels = labels;
this.values = values;
this.selection = defaultSelection;

// If no values were supplied, use the labels
if (values == null) this.values = labels;

// Now create content and event handlers based on presentation type
initList();

    }

    // Initialization for JList presentation
    public void initList() {
list = new JList(labels);          // Create the list
list.setSelectedIndex(selection);  // Set initial state

// Handle state changes
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
    ItemChooser.this.select(list.getSelectedIndex());
}
    });

// Lay out list and name label vertically
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); // vertical
this.add(new JLabel(name));        // Display choice name
this.add(new JScrollPane(list));   // Add the JList
    }
        
    // These simple property accessor methods just return field values
    // These are read-only properties.  The values are set by the constructor
    // and may not be changed.
    public String getName() { return name; }
    public String[] getLabels() { return labels; }
    public Object[] getValues() { return values; }
    
    /** Return the index of the selected item */
    public int getSelectedIndex() { return selection; }
    
    /** Return the object associated with the selected item */
    public Object getSelectedValue() { return values[selection]; }
    
    /**
     * Set the selected item by specifying its index.  Calling this
     * method changes the on-screen display but does not generate events.
     **/
    public void setSelectedIndex(int selection) {
list.setSelectedIndex(selection);
this.selection = selection;
    }

    /**
     * This internal method is called when the selection changes.  It stores
     * the new selected index, and fires events to any registered listeners.
     * The event listeners registered on the JList, JComboBox, or JRadioButtons
     * all call this method.
     **/
    protected void select(int selection) {
this.selection = selection;  // Store the new selected index
if (!listeners.isEmpty()) {  // If there are any listeners registered
    // Create an event object to describe the selection
    ItemChooser.Event e =
new ItemChooser.Event(this, selection, values[selection]);
    // Loop through the listeners using an Iterator
    for(Iterator i = listeners.iterator(); i.hasNext();) {
ItemChooser.Listener l = (ItemChooser.Listener)i.next();
l.itemChosen(e);  // Notify each listener of the selection
    }
}
    }

    // These methods are for event listener registration and deregistration
    public void addItemChooserListener(ItemChooser.Listener l) {
listeners.add(l);
    }
    public void removeItemChooserListener(ItemChooser.Listener l) {
listeners.remove(l);
    }

    /**
     * This inner class defines the event type generated by ItemChooser objects
     * The inner class name is Event, so the full name is ItemChooser.Event
     **/
    public static class Event extends java.util.EventObject {
int selectedIndex;      // index of the selected item
Object selectedValue;   // the value associated with it
public Event(ItemChooser source,
     int selectedIndex, Object selectedValue) {
    super(source);
    this.selectedIndex = selectedIndex;
    this.selectedValue = selectedValue;
}

public ItemChooser getItemChooser() { return (ItemChooser)getSource();}
public int getSelectedIndex() { return selectedIndex; }
public Object getSelectedValue() { return selectedValue; }
    }

    /**
     * This inner interface must be implemented by any object that wants to be
     * notified when the current selection in a ItemChooser component changes.
     **/
    public interface Listener extends java.util.EventListener {
public void itemChosen(ItemChooser.Event e);
    }

    /**
     * This inner class is a simple demonstration of the ItemChooser component
     * It uses command-line arguments as ItemChooser labels and values.
     **/

#5



    public static class Demo {
public static void main(String[] args) {
    // Create a window, arrange to handle close requests
    final JFrame frame = new JFrame("ItemChooser Demo");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}
});

    // A "message line" to display results in
    final JLabel msgline = new JLabel(" ");
    

    // Create a panel holding ItemChooser components
    JPanel chooserPanel = new JPanel();
    final ItemChooser c = new ItemChooser("test", args, null, 0
   );
    
    
    // An event listener that displays changes on the message line
    ItemChooser.Listener l = new ItemChooser.Listener() {
    public void itemChosen(ItemChooser.Event e) {
msgline.setText(e.getItemChooser().getName() + ": " +
e.getSelectedIndex() + ": " +
e.getSelectedValue());
    }
};
    c.addItemChooserListener(l);
    
    // Instead of tracking every change with a ItemChooser.Listener,
    // applications can also just query the current state when
    // they need it.  Here's a button that does that.
    JButton report = new JButton("Report");
    report.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
// Note the use of multi-line italic HTML text
// with the JOptionPane message dialog box.
String msg = "<html><i>" +
  c.getName() + ": " + c.getSelectedValue() + "<br>";
JOptionPane.showMessageDialog(frame, msg);
    }
});

    // Add the ItemChooser objects, and the Button to the panel
    chooserPanel.add(c);
    
    chooserPanel.add(report);

    // Add the panel and the message line to the window
    Container contentPane = frame.getContentPane();
    contentPane.add(chooserPanel, BorderLayout.CENTER);
    contentPane.add(msgline, BorderLayout.SOUTH);
    
    // Set the window size and pop it up.
    frame.pack();
    frame.show();
}
    }
}

#6


没有人回我吗?

程序看不大懂啊!lins(*有为青年*) ,能不能说一下!

#7


zhangjw(zjw)能不能举个例子啊!

#8


各位大虾:帮帮忙!
我明天结帐!

#9


同意楼主。。。

#10


mm

#11


类ItemChooser有一个list类,当你点击list的选项时list类产生一个事件,该事件的处理函数调用ItemChooser的方法select(),select()方法产生一个自定义事件e,并且遍历了ItemChooser的listencers的监听器,把该事件传递给ItemChooser的自定义处理函数Itemchosen().这样就实现了自定义事件和自定义监听器。

#12


mark

#13



//define a event object,the object will tell the consumer which window throws the event
//a event object is a object that will take the data from source to dest,
//or a protocal between two  objects(here are Event source object and Event listener)
class WndEvent{
    Wnd m_oWnd;
    WndEvent(Wnd src){m_oWnd=src;}
    String getWnd(){return m_oWnd.toString();};
}

//define a listener that process the window event
interface WndListener{
    void wndOpen(WndEvent e);
    void wndClose(WndEvent e);
}

//a listener implemention
class AWndListener implements WndListener{
    public void wndOpen(WndEvent e){
        System.out.println("window ["+ e.getWnd() + "] opened.");
    }

    public void wndClose(WndEvent e){
        System.out.println("window ["+ e.getWnd() + "] closed.");
    }
}

//a event source object
class Wnd{
    String m_strWndName;
    Wnd(String strWndName){m_strWndName=strWndName;}

    void initShow(){
        //show the window first time
        //after accomplish this,call wndOpen()
        for(int i=0;i<vListeners.size();i++){
            ((WndListener)vListeners.get(i)).wndOpen(new WndEvent(this));
        }
    }

    void close(){
        //close the window
        //after accomplish this,call wndClose()
        for(int i=0;i<vListeners.size();i++){
            ((WndListener)vListeners.get(i)).wndClose(new WndEvent(this));
        }
    }

    public String toString(){
        return m_strWndName;
    }

    Vector vListeners = new Vector();
    void addListener(WndListener el){
        vListeners.add(el);
    }
}

public class test{
    public static void main(String[] args){
        Wnd wnd = new Wnd("sample window a");//create source object

        //"通过调用源对象中特定的方法注册带有源的监听器对象"
        wnd.addListener(new AWndListener());//add a listener
        //add another listener(a anonymous class)
        wnd.addListener(new WndListener(){
                        public void wndOpen(WndEvent e){
                            System.out.println("I'v got window ["+ e.getWnd() + "] opened event.");
                        }

                        public void wndClose(WndEvent e){
                            System.out.println("I'v got window ["+ e.getWnd() + "] closed event.");
                        }
                    }
                    );
        //running
        wnd.initShow();//throws out event,src object will automatically call corresponding method of listeners registered ,here the method is wndOpen()
        wnd.close();//throws out event,src object will automatically call corresponding method of listeners registered ,here the method is wndClose()
    }
}

上述是现想的,没测试过,也是我对此理解的一个整理,希望大家能明白,有问题欢迎交流

#14


yun!

#15


java是事件监听机制,不是事件驱动

#16


很简单,楼上的见解一般而已

#1


up!

#2


其实java的事件机制十分简单,你完全可以实现自己的事件驱动;
主要涉及到如下几个类(可以参考键盘事件的有关类):
1.事件类XXXEvent,其中包含你所规定的事件的一些信息,如事件源,事件名称等等,如KeyEvent,中有eventSource,keyCode等等
2.事件监听接口,XXXEventListener,其中包含捕获到事件的类要作的事情,如KeyListener,其中包括:keyPress,keyReleased,等等
如:
public interface XXXListener{
   public void doXXXEvent(xxxEvent e);
}
3.发出事件的类:可以是任意的类,在这个类中,可以发出该事件XXXEvent,比如可以在这个类中添加一个fireXXXEvent方法,在这个方法中去手工发出事件,如:
public void fireXXXEvent(){
    java.util.Vector targets; 
    synchronized (this) {
        targets = (java.util.Vector) xxxListeners.clone();
    }
    XXXEvent evt = new XXXEvent(.....);
    for (int i = 0; i < targets.size(); i++) {            
            XXXListener target = (XXXListener) targets.elementAt(i);
            target.doXXXEvent(evt);
    }
}
此外在这个类里要有一个监听列表即上面的xxxlisteners,在这个类中还要实现一个addXXXListrener(XXXListener)方法,来把一个实现了XXXListenr的类作为监听者加到该类中。


这样就基本实现了,讲的可能不大明白,咱们再来讨论。

#3


java的授权事件模型
    在授权事件模型中,源产生一个事件,并将它传送到一个或多个接收器。接受器只是等待,直到它接收到一个事件。一旦它接收到以后,接收器处理该事件然后返回。
    事件接收器在源中注册自己!
类似于vc:
    如果你想实现自己的事件响应函数,你只要在注册监听器的同时调用自己的处理函数,相当于在vc的消息映射池,你只要把消息指向你的处理函数就可以了。如果你想实现自定义事件,你要实现一个事件Event,相当于vc的WM_USER+1,同时你还要实现事件的传递,像实现vc的自定义消息传递Notify()。

下面是一个例子:

#4


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.border.*;
import java.util.*;

/**
 * This class is a Swing component that presents a choice to the user.  It
 * allows the choice to be presented in a JList, in a JComboBox, or with a
 * bordered group of JRadioButton components.  Additionally, it displays the
 * name of the choice with a JLabel.  It allows an arbitrary value to be
 * associated with each possible choice.  Note that this component only allows
 * one item to be selected at a time.  Multiple selections are not supported.
 **/
public class ItemChooser extends JPanel {
    // These fields hold property values for this component
    String name;           // The overall name of the choice
    String[] labels;       // The text for each choice option
    Object[] values;       // Arbitrary values associated with each option
    int selection;         // The selected choice
    

    // These are the legal values for the presentation field
    public static final int LIST = 1;
    
    // These components are used for each of the 3 possible presentations
    JList list;                     // One type of presentation
    
    // The list of objects that are interested in our state
    ArrayList listeners = new ArrayList();

    // The constructor method sets everything up
    public ItemChooser(String name, String[] labels, Object[] values,
       int defaultSelection)
    {
// Copy the constructor arguments to instance fields
this.name = name;
this.labels = labels;
this.values = values;
this.selection = defaultSelection;

// If no values were supplied, use the labels
if (values == null) this.values = labels;

// Now create content and event handlers based on presentation type
initList();

    }

    // Initialization for JList presentation
    public void initList() {
list = new JList(labels);          // Create the list
list.setSelectedIndex(selection);  // Set initial state

// Handle state changes
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
    ItemChooser.this.select(list.getSelectedIndex());
}
    });

// Lay out list and name label vertically
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); // vertical
this.add(new JLabel(name));        // Display choice name
this.add(new JScrollPane(list));   // Add the JList
    }
        
    // These simple property accessor methods just return field values
    // These are read-only properties.  The values are set by the constructor
    // and may not be changed.
    public String getName() { return name; }
    public String[] getLabels() { return labels; }
    public Object[] getValues() { return values; }
    
    /** Return the index of the selected item */
    public int getSelectedIndex() { return selection; }
    
    /** Return the object associated with the selected item */
    public Object getSelectedValue() { return values[selection]; }
    
    /**
     * Set the selected item by specifying its index.  Calling this
     * method changes the on-screen display but does not generate events.
     **/
    public void setSelectedIndex(int selection) {
list.setSelectedIndex(selection);
this.selection = selection;
    }

    /**
     * This internal method is called when the selection changes.  It stores
     * the new selected index, and fires events to any registered listeners.
     * The event listeners registered on the JList, JComboBox, or JRadioButtons
     * all call this method.
     **/
    protected void select(int selection) {
this.selection = selection;  // Store the new selected index
if (!listeners.isEmpty()) {  // If there are any listeners registered
    // Create an event object to describe the selection
    ItemChooser.Event e =
new ItemChooser.Event(this, selection, values[selection]);
    // Loop through the listeners using an Iterator
    for(Iterator i = listeners.iterator(); i.hasNext();) {
ItemChooser.Listener l = (ItemChooser.Listener)i.next();
l.itemChosen(e);  // Notify each listener of the selection
    }
}
    }

    // These methods are for event listener registration and deregistration
    public void addItemChooserListener(ItemChooser.Listener l) {
listeners.add(l);
    }
    public void removeItemChooserListener(ItemChooser.Listener l) {
listeners.remove(l);
    }

    /**
     * This inner class defines the event type generated by ItemChooser objects
     * The inner class name is Event, so the full name is ItemChooser.Event
     **/
    public static class Event extends java.util.EventObject {
int selectedIndex;      // index of the selected item
Object selectedValue;   // the value associated with it
public Event(ItemChooser source,
     int selectedIndex, Object selectedValue) {
    super(source);
    this.selectedIndex = selectedIndex;
    this.selectedValue = selectedValue;
}

public ItemChooser getItemChooser() { return (ItemChooser)getSource();}
public int getSelectedIndex() { return selectedIndex; }
public Object getSelectedValue() { return selectedValue; }
    }

    /**
     * This inner interface must be implemented by any object that wants to be
     * notified when the current selection in a ItemChooser component changes.
     **/
    public interface Listener extends java.util.EventListener {
public void itemChosen(ItemChooser.Event e);
    }

    /**
     * This inner class is a simple demonstration of the ItemChooser component
     * It uses command-line arguments as ItemChooser labels and values.
     **/

#5



    public static class Demo {
public static void main(String[] args) {
    // Create a window, arrange to handle close requests
    final JFrame frame = new JFrame("ItemChooser Demo");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}
});

    // A "message line" to display results in
    final JLabel msgline = new JLabel(" ");
    

    // Create a panel holding ItemChooser components
    JPanel chooserPanel = new JPanel();
    final ItemChooser c = new ItemChooser("test", args, null, 0
   );
    
    
    // An event listener that displays changes on the message line
    ItemChooser.Listener l = new ItemChooser.Listener() {
    public void itemChosen(ItemChooser.Event e) {
msgline.setText(e.getItemChooser().getName() + ": " +
e.getSelectedIndex() + ": " +
e.getSelectedValue());
    }
};
    c.addItemChooserListener(l);
    
    // Instead of tracking every change with a ItemChooser.Listener,
    // applications can also just query the current state when
    // they need it.  Here's a button that does that.
    JButton report = new JButton("Report");
    report.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
// Note the use of multi-line italic HTML text
// with the JOptionPane message dialog box.
String msg = "<html><i>" +
  c.getName() + ": " + c.getSelectedValue() + "<br>";
JOptionPane.showMessageDialog(frame, msg);
    }
});

    // Add the ItemChooser objects, and the Button to the panel
    chooserPanel.add(c);
    
    chooserPanel.add(report);

    // Add the panel and the message line to the window
    Container contentPane = frame.getContentPane();
    contentPane.add(chooserPanel, BorderLayout.CENTER);
    contentPane.add(msgline, BorderLayout.SOUTH);
    
    // Set the window size and pop it up.
    frame.pack();
    frame.show();
}
    }
}

#6


没有人回我吗?

程序看不大懂啊!lins(*有为青年*) ,能不能说一下!

#7


zhangjw(zjw)能不能举个例子啊!

#8


各位大虾:帮帮忙!
我明天结帐!

#9


同意楼主。。。

#10


mm

#11


类ItemChooser有一个list类,当你点击list的选项时list类产生一个事件,该事件的处理函数调用ItemChooser的方法select(),select()方法产生一个自定义事件e,并且遍历了ItemChooser的listencers的监听器,把该事件传递给ItemChooser的自定义处理函数Itemchosen().这样就实现了自定义事件和自定义监听器。

#12


mark

#13



//define a event object,the object will tell the consumer which window throws the event
//a event object is a object that will take the data from source to dest,
//or a protocal between two  objects(here are Event source object and Event listener)
class WndEvent{
    Wnd m_oWnd;
    WndEvent(Wnd src){m_oWnd=src;}
    String getWnd(){return m_oWnd.toString();};
}

//define a listener that process the window event
interface WndListener{
    void wndOpen(WndEvent e);
    void wndClose(WndEvent e);
}

//a listener implemention
class AWndListener implements WndListener{
    public void wndOpen(WndEvent e){
        System.out.println("window ["+ e.getWnd() + "] opened.");
    }

    public void wndClose(WndEvent e){
        System.out.println("window ["+ e.getWnd() + "] closed.");
    }
}

//a event source object
class Wnd{
    String m_strWndName;
    Wnd(String strWndName){m_strWndName=strWndName;}

    void initShow(){
        //show the window first time
        //after accomplish this,call wndOpen()
        for(int i=0;i<vListeners.size();i++){
            ((WndListener)vListeners.get(i)).wndOpen(new WndEvent(this));
        }
    }

    void close(){
        //close the window
        //after accomplish this,call wndClose()
        for(int i=0;i<vListeners.size();i++){
            ((WndListener)vListeners.get(i)).wndClose(new WndEvent(this));
        }
    }

    public String toString(){
        return m_strWndName;
    }

    Vector vListeners = new Vector();
    void addListener(WndListener el){
        vListeners.add(el);
    }
}

public class test{
    public static void main(String[] args){
        Wnd wnd = new Wnd("sample window a");//create source object

        //"通过调用源对象中特定的方法注册带有源的监听器对象"
        wnd.addListener(new AWndListener());//add a listener
        //add another listener(a anonymous class)
        wnd.addListener(new WndListener(){
                        public void wndOpen(WndEvent e){
                            System.out.println("I'v got window ["+ e.getWnd() + "] opened event.");
                        }

                        public void wndClose(WndEvent e){
                            System.out.println("I'v got window ["+ e.getWnd() + "] closed event.");
                        }
                    }
                    );
        //running
        wnd.initShow();//throws out event,src object will automatically call corresponding method of listeners registered ,here the method is wndOpen()
        wnd.close();//throws out event,src object will automatically call corresponding method of listeners registered ,here the method is wndClose()
    }
}

上述是现想的,没测试过,也是我对此理解的一个整理,希望大家能明白,有问题欢迎交流

#14


yun!

#15


java是事件监听机制,不是事件驱动

#16


很简单,楼上的见解一般而已