JAVA game works - mine
Abstract: JAVA game works - mine
*************************** Programming ideas ******************** ***********
The fry are familiar with the game, the mouse click box mine, if it is mine, Manpanjieshu, if not mine, the mine opened boxes, showing that the number of minefields around. If this box around lap mine is not mine, the mine should be around the boxes are opened, and were in accordance with the above rules on iterative cycle, this cycle should come to an end in the face of boxes containing Lei Lei there, or all the minefields boxes have been detecting End, the difficulty of programming it here, we pay more attention to bones_box under the category of the left mouse button click events and bones_triggers () process, with special attention to
Is_clicked this Boolean value, it is precisely because he makes the use of iterative As for the smooth conduct of mine, I immediately adopted the way, it was said that the company's mines is very sophisticated, I do not know that the algorithm, as if still a very deep Mathematical problems, you who had nothing to feed on the bar
************************************************** *****************/
Import java.awt .*;
Import java.awt.event .*;
Import javax.swing .*;
Import javax.swing.border .*;
Import java.util .*;
Public class bones_game / / Lord of the game, initialization interface, generating minefields
(
Public static int clicked_counter = 450; / / counters, 0:00 to the successful conclusion of that mine
JFrame MainFrame; / / main form
JButton button_refresh;
Bones_box bones_box [];// Lei box
Public bones_game () / / constructor
(
Int i;
Bones_box new bones_box = [450];
Button_refresh = new JButton ( "re-start the game");
MainFrame = new JFrame ( "mine games");
MainFrame.getContentPane (). SetLayout (new BorderLayout ());
Container box_grid = new Container ();
Box_grid.setLayout (new GridLayout (15th and 30th));
For (i = 0; i <450; i ++)// draw all minefields box
(
Bones_box [i] = new bones_box (i, this);
Box_grid.add (bones_box [i]);
)
Bones_sts_refresh ();// updated information
MainFrame.getContentPane (). Add (button_refresh, BorderLayout.NORTH);
MainFrame.getContentPane (). Add (box_grid, BorderLayout.CENTER);
MainFrame.pack ();
MainFrame.show ();
MainFrame.addWindowListener (new WindowAdapter ()
(
Public void windowClosing (WindowEvent e) (
System.exit (0);
)
));
Button_refresh.addMouseListener (new MouseAdapter ()
(
Public void mouseClicked (MouseEvent e)
(
Bones_sts_refresh ();
)
));
)
Public static void main (String [] argus)
(
Games start new bones_game ();//
)
Public void bones_sts_refresh () / / set all minefields boxes, layout information
(
Int i, j;
Clicked_counter = 450;
For (i = 0; i <450; i + +)
(
Bones_box [i]. SetEnabled (true);
Bones_box [i]. Is_clicked = false;
Bones_box [i]. SetVisible (true);
Bones_box [i]. Is_bone = false;
Bones_box [i]. Number_of_real_bone = 0;
Bones_box [i]. Flag = "";
Bones_box [i]. SetText ( "");
Bones_box [i]. SetBorder (BorderFactory.createBevelBorder (BevelBorder.RAISED, Color.white, Color.black ));// processes for the initial state
Bones_box [i]. SetBackground (Color.gray);
)
For (i = 0; i <90; i ++)// random minefields
(
Bones_box [(int) (Math.random () * 449)]. Is_bone = true;
)
For (i = 0; i <450; i ++)// statistics were each Lei Lei the number of boxes around
(
If (bones_box [i]. Is_bone) / / Lei Lei in the box and does not participate in overlapping zone, by the Counter
(
Bones_game.clicked_counter–;
)
For (j = 0; j <8; j + +)
(
If (bones_box [i]. Bones_around [j] == 777)
(
Continue;
)
If (bones_box [bones_box] [i]. Bones_around [j]]. Is_bone)
(
Bones_box [i]. Number_of_real_bone + +;
)
)
/ / Open the code can look at the distribution of mine
/ / If (bones_box [i]. Is_bone)
/ / (
/ / Bones_box [i]. SetText ( "â—");
/ /)
)
)
Public void game_lose ()
(
Int type, k;
For (k = 0; k <450; k + +)
(
If (bones_box [k]. Is_bone)
(
Bones_box [k]. SetText ( "â—");
)
)
Type = JOptionPane.INFORMATION_MESSAGE;
JOptionPane.showMessageDialog (MainFrame, "I am sorry, you lose, I would like to thank !!!"," messages" type);
Bones_sts_refresh ();
)
Public void game_win ()
(
Int type;
Type = JOptionPane.INFORMATION_MESSAGE;
JOptionPane.showMessageDialog (MainFrame, "serious Congratulations, you won, Shaque !!!"," messages" type);
Bones_sts_refresh ();
)
)
Class bones_box extends JTextField / / Lei box
(
Public boolean is_clicked = false; / / check whether the signs
Public boolean is_bone = false; / / Is mine
Public int bone_id; / / Lei box logo,
Public int [] bones_around; / / minefields around the box BONE_ID to form an array of records
Public bones_game frame_handle; / / handle of the game
Public int number_of_real_bone; / / lap around the total number of minefields
Public String flag; / / right-click on the logo "↑": logo for the mine "?": Uncertain state ",": space
Public bones_box (int i, bones_game handle) / / constructor
(
Super ();
This.bone_id = i;
/ / This.setEnabled (false);
This.frame_handle = handle;
This.setCursor (frame_handle.MainFrame.getCursor ());
This.setForeground (Color.cyan);
This.bones_around = find_bones_around ();// access to the ID boxes around the mine, an array of deposit bones_around
This.addMouseListener (new MouseAdapter ()
(
Public void mouseClicked (MouseEvent e)
(
Int j;
/*——————- Bond pronged ———————-
Capture poor results, it gives rise to the slightest deviation below the left or right, do not know if you are better able to accurately capture the way this incident, like Microsoft, did not even fingers the keyboard at the same time, can be captured, if found, could be below code package, and I told DEV一声
(
Int k, li_num;
If (is_clicked)
(
For (k = 0, k <8, k + +)
(
If (frame_handle.bones_box [bones_around] [k]]. Flag == "↑")
(
Li_num + +;
)
)
If (li_num == number_of_real_bone)
(
For (k = 0, k <8, k + +)
(
If (frame_handle.bones_box [bones_around] [k]]. Flag == "↑")
(
Continue;
)
If (frame_handle.bones_box [bones_around] [k]]. Is_clicked)
(
Continue;
)
If (frame_handle.bones_box [bones_around] [k]]. Is_bone) / / failure
(
Frame_handle.game_lose ();
Return;
)
Frame_handle.bones_box [bones_around] [k]]. SetBorder (BorderFactory.createBevelBorder (BevelBorder.LOWERED, Color.white, Color.black ));// Lei box Waxia Show
Frame_handle.bones_box [bones_around] [k]]. SetBackground (Color.WHITE);
Frame_handle.bones_box [bones_around] [k]]. SetEnabled (false);
Frame_handle.bones_box [bones_around] [k]]. SetText (Integer.toString (frame_handle.bones_box [bones_around] [k]]. Number_of_real_bone ));// suggested that the number of minefields around
Frame_handle.bones_box [bones_around] [k]]. Is_clicked = true; / / mark the box in order to detect a mine, and avoid the frequent with each other have infinite loop
Bones_game.clicked_counter–;
)
)
)
Else
(
)
)
————————————————– –* /
If (e.getButton () == e.BUTTON1) / / left click on the
(
If (is_clicked)
(
Return;
)
If (flag == "↑") / / logo of the mine, click the direct return
(
Return;
)
If (is_bone) / / is mine, suggesting that the game failure
(
Frame_handle.game_lose ();
Return;
)
SetBorder (BorderFactory.createBevelBorder (BevelBorder.LOWERED, Color.white, Color.black ));// Lei box Waxia Show
SetBackground (Color.WHITE);
SetEnabled (false);
SetText (Integer.toString (number_of_real_bone ));// suggested that the number of minefields around
Is_clicked = true; / / mark the box in order to detect a mine, and avoid the frequent with each other have infinite loop
Bones_game.clicked_counter–;
Bones_triggers ();// trigger process
If (bones_game.clicked_counter <= 0)
(
Frame_handle.game_win ();
)
)
If (e.getButton () == e.BUTTON3) / / Right
(
If (is_clicked)
(
Return;
)
If (flag == "")
(
SetText ( "↑");
Flag = "↑";
Return;
)
If (flag == "↑")
(
SetText ("?");
Flag = "";
Return;
)
If (flag == "?")
(
SetText ("");
Flag = "";
Return;
)
)
)
));
)
Find_bones_around public int [] () / / in accordance with their own BONE_ID identify minefields lap around the ID box
(
Bones_around int [] = new int [8];
Int i, li_row, li_column;
Li_row = bone_id / 30;
Li_column bone_id-li_row * = 30;
Bones_around [0] = li_column - 1 + (li_row - 1) * 30;
Bones_around [1] = li_column + (li_row - 1) * 30;
Bones_around li_column [2] + = 1 + (li_row - 1) * 30;
Bones_around [3] = 1 + + li_column li_row * 30;
Bones_around li_column [4] + = 1 + (li_row + 1) * 30;
Bones_around [5] = li_column + (li_row + 1) * 30;
Bones_around [6] = li_column - 1 + (li_row + 1) * 30;
Bones_around [7] = li_column - 1 + li_row * 30;
If (li_column == 0) / / first out of the special treatment, because he left the air, and this will be marked as in the 777
(
Bones_around [0] = 777;
Bones_around [6] = 777;
Bones_around [7] = 777;
)
If (li_column == 29) / / Finally a special treatment, because his right is empty
(
Bones_around [2] = 777;
Bones_around [3] = 777;
Bones_around [4] = 777;
)
For (i = 0; i <bones_around.length; i + +)
(
If (bones_around [i] <0 | bones_around [i]> 449)
(
Bones_around [i] = 777;
)
)
Return bones_around;
)
Public void bones_triggers () / / trigger process
(
Int k;
Boolean is_all_free = true;
For (k = 0; k <8; k + +)
(
If (bones_around [k] == 777)
(
Continue;
)
If (frame_handle.bones_box [bones_around] [k]]. Is_bone)
/ / Not judge whether all around the mine, if the condition is not met, there will be no automatic trigger the necessary boxes around the mine, leaving players to hit their own
(
Is_all_free = false;
Break;
)
)
If (is_all_free) / / set up the conditions to begin automatically detect mines around the box
(
For (k = 0; k <8; k + +)
(
If (bones_around [k] == 777)
(
Continue;
)
If (frame_handle.bones_box [bones_around] [k]]. Flag == "↑") / / has been marked as mine, Skip
(
Continue;
)
If (frame_handle.bones_box [bones_around] [k]]. Is_clicked) / / detection, Skip
(
Continue;
)
Bones_game.clicked_counter–;
Frame_handle.bones_box [bones_around] [k]]. SetEnabled (false);
Frame_handle.bones_box [bones_around] [k]]. SetBorder (BorderFactory.createBevelBorder (BevelBorder.LOWERED, Color.white, Color.black));
Frame_handle.bones_box [bones_around] [k]]. SetBackground (Color.WHITE);
Frame_handle.bones_box [bones_around] [k]]. SetText (Integer.toString (frame_handle.bones_box [bones_around] [k]]. Number_of_real_bone));
Frame_handle.bones_box [bones_around] [k]]. Is_clicked = true;
Frame_handle.bones_box [bones_around] [k]]. Bones_triggers ();// iteration trigger continue
)
)
)
)
/*—————————— Edited by Cang, Bashen tools: EditPlus + JDK1.4.2—— ————————-*/
↑ Back
I Scjp on the online test
Abstract: On my Scjp online testing
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="271" height="86" align="center" valign="top"> </ td> <td width="413" valign="top"> on my Scjp Online testing, a summary.
I use the database connection pool is proxool.
I look at the cache strategy: if the database in 1000 that first one from the database that a random read 300 Add in the cache memory, where a cache of expired when questions from the remaining 700 Title take a random test questions to replace expired. JSP pages from the memory cache that the 300 randomly selected from 60 title. This fully consider the response speed of the page, users will not be slow to react to that website and complain or leave. And those who take the test online more speed, it is not affected because there is no expired questions, or to access the database, all the questions removed from the memory cache.
Concrete realization of the following for information.
</ Td> </ tr> <tr> <td height="14" colspan="2">
</ Td> </ tr> </ table>
First, in the category of object ScjpVObj fields in the database and fields questions Table corresponding package com.java3z.data; import java.io.Serializable; import java.util.Date; public class ScjpVObj implements Serializable (int id = 0 ; String content; / / test the contents of String option; / / Item String explain the number of options; / / int test_type Comments answer; / / item types, radio: 0 multiple-choice: a String answer; / / The answer questions int score; / / test scores Date qdate; / / add period of questions public ScjpVObj () () public ScjpVObj (int id, String content, String option, String explain, int test_type, String answer, int score, Date qdate) (id = this.id; this.content = content; this.option = option; this.explain = explain; this.test_type = test_type; this.answer = answer; this.score = score; this.qdate = qdate;) public int getId () (return id;) public String getcontent () (return content;) public void setcontent (String content) = (this.content content;) public String getoption () (return option;) public void setoption (String option) (this.option = option;) public String getExplain () (return explain;) public void setExplain (String explain) = (this.explain explain;) public int getTest_type () (return test_type;) public void setTest_type (int test_type) = (this.test_type test_type;) public String getAnswer () (return answer;) public void setAnswer (String answer) (this.answer = answer;) public int getScore () (return score;) public void setScore (int content) = (this.score score;) public Date getQdate () (return qdate;) public void setQdata (Date qdate) = (this.qdate qdate;)) Second, I cache-cache management system use the revenue JCS. Package com.java3z.data; import java.sql .*; import org.apache.jcs.JCS; import org.apache.jcs.engine.behavior.IElementAttributes;
/ ** Note: Let count in a database that can be used, the questions of ID must be continuous, with a preservation of the array of questions ID, * for (int i = 0; i <count; i + +) * a [i] = i +1; * then the value of elements in an array upset, random array of questions in the database, ID * for (int i = 0; i <count; i + +) (* int j = (int) (Math. random () * count); * int temp = a [i]; * a [i] [j] = a * a [j] = temp;) * * 300 from the former test (a test for the ID [0 ] to a [299]) Add cache. questions id if a cache expired, and that the back from 300 * (ID test for a [300] to a [count-1]) were obtained from ID, replace expiring id and the questions, this would ensure that the cache questions constantly updated. * / Public class ScjpVObjManager (private static ScjpVObjManager instance; private static JCS scjpCache; private static int a [];// preserve all questions in the database ID number, private static int count; / / item in the database the number of private ScjpVObjManager () / / constructor function (Statement stmt = null; Connection conn = null; ResultSet rs = null; ScjpVObj vobj = null; try scjpCache = (JCS.getInstance ( "scjpCache"); conn = DriverManager.getConnection ( "proxool.Access"); stmt = conn.createStatement (); rs = stmt.executeQuery ( "select count (*) from examination3"); rs.next (); rs.getInt count = (1) / / database access to a number of questions = new int [count]; for (int i = 0; i <count; i + +) a [i] = i +1; / / ID database, is a start for (int i = 0; i <count; i + + ) (/ / value of elements in an array of disruption, random array of questions in the database ID, int j = (int) (Math.random () * count); int temp = a [i]; a [i] = a [j]; a [j] = temp;) for (int i = 0; i <300; i + +) (rs = stmt.executeQuery ( "select * from examination3 where id =" + a [i]); while (rs.next ()) (int id = rs.getInt ( "id"); String title = rs.getString ( "content"); String content = rs.getString (the "option"); String explain = rs. getString ( "explain"); int test_type = rs.getInt ( "test_type"); String answer = rs.getString (the "answer"); int score = rs.getInt (the "score"); Date qdate rs.getDate = ( "qdate"); vobj = new ScjpVObj (id, content, option, explain, test_type, answer, score, qdate); scjpCache.put ( "ScjpVObj" + i, vobj); / / Add to test memory cache ))) catch (SQLException e) (System.err.println (e.getMessage ());) catch (Exception e) (System.err.println (e.getMessage ());) finally (try (stmt.close (); conn.close ();) catch (SQLException ex1) (System.out.print (ex1);))) / ** * Singleton access point to the manager * / public static ScjpVObjManager getInstance () (synchronized ( ScjpVObjManager.class) (if (instance == null) (instance = new ScjpVObjManager ();)) return instance;) / ** * Retrieves a ScjpVObj. Default to look in the cache * / public ScjpVObj getScjpVObj (int id) (return getScjpVObj (id, true);) public ScjpVObj getScjpVObj (int i, boolean fromCache) / / id must be 0 <= id <= 299 (if (i <0 | | i> 299) return null; / / simple Treatment ScjpVObj vobj = null; / / First, if requested, and attempt to load from cache if (fromCache) (vobj = (ScjpVObj) scjpCache.get ( "ScjpVObj" + i);) / / If not in the cache memory test ID, for a [i] questions, then exchanged a [i] and a [300], in order to ensure that each admitted that not the same, to ensure that a [300] is random. If (vobj == null) (for (int k = 300; k <305; k + +) (/ / disrupt the five elements in the order of questions in the Q & A at least 305 int j = (int) (300 + ( int) (Math.random () * (count-301))); int temp = a [k] a [k] = a [j]; a [j] = temp;) int t = a [i] ; a [i] = a [300]; a [300] = t; vobj = loadScjpVObj (i); / / from the database from that return vobj);) public ScjpVObj loadScjpVObj (int i) (ScjpVObj vobj = null; Statement stmt = null; Connection conn = null; try (conn = DriverManager.getConnection ( "proxool.Access"); stmt = conn.createStatement (); ResultSet rs = stmt.executeQuery ( "select * from examination3 where id =" + a [i]); while (rs.next ()) (int id = rs.getInt ( "id"); String title = rs.getString ( "content"); String content = rs.getString (the "option") ; String explain = rs.getString ( "explain"); int test_type = rs.getInt ( "test_type"); String answer = rs.getString (the "answer"); int score = rs.getInt (the "score"); Date qdate = rs.getDate ( "qdate"); vobj = new ScjpVObj (id, title, content, explain, test_type, answer, score, qdate); if (vobj! = null) (scjpCache.put ( "ScjpVObj" + i , vobj); / / cache the questions))) catch (SQLException e) (System.err.println (e.getMessage ());) catch (Exception e) (System.err.println (e.getMessage () );) finally (try (stmt.close (); conn.close ();) catch (SQLException ex1) (System.out.print (ex1);)) return vobj;))
3, JSP pages
<% @ Page contentType = "text / html; gb2312 charset ="%>
<% @ Page language = "java"%>
<% @ Page import = "com.java3z.data .*"%>
<%
ScjpVObjManager cache = ScjpVObjManager.getInstance ();
Int a [] = new int [300];
For (int i = 0; i <300; i + +)
A [i] = i;
For (int i = 0; i <300; i + +) (/ / cache memory will be the test for chaos
Int j = (int) (Math.random () * 300);
Int temp = a [i];
A [i] = a [j];
A [j] = temp;
)
For (int count = 0; count <60; count ++){// out that 60
ScjpVObj bv = (ScjpVObj) cache.getScjpVObj (a [count], true);
String content = bv.getContent ();
Out.println (content + "
");
)
%>
Fourth, if inappropriate, to please correct me.
Function TempSave (ElementID) (CommentsPersistDiv.setAttribute ( "CommentContent" document.getElementById (ElementID). Value); CommentsPersistDiv.save ( "CommentXMLStore");) function Restore (ElementID) (CommentsPersistDiv.load ( "CommentXMLStore"); document . getElementById (ElementID). CommentsPersistDiv.getAttribute value = ( "CommentContent");) </ td> </ tr> <tr>
↑ Back
LightningBoard (Thunder Forum) v0.3.7
Abstract: LightningBoard (Thunder Forum) v0.3.7
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> Thunder Forum is J2EE technology development with a robust, scalable strong, and easy to customize, and open Forum software source code.
<table Width="733" border="0"> <tr> <td> </ td> </ tr> </ table>
JSP very good forum, very quickly!
Installation Guide:
1, jdk installed, configured environment variables, such as:
Java_home = d: \ jdk1.5
2, download and extract the Thunder forum will be to extract the entire LightningBoard copied to the directory d: \ LightningBoard
3, Operation Thunderbolt Forum onboard tomcat, as follows
D: \ LightningBoard \ tomcat \ bin \ startup
4, in the browser type: http://localhost:8080/lb/
What is LightningBoard?
LightningBoard is an open source, powerful, easy to use and fully customizable
Bulletin board system written in Java.
Install Guide
1.Set an environment variable JAVA_HOME to the pathname of the directory
Into which you installed the JDK release.
2.Run tomcat (Windows: tomcat \ bin \ startup; Unix: tomcat / bin / startup.sh).
3.Open the url "http://localhost:8080/lb/" in your browser. Enjoy LightningBoard!
================================================== ================================
Xiaobo Liu (nscdl@yahoo.com)
Http://lightningboard.sourceforge.net/ function TempSave (ElementID) (CommentsPersistDiv.setAttribute ( "CommentContent" document.getElementById (ElementID). Value); CommentsPersistDiv.save ( "CommentXMLStore");) function Restore (ElementID) ( CommentsPersistDiv.load ( "CommentXMLStore"); document.getElementById (ElementID). CommentsPersistDiv.getAttribute value = ( "CommentContent");) </ td> </ tr> <tr>
↑ Back
JspSmartUpload upload download components
Abstract: uploading and downloading components jspSmartUpload
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> popular upload download components. There are examples of usage, types of documents and documentation. </ Td> </ tr> <tr>
↑ Back
Mobile background image
Abstract: Mobile background image
</ Td> </ tr> <tr> <td width="389" height="35" valign="top" class="ArticleTeitle">
/ / A moving background images of animation
Import java.awt .*;
Import java.applet.Applet;
Public class Pan extends Applet implements Runnable (
Thread runner;
Image back and fore, workspace;
Graphics offscreen;
String text;
String fontName;
Int fontSize = 24;
Int x1 = 0;
Int x2;
Public void init () (
CreateImage workspace = (size (). Width, size (). Height);
Workspace.getGraphics offscreen = ();
String imageBack = getParameter ( "background");
If (imageBack! = Null)
Back = getImage (getDocumentBase (), imageBack);
String imageFore = getParameter ( "foreground");
If (imageFore! = Null)
Back = getImage (getDocumentBase (), imageFore);
X2 = size (). Width;
Text = getParameter ( "text");
FontName = getParameter ( "font");
If (fontName == null)
FontName = "Arial";
String param = getParameter ( "fontsize");
If (param! = Null)
FontSize = Integer.parseInt ( "0" + param);
)
Public void start () (
If (runner == null) (
Runner = new Thread (this);
Runner.start ();
)
)
Public void stop () (
If (runner! = Null) (
Runner = null;
)
)
Public void run () (
Thread thisThread = Thread.currentThread ();
While (runner == thisThread) (
Repaint ();
Try (Thread.sleep (200);)
Catch (InterruptedException e) ()
X1 = x1-5;
X2 = x2-5;
If (x1 <= (size (). Width * (-1)))
X1 = size (). Width;
If (x2 <= (size (). Width * (-1)))
X2 = size (). Width;
)
)
Public void paint (Graphics g) (
Offscreen.drawImage (back, x1, 0, null);
Offscreen.drawImage (back, x2, 0, null);
If (fore! = Null)
Offscreen.drawImage (fore, 0,0, null);
If (text! = Null) (
Offscreen.setColor (Color.black);
Font f = new Font (fontName, Font.BOLD, fontSize);
FontMetrics fm = g.getFontMetrics ();
Offscreen.setFont (f);
Int xStart size = () .width/2-fm.stringWidth (text) / 2-100;
Int yStart = size (). Height / 2 + fm.getHeight () / 2;
Offscreen.drawString (text, xStart, yStart);
Offscreen.setColor (Color.white);
Offscreen.drawString (text, xStart-2, yStart-2);
)
G.drawImage (workspace, 0, 0, this);
)
Public void update (Graphics g) (
Paint (g);
)
)
</ Td> <td width="295" valign="top" class="ArticleTeitle">
</ Td> </ tr> <tr> <td height="25" colspan="2" valign="top" class="ArticleTeitle">
↑ Back
The document Java HTTP download queue
Abstract: The Java HTTP download documents queue
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width="730" border="0"> <tr> <td> </ td> </ tr> </ table>
Import java.io. *;
Import java.net .*;
Import java.util .*;
/ **
*
Title: Personal development of the API
*
Description: HTTP will be designated to local network resources in the form of document storage
*
Copyright: Copyright (c) 2004
*
Company: NewSky
* @ Author MagicLiao
* @ Version 1.0
* /
(Public class HttpGet
Public final static boolean DEBUG = true; / / debugging
Private static int BUFFER_SIZE = 8096; / / Buffer Size
Private Vector vDownLoad = new Vector ();// URL List
Private Vector vFileList = new Vector ();// after downloading the file name list
/ **
* Construction
* /
Public HttpGet () (
)
/ **
* Removal Download List
* /
Public void resetList () (
VDownLoad.clear ();
VFileList.clear ();
)
/ **
* Download List of
*
* @ Param url String
* @ Param filename String
* /
Public void addItem (String url, String filename) (
VDownLoad.add (url);
VFileList.add (filename);
)
/ **
* Based on the download list of resources
* /
Public void downLoadByList () (
String url = null;
String filename = null;
/ / Resource preservation order on List
For (int i = 0; i <vDownLoad.size (); i + +) (
Url = (String) vDownLoad.get (i);
Filename = (String) vFileList.get (i);
Try (
SaveToFile (url, filename);
)
Catch (IOException err) (
If (DEBUG) (
System.out.println ( "resources [" + url + "] Download failure !!!");
)
)
)
If (DEBUG) (
System.out.println ( "download !!!");
)
)
/ **
* Save the document HTTP resources
*
* @ Param destUrl String
* @ Param fileName String
* @ Throws Exception
* /
Public void saveToFile (String destUrl, String fileName) throws IOException (
FileOutputStream fos = null;
BufferedInputStream bis = null;
HttpURLConnection httpUrl = null;
URL url = null;
Byte [] buf = new byte [BUFFER_SIZE];
Int size = 0;
/ / Links
Url = new URL (destUrl);
HttpUrl = (HttpURLConnection) url.openConnection ();
/ / Connect designated resources
HttpUrl.connect ();
/ / Get input flow network
Bis = new BufferedInputStream (httpUrl.getInputStream ());
/ / Create documents
Fos = new FileOutputStream (fileName);
If (this.DEBUG)
System.out.println ( "access links are [" + + destUrl "] … \ n will be preserved for its paper [" + + "]"); fileName
/ / Save the file
While ((size = bis.read (buf))! = -1)
Fos.write (buf, 0, size);
Fos.close ();
Bis.close ();
HttpUrl.disconnect ();
)
/ **
* Set up a proxy server
*
* @ Param proxy String
* @ Param proxyPort String
* /
Public void setProxyServer (String proxy, String proxyPort) (
/ / Set proxy server
System.getProperties (). Put ( "proxySet", "true");
System.getProperties (). Put ( "proxyHost" proxy);
System.getProperties (). Put ( "proxyPort" proxyPort);
)
/ **
* Set up user name and password authentication
*
* @ Param uid String
* @ Param pwd String
* /
Public void setAuthenticator (String uid, String pwd) (
/ / Authenticator.setDefault (new MyAuthenticator (uid, pwd));
)
/ **
* The main method (for testing)
*
* @ Param argv String []
* /
Public static void main (String argv []) (
HttpGet oInstance = new HttpGet ();
Try (
/ / Increase download list (here users can write their own code to increase the download list), to save downloaded files in the current directory.
OInstance.addItem ( "http://java.dhcn.net:8080/softdownload/dir1/dir5/10.zip ","./ Network Programming 1. Zip");
OInstance.addItem ( "http://java.dhcn.net:8080/softdownload/dir1/dir5/10233.zip ","./ Network Programming 2. Zip");
/ / OInstance.addItem ( "http://www.ebook.com/java/ Network Programming 003. Zip ","./ network programming 3. Zip");
/ / OInstance.addItem ( "http://www.ebook.com/java/ Network Programming 004. Zip ","./ network programming 4. Zip");
/ / OInstance.addItem ( "http://www.ebook.com/java/ Network Programming 005. Zip ","./ network programming 5. Zip");
/ / OInstance.addItem ( "http://www.ebook.com/java/ Network Programming 006. Zip ","./ network programming 6. Zip");
/ / OInstance.addItem ( "http://www.ebook.com/java/ Network Programming 007. Zip ","./ Network Programming 7. Zip");
/ / Start the download
OInstance.downLoadByList ();
)
Catch (Exception err) (
System.out.println (err.getMessage ());
)
)
)
Running Results:
C: \ java> javac HttpGet.java
C: \ java> java HttpGet
Access links are [http://java.dhcn.net:8080/softdownload/dir1/dir5/10.zip] …
For the preservation of their documents [. / Network Programming 1. Zip]
Access links are [http://java.dhcn.net:8080/softdownload/dir1/dir5/10233.zip] …
For the preservation of their documents [. / Network Programming 2. Zip]
Download!
C: \ java>
</ Td> </ tr> <tr>
↑ Back
JDK1.5 Aizhichubenyan
Abstract: JDK1.5 Aizhichubenyan
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width="667" border="0"> <tr> <td width = " 386 ">
Jdk1.5 early experience
—————-
Sun's JDK1.5 finally to the full version, for our Java fans it was a good news! This time, the updated JDK have heard that it is 1995 since the release of the Java Java grammar made the biggest update (previously largely on the expansion of Java class libraries), the introduction of a number of exciting new features.
Oh, gossip less, and now we see JDK1.5 jellen together in the end there is nothing good Dongdong.
1 - pan-sexual programming
Wow, and this is before C + + plated signpost ah, Java can also use the inside. We first look at the past and not the pan-Java:
ArrayList list = new ArrayList ();
List.add (new String ( "Hello !"));
System.out.println ((String) list.get (0));
Is not a bit wordy trouble, it is necessary to turn to turn to be printed out that: "hello!"
Now we look at the new code:
ArrayList
List.add (new String ( "Hello !"));
System.out.println (list.get (0));
Tu, indeed more concise, is not it? Pan-type nature of the introduction of the pool, making our code more concise understandable.
2 - automatic packing / uncrating
This is a very caring of our programmers design, we need to think about before int ArrayList, and other basic data, such as stuffed into trouble when it sets:
ArrayList list = new ArrayList ();
Integer number = new Integer (10); / / first must figure into packaging Lane
List.add (number);
/ / Then want to remove this figure is extremely troublesome to see this Shizi, halo ah!
Int i = ((Integer) list.get (0)). IntValue ();
Well now, the same code in JDK1.5:
ArrayList
List.add (10);
Int i = list.get (0);
It is very convenient ah!
3 - Enhanced Structural cycle
Oh, and this is a very powerful Dongdonga can not be underestimated. The former for (;;) cycle, I think we are familiar with, I do not cite examples, Let's see now on this new cycle of it:
Int data [] = (1, 2, 3, 4, 5);
For (int j: data)
System.out.println (j);
Oh, relatively powerful it:) we do not have to concern about the size of the array, as long as a given type and the name of the array, the system will automatically give us the cycle.
4 - enumerated type
This is a C / C + + programmers are more familiar with the concept, but there's no prior Java, is finally introduced, usage, and C / C + + similar:
(Enum Color
BLACK,
WHITE,
GREEN
);
Color c = Color.GREEN;
5 - static import
Remember that the use of mathematical functions, we wrote the code?
Double result = Math.sqrt (100);
Math in front of the prefix that is not aä¸çˆ½, if the C language and directly to the use of sqrt () good. OK, now we can - to use static import:
Import static java.lang.Math .*;
Double result = sqrt (100);
This code is not that reminds us of the good times C:) said here, I have remembered that from the C language inside cordial printf () up, and through it we can control the output format. Now Java can be used inside:
6 - formatted output
System.out.printf ( "This is a test:% 4.2f \ n", 123.123);
This will print out: This is a test: 123.12
Ah good cordial Grammar:)
7 - read data from terminals
Java's first contact, I can not how Java C in the terminal as easy as reading the data. From the terminal before I read an integer is so Lane:
Try (
BufferedReader reader = new BufferedReader (new
InputStreamReader (System.in));
Int i = Integer.parseInt (reader.readLine ());
) Catch (IOException e) ()
Shizi long, relatively depressed syntax.
Now well, the introduction of a Java inside Scanner (), can be easily read data from the terminal:
Scanner read = new Scanner (System.in);
Int i = read.nextInt ();
The syntax seems to be more than that?
8 - Number of uncertain parameters
This feature in C + + there is a popular grammar, JDK1.5 there is now also available:
Void argtest (Object … args) (
For (int i = 0; i <args.length; i + +)
System.out.println (i);
)
Then we can call this function:
Argtest (1);
Argtest (1, 2, 4, 5, 6);
Comparison of magic?
OK, JDK1.5 inside can describe the new features is really too much, I have been deeply attracted it.
Hope that we can understand some of this small article JDK1.5 the new features, what next? Go download new JDK ah! Oh, to experience JDK1.5 quickly to bring us a new feeling!
↑ Back
Jdk1.5 metadata in a case
Abstract: jdk1.5 metadata in a case
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="265" height="265" align="center" valign="top"> </ td> <td width="57%" valign="top">
Metadata, in the java also called Notes, Notes. Microsoft's. Net from the outset there is a design function, but it is the terminology attributes.
This is a powerful, programmers If you want to earn money, a good study it, because
J2ee development in the future, the extensive use of it, including ejb statement, the IOC injection.
IBM Web site has detailed articles on it, very good article.
Http://www-900.ibm.com/developerWorks/cn/java/j-annotate1/
Http://www-900.ibm.com/developerworks/cn/java/j-annotate2.shtml
</ Td> </ tr> <tr> <td height="44" colspan="2">
Notes of a new type, the type specified by the author of a famous book and his email.
- Package com.kuaff.jdk5;
- Import java.lang.annotation .*;
- @ Retention (RetentionPolicy.RUNTIME)
- @ Target (ElementType.METHOD)
- Public @ interface BookAuthor
- (
- String name ();
- String email ();
- )
Below the use of the Notes, together with our approach Notes:
- Package com.kuaff.jdk5;
- Import java.lang.annotation.Annotation;
- Public class MetadataShow
- (
- @ BookAuthor (name = "Cao Xueqin," email = "caoxueqin@hongloumeng.books")
- Public void introHongLouMeng ()
- (
- System. Out.println ( "This is a good book ah");
- )
- Public static void main (String [] args)
- (
- MetadataShow metadata = new MetadataShow ();
- Try
- (
- Annotation [] = metadata.getClass annotation (). GetMethod ( "introHongLouMeng"). GetAnnotations ();
- For (Annotation a: annotation)
- (
- System. Out.printf ( "Author:% n% s", ((BookAuthor) a). Name ());
- System. Out.printf ( "His e-mail (which may have been cancelled):% s% n", ((BookAuthor) a). Email ());
- )
- )
- Catch (SecurityException e)
- (
- E.printStackTrace ();
- )
- Catch (NoSuchMethodException e)
- (
- E.printStackTrace ();
- )
- )
- )
Please note that in order to run the program can read these notes in the Notes of the needs of the time of the statement
@ Retention (RetentionPolicy.RUNTIME)
@ Target (ElementType.METHOD) / / also possible, other types, such as those for the Notes statement
This is the Notes of the Notes.
Compiler operation of these two documents:
C: \ java> java MetadataShow
Author: Cao Xueqin
His e-mail (which may have been cancelled): caoxueqin@hongloumeng.books
C: \ java>
</ Td> </ tr> </ table>
Function TempSave (ElementID) (CommentsPersistDiv.setAttribute ( "CommentContent" document.getElementById (ElementID). Value); CommentsPersistDiv.save ( "CommentXMLStore");) function Restore (ElementID) (CommentsPersistDiv.load ( "CommentXMLStore"); document . getElementById (ElementID). CommentsPersistDiv.getAttribute value = ( "CommentContent");) </ td> </ tr> <tr>
↑ Back
SCJP certification examinations Guide
Abstract: SCJP certification examinations Guide
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td height="86" align="left" valign="top"> </ td> </ tr> </ table>
SCJP certification examinations Guide (Chinese), in PDF format.
</ Td> </ tr> <tr>
↑ Back
Simple game Tuixiangzi
Abstract: The simple game Tuixiangzi
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="511" height="86" align="left" valign="top"> previously always longing to write games, but never write that the game is also a very difficult process.
The rewriting of Tuixiangzi, not the functions. Just realized: the right audience and the mobile boxes, including the detection of the wall when all the boxes arrive at their destination in time, it suggested that "Congratulations clearance" Players can use the keyboard "below" to the progress of control direction is the idea of the entire code: the game interface as a two-dimensional array, and then use a Boolean array boolean a [] [] to fill it. The players, true to the wall and boxes, destined for false. All elements of the interface are the target of a Node class, when a [] [Node.x Node.y] is true, on behalf of the players encountered box or wall, and then gave the achievement of the relevant algorithms..
Below is the code:
Import javax.swing .*;
Import java.awt .*;
Import java.awt.event .*;
Import java.util .*;
Import java.awt.geom .*;
</ Td> <td width="173" valign="top"> </ td> </ tr> </ table>
Public class PushBox (public static void main (String args []) (GameFrame frame = new GameFrame (); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); frame.show (); JOptionPane.showMessageDialog (null, "red box on behalf of play home \ n purple box to the blue box, pushed through \ n keys control the direction \ n not to return to the previous step ");)) class GameFrame extends JFrame (static int num; public GameFrame () (setSize (400, 400) ; Container c = getContentPane (); GamePanel panel1 = new GamePanel (); c.add (panel1);)) class GamePanel_2 extends JPanel (public GamePanel_2 () (this.setBackground (Color.BLACK);)) class GamePanel extends JPanel implements KeyListener (int width = 400; int height = 400; Box b; Node man; Node box; Node [] target; int d = 1 / / moving step int sideX = 25; int sideY = 25; GameFrame frame ; ArrayList wallList; / / initialization interface elements public GamePanel () (this.setBackground (Color.WHITE), b = new Box (this, width / sideX, width / sideY); this.man = b.man; this . box = b.box; this.target = b.target; this.wallList = b.wallList; this.setFocusable (true); this.addKeyListener (this);) public void paintComponent (Graphics g) (super.paintComponent ( g); Graphics2D g2 = (Graphics2D) g / / background rendering the game, players and boxes. g2.setColor (Color.white); g2.fillRect (0, 0, width, height); g2.setColor (Color. RED); draw (g2, man); g2.setColor (Color.MAGENTA); draw (g2, box); draw (g2, b.box1); draw (g2, b.box2); draw (g2, b. box3); / / Drawing walls g2.setColor (Color.darkGray) for (int i = 0; i <wallList.size (); i + +) (Node n = (Node) wallList.get (i); draw (g2 , n);) / / mapping destination. g2.setColor (Color.blue) for (int i = 0; i <target.length; i + +) (g2.drawRect (target [i]. x * sideX, target [i]. y * sideY, sideX - 1, sideY - 1); Ellipse2D e = new Ellipse2D.Double (target [i]. x * sideX, target [i]. y * sideY, sideX - 1, sideY - 1 ); g2.draw (e);)) public void keyPressed (KeyEvent e) (int keycode = e.getKeyCode (); if (keycode == KeyEvent.VK_UP) (Box.direction = 1; / / set the orientation for first Mobile b.move again (0,-d);) else if (keycode == KeyEvent.VK_RIGHT) (Box.direction = 2; b.move (d 0);) else if (keycode == KeyEvent.VK_DOWN) (Box.direction = 3; b.move (0, d);) else if (keycode == KeyEvent.VK_LEFT) (Box.direction = 4; b.move (-d, 0);)) public void keyReleased ( KeyEvent e) () public void keyTyped (KeyEvent e) () public void draw (Graphics2D g, Node n) (g.fillRect (nx * sideX, ny * sideY, sideX - 1, sideY - 1);)) class Node (int x; int y; public Node (int x, int y) (this.x = x; this.y = y;)) (boolean end class Box = false; int maxX; int maxY; boolean [] [] a; / / regional entire game is a Boolean type of two-dimensional array Node man; Node [] target; / / storage destination Node box; Node box1; Node box2; Node box3; Node [] wall; / / storage wall Node [] b; / / b array storage boxes. GamePanel panel; / / When a push to the purpose of boxes, storage destination node list. ArrayList list = new ArrayList (); / / storage wall. ArrayList wallList = new ArrayList (); public static int left = 4; public static int up = 1; public static int right = 2; public static int down = 3; public static int direction = 0; / / BOX constructor, using Boolean Two-dimensional arrays filled games, while the definition players, boxes and destination. Public Box (GamePanel p, int maxX, int maxY) (panel = p; this.maxX = maxX; this.maxY = maxY; a new boolean = [] [maxX maxY]; for (int i = 0; i <maxX ; i + +) (for (int j = 0; j <maxY; j + +) (a [i] [j] = false;)) / / definition box, the initial audience and destination locations int x = 5; int y = 8; man = new Node (x, y); a [x] [y] = true; / / definition of the game's box location, and home to TRUE; b = new Node [4] = new box Node (10, 9); a [10] [9] = true; b [0] = box; box1 = new Node (6, 7); a [6] [7] = true; b [1] = box1 ; box2 = new Node (11, 8); a [11] [8] = true; b [2] = box2; box3 = new Node (8, 8); a [8] [8] = true; b [ 3] = box3; / / definition of the wall and destination. createWall (); target = new Node [4]; target [0] = new Node (7, 9); target [3] = new Node (6, 9) ; target [1] = new Node (7, 10); target [2] = new Node (6, 10);) public void move (int d1, int d2) (a [] [man.y man.x] = false; man.x + = d1; man.y + = d2; / / If the player encountered wall, it can not move forward, otherwise, promote boxes. if (a [man.y man.x] []) ( if (isOutofwall ()) (moveDisable (man, d1, d2);) else (for (int i = 0; i <b.length; i + +) (if (man.x == b [i]. x & & man . y = b [i]. y) (b [i]. d1 = x +; b [i]. d2 = y + / / use of a box IF judge whether the overlap, if overlapping, it can not go forward; if (a [b [i]. x] [b [i]. y]) (moveDisable (man, d1, d2); moveDisable (b [i], d1, d2);) else (/ / it must boxes true for the location of home, or moving a box after no longer mobile. a [b [i]. x] [b [i]. y] = true; / / If all pushing boxes in place, the end of the game / / In this procedures, methods to isArrive home in a box for the true future use. isArrive (b [i]);))))) panel.repaint (); if (end) (JOptionPane.showMessageDialog (null, "over"); System . exit (0);)) / / generate maps public void createWall () (for (int i = 5; i <12; i + +) (Node walls = new Node (i, 5); wallList.add (walls)
for (int i = 11; i <14; i + +) (Node walls = new Node (i, 6); wallList.add (walls);) wallList.add (new Node (13, 7)); wallList. add (new Node (13, 8)); wallList.add (new Node (13, 9)); wallList.add (new Node (12, 9)); wallList.add (new Node (12, 10)); for (int i = 12; i> 4; i -) (Node walls = new Node (i, 11); wallList.add (walls);) wallList.add (new Node (5, 10)); wallList. add (new Node (4, 10)); wallList.add (new Node (4, 9)); wallList.add (new Node (4, 8)); wallList.add (new Node (4, 8)); wallList.add (new Node (4, 7)); wallList.add (new Node (5, 7)); wallList.add (new Node (5, 6)); wallList.add (new Node (7, 7) ); wallList.add (new Node (8, 7)); wallList.add (new Node (9, 7)); wallList.add (new Node (8, 9)); wallList.add (new Node (8, 10)) / / will be home for the object of the walls true for (int i = 0; i <wallList.size (); i + +) (Node n = (Node) wallList.get (i) a [ny] [nx ] = true;)) / / hit the wall, the players can not advance public void moveDisable (Node n, int d1, int d2) (switch (direction) (case 4: nx -= d1; break; case 1: ny -= d2; break; case 2: nx -= d1; break; case 3: ny -= d2; break;)) / / determine whether the players across the border public boolean isOutofwall () (for (int i = 0; i <wallList.size (); i + +) (Node n = (Node) wallList.get (i) if (nx man.x == == & man.y ny) (return true;)) return false;) / / If all the boxes in place, then the game to an end public void isArrive (Node n) (for (int i = 0; i <target.length; i + +) (if ((target [i]. x == nx & target [ i]. y == ny)) (list.add (target [i]);) else if (target [i]. x == man.x & target [i]. y == man.y) (list . remove (target [i]);)) if (list.size () == target.length) (end = true;)))
</ Td> </ tr> <tr>
↑ Back