Java Event Custom Event learning

Source: Internet
Author: User

Course design to do a game, because C + + is not very familiar with the teacher also allowed to use Java or other languages, in. NET I learned events, a delegate callback, but in Java I do not know very well, should be the same principle!

The game is roughly like this, and now it's written in a successful judgment! So I added an event on my own.

Package Com.zhaojun.base;import Org.w3c.dom.events.event;import java.util.*;/** * Game class * * @author Coder-jun */public clas s Game {/* Map enumeration */    public enum Map_user {Red, Black, Null,}/* Record error log */private StringBuilder errorstringbuilder;    /* Record log */private StringBuilder arrivedbuilderlog;    /* Game map */private map_user[][] map;    public int GetCount () {return this._count;    } public int Getallcount () {return this._all_count;    } private int _xcount;    private int _ycount; /* Record Victory Person */private Map_user Winuser = Map_user.    Null;    Private Dictionary<map_user, string> _usermsg;    private int _count;//Walk how many private int _all_count;//altogether can walk how many private Collection winlistener; /** * Add Success Event * * @param listener */public void Addwinlistener (WinEvent listener) {if (winliste        NER = = null) {Winlistener = new HashSet ();    } this.winlistener.add (listener);        } private void Notifydoevent () {Iterator iter = Winlistener.iterator (); while (Iter.hasnext ()) {WinEvent listener = (winevent) itEr.next (); Listener.        Doevent ();    }}/** * Successful interface */public interface WinEvent extends EventListener {public void doevent ();        }/** * Initialize map size * * @param xcount * @param ycount * * * private Game (int xcount, int ycount) {        /* Initialize map */Errorstringbuilder = new StringBuilder ();        Arrivedbuilderlog = new StringBuilder (); Arrivedbuilderlog.append ("1. Initialize the map successfully!        \ n ");        _usermsg = new Hashtable<map_user, string> ();        This.initmap (Xcount, Ycount);    This.inituser ();        } public static void Start (int x, int y) {//Initialize map game game = new Game (x, y);        Scanner Scanner = new Scanner (system.in); Game.addwinlistener (New WinEvent () {@Override public void doevent () {System.out.pri            Ntln ("I succeeded in pulling!");        }        });        Save user byte Userint = 1;      /* Chess */for (int i = 0; i < Game.getallcount (); ++i) {      Chess Start Map_user USER;            int var11;            int var12; while (true) {/* users determine start*/user = Map_user.                Null; Switch (userint) {case 1:user = Map_user.                        Red;                        System.out.println ("Red side to go first X, y:");                    Break Case 2:user = Map_user.                        Black;                System.out.println ("Black side to go first X, y:");                    }/*end*/String string = Scanner.next ();                    /* Parse Path */try {string[] e = String.Split (",");                        if (e.length >= 2) {var11 = Integer.parseint (e[0]);                    Var12 = Integer.parseint (e[1]);                        } else {System.err.println ("You are wrong in chess, re-amended!");                    Continue               } } catch (Exception var10) {System.err.println ("You are wrong in chess, re-amended!");                Continue }//Chess fails if (!game.inputgo (Var11, var12, user)) {System.err.println (game                    . GetError ());                Continue                    } else {game.showmap ();                        if (Userint = = 1) {userint = 2;                    Break                        } if (Userint = = 2) {userint = 1;                    Break }}}//Chess Start}}/** * @return * * * Private Map_user CHECKW In () {return map_user.    Black;         /** * Load Map * * @param xcount * @param ycount * * * private void Initmap (int xcount, int ycount) {        Record the total step this.map = new Map_user[xcount][ycount]; for (int i = 0; i < map.length; i++) {            for (int j = 0; J < Map[i].length; J + +) {Map[i][j] = Map_user.            Null;        }} this._xcount = Xcount;        This._ycount = Ycount;    This._all_count = Xcount * YCOUNT;        }/** * Initialize user */private void Inituser () {System.out.println ("Please enter Black Name:");        Scanner Canscanner = new Scanner (system.in);        String heinamestring = Canscanner.next ();        System.out.println ("Please enter the Red Party name:");        String hongnamestring = Canscanner.next (); _usermsg.put (Map_user.        Black, heinamestring); _usermsg.put (Map_user.    Red, hongnamestring);             /** * Map * */private void Showmap () {for (int i = 0; i < map.length; i++) {/* Output header */                if (i = = 0) {System.out.print ("map\t");                for (int j = 0; J < Map[i].length; J + +) {System.out.print ("[" + j + "]\t");            } System.out.println ("");        }    System.out.print ("[" + i + "]\t"); /* Map Output */for (int j = 0; J < Map[i].length; J + +) {System.out.print ("{" + Map[i][j] + "}\t"            );        } System.out.println (""); }}/** * Chess * * @param x * @param y * @param user * @return */Private Boolean input        Go (int x, int y, Map_user USER) {Boolean tag = false;            /* Cross Check * * * if (x > This.map[0].length-1) {errorstringbuilder.append ("Chess crosses x Foul!");        return false;            } if (Y > This.map.length-1) {errorstringbuilder.append ("Play chess crosses y foul!");        return false; } if (map[y][x] = = Map_user.            Null) {map[y][x] = user;        Tag = true; } else {/* Add error message */Errorstringbuilder.append ("x:" + x + "y:" + y + "Someone has been under this place!!            ");        return false; }/* the user under the game is successful! */if (this.checkwin () = = Map_user. Null) {}else {} this._count++;    return tag; /** * GET error message * * @return error message */private String GetError () {String resstring = ErrorString        Builder.tostring ();        This.errorStringBuilder.delete (0, Errorstringbuilder.length ()-1);    return resstring; }}

1. To use the event first, you must write an interface to inherit EventListener and then write an interface method that needs to be implemented.

/**
Successful interface
*/
Extends EventListener {
public void doevent ();
}
Private CollectionWinlistener;

/**
*Add Success Events
*
* @param */
public void Addwinlistener (WinEvent listener) {
if (winlistener = = winlistener = new HashSet ();
}
this. Winlistener.add (listener);
}

private void Notifydoevent () {
Winlistener.iterator ();
while (Iter.hasnext ()) {
WinEvent listener = (winevent) iter.next ();
Listener. Doevent ();
}
}

2. Implementation of basic add-on events and notifications can be made;;; The next step is to use

Haha, success!

Learning Source: http://www.cnblogs.com/atyou/archive/2013/01/07/2850321.html

Java Event Custom Event learning

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.