Event Monitoring mechanism in Java

Source: Internet
Author: User
Tags event listener gety

Three aspects of the mouse event monitoring mechanism:

1. Event Source object:

The event source object is the object that can produce the action. All container components and element components in the Java language are event source objects in event snooping. In Java, depending on the action of the event to distinguish between different event source objects, which component the action occurs on, then the component is the event source object

2. Event Monitoring method:

Addmouselistener (MouseListener ml); This method is mainly used to capture the mouse release, press, click, enter and leave the action, after capturing the corresponding action, the event processing class (Implement the MouseListener Interface) processing.

addActionListener (ActionListener al); Captures a mouse click action on a similar button component or a keyboard return action on a similar input box component The actions and related information are then processed by the corresponding methods of the event-handling class (Implementing the ActionListener interface).

Addmousemotionlistener (Mousemotionlistener MML) captures mouse movement and drag actions, and then moves the action and related information to the event-handling class (implementing Mousemotionlistener interface) is handled by the corresponding method.

Addkeylistener (KeyListener KL) captures the press, release, and strike action of the keyboard key on the event source object, and then handles the action and related information to the appropriate method of the event-handling class (Implementing the KeyListener interface).

3. Event interface (event handler class, also the class that implements the event interface):

MouseListener Mouse Event interface, there are press, release, click, enter and leave the event handling method

ActionListener action event interface with action-corresponding event-handling method

Mousemotionlistener Mouse Movement event interface, with move and drag event handling methods

Keylisetener Keyboard event interface, event handling method with release, press and Tap

Having learned about these three aspects of event monitoring, it is easy for us to listen on the components to add events. Here is a small example:

Objective: To create a simple drawing board, you can press the corresponding functions to achieve different painting purposes.

Analysis: 1. A simple interface that requires a drawing board is preferred, defining a draw class to initialize the interface using the Java Swing component.

2. Then define the event interface Drawlistener class, let it implement the above interface, rewrite the interface in the method, to achieve their own purposes.

3. Instantiate the object of the Drawlistener class in draw.

4. Add an event listener method for the components in the draw class, specifying that the event handler class is Drawlistener.

Code implementation:

Draw class

Package Com.cbs;import Java.awt.color;import java.awt.dimension;import java.awt.flowlayout;import Java.awt.graphics;import java.awt.Event. Actionevent;import java.awt.Event. Actionlistener;import Javax.swing.jbutton;import Javax.swing.JFrame;/** Draw class for initialization of the interface * * @author CBS **/ Public classDraw { Public Static voidMain (string[] args) {Draw T=NewDraw ();    T.showui (); }    //Interface Initialization Method     Public voidShowUI () {JFrame JF=NewJFrame (); Jf.settitle ("Drawing"); Jf.setsize ( the, the); Jf.setdefaultcloseoperation (3); Jf.setlocationrelativeto (NULL); FlowLayout Layout=NewFlowLayout (Flowlayout.left);        Jf.setlayout (layout); JButton DrawLine=NewJButton ("Draw a line");        Jf.add (DrawLine); JButton DrawOval=NewJButton ("Draw an ellipse");        Jf.add (DrawOval); JButton DrawArc=NewJButton ("Draw a curve");        Jf.add (DRAWARC); JButton DrawPolygon=NewJButton ("Triangles");        Jf.add (DrawPolygon); JButton JB1=NewJButton ();        Jb1.setbackground (color.red);        Jf.add (JB1); Jb1.setpreferredsize (NewDimension ( -, -)); JButton JB2=NewJButton ();        Jb2.setbackground (Color.green);        Jf.add (JB2); Jb2.setpreferredsize (NewDimension ( -, -)); Jf.setvisible (true); Graphics g= Jf.getgraphics ();//gets the current brushDrawlistener dl =NewDrawlistener (g);//instantiating an object of the Drawlistener classJf.addmouselistener (DL);//to add a mouse event listener method to a formJf.addmousemotionlistener (DL);//to add a mouse move event listener method to a form//add an action listener to a buttonDrawline.addactionlistener (DL);        Drawoval.addactionlistener (DL);        Jb1.addactionlistener (DL);        Jb2.addactionlistener (DL);        Drawarc.addactionlistener (DL);    Drawpolygon.addactionlistener (DL); }}

Drawlistener class

Package Com.cbs;import java.awt.color;import java.awt.graphics;import java.awt.image;import java.awt.Event. Actionevent;import java.awt.Event. Actionlistener;import java.awt.Event. Mouseevent;import java.awt.Event. Mouselistener;import java.awt.Event. Mousemotionlistener;import Javax.swing.imageicon;import Javax.swing.JButton;/** * Event Handling class * * @author CBS **/ Public classDrawlistener implements MouseListener, Mousemotionlistener, ActionListener {Private intx1, y1, x2, y2;//record the Click coordinates of the mouse two times    PrivateGraphics G;//getting canvas objects from the interface    PrivateString str;//record the current button's information, distinguish between different buttons    PrivateColor color;//record The color information of a brush    Private intf =1;//control variables, for updating coordinates     PublicDrawlistener (Graphics g) { This. G =G; }    //How to handle when the mouse is pressed     Public voidmousepressed (MouseEvent e) {//records the position of the first click, which is obtained by the object e        if(f = =1) {x1=E.getx (); Y1=e.gety (); }    }    //How to handle mouse clicks     Public voidmouseclicked (MouseEvent e) {if("Triangles". Equals (str)) {System. out. println ("sanjaioxing"); intx, y; X=E.getx (); Y=e.gety ();            G.setcolor (color);            G.drawline (x, y, x1, y1);            G.drawline (x2, y2, x, y); F=1; }    }    //How to handle when mouse is released     Public voidmousereleased (MouseEvent e) {//record the coordinates when the mouse is released        if(f = =1) {X2=E.getx (); Y2=e.gety (); }        //Two coordinates are obtained, can be used for line drawing, call the Canvas object G method, draw a line on the interface        if("Draw a line". Equals (str))            {G.setcolor (color);        G.drawline (x1, y1, x2, y2); }        if("Draw an ellipse". Equals (str))            {G.setcolor (color);        G.drawoval (x1, y1, x2, y2); }        if("Triangles". Equals (str) && F = =1) {g.setcolor (color);            G.drawline (x1, y1, x2, y2); F++; }    }    //how to deal with mouse entry     Public voidmouseentered (MouseEvent e) {}//How to handle when the mouse exits     Public voidmouseexited (MouseEvent e) {} Public voidactionperformed (ActionEvent e) {if("". Equals (E.getactioncommand ())) {JButton JB=(JButton) E.getsource (); Color=Jb.getbackground (); } Else{str=E.getactioncommand (); }    }    //How to handle the mouse when dragging     Public voidmousedragged (MouseEvent e) {if("Draw a curve". Equals (str)) {            intx, y; X=E.getx (); Y=e.gety ();            G.setcolor (color);            G.drawline (x1, y1, x, y); X1=x; Y1=y; }    }    //How to move when Mouse is released     Public voidmousemoved (MouseEvent e) {}}

PS: Purely further reseach, please correct me.

Event Monitoring mechanism in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.