import java.awt.*;
創(chuàng)新互聯(lián)公司專注于化隆網站建設服務及定制,我們擁有豐富的企業(yè)做網站經驗。 熱誠為您提供化隆營銷型網站建設,化隆網站制作、化隆網頁設計、化隆網站官網定制、成都小程序開發(fā)服務,打造化隆網絡公司原創(chuàng)品牌,更為您提供化隆網站排名全網營銷落地服務。
import java.applet.*;
import java.awt.event.*;
import java.awt.image.*;
import java.awt.geom.*;
import java.util.*;
class Car{
Image img;
int x, y;
Dimension dim;
Car(Image img){
this.img=img;
}
Car(Image img, int x, int y){
this.img=img; this.x=x; this.y=y;
}
Car(Image img, int x, int y, Dimension dim){
this(img, x, y);
this.dim=dim;
}
void draw(Graphics g, ImageObserver observer){
g.drawImage(img, x, y, observer);
}
int getX(){ return x;}
int getY(){ return y;}
void setX(int x){this.x=x;}
void setY(int y){this.y=y;}
void setLocation(int x, int y){
this.x=x; this.y=y;
}
int getWidth(){ return img.getWidth(null);}
int getHeight(){ return img.getHeight(null);}
Rectangle2D getRectangle(){
return new Rectangle2D.Float(x, y, getWidth(), getHeight());
}
void move(int dx, int dy){
x+=dx;
y+=dy;
if(dim!=null){
if(x0)x=0;
if(x+getWidth()dim.getWidth())
x=(int)dim.getWidth()-getWidth();
}
}
boolean intersects(Car car){
return getRectangle().intersects(car.getRectangle());
}
boolean intersects(int x, int y){
return getRectangle().intersects(x, y, getWidth(), getHeight());
}
}
public class CarRace extends Applet implements KeyListener, Runnable{
Image buff;
Canvas screen;
Graphics2D gs, gb;
Car redCar;
Car[] enemy=new Car[20];
Button bStart;
Thread game;
boolean loop=true;
Dimension dim=new Dimension(200, 300);
int road;
Random rnd=new Random();
public void init(){
prepareResource();
setBackground(Color.blue);
initScreen();
add(screen);
bStart=new Button("霸烙 矯累");
add(bStart);
bStart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
screen.requestFocus();
if(!game.isAlive())
game.start();
}
});
}
void prepareResource(){
Image imgRed=getImage(getCodeBase(),"images/red_car.gif");
Image imgBlue=getImage(getCodeBase(),"images/blue_car.gif");
Image imgGreen=getImage(getCodeBase(),"images/green_car.gif");
MediaTracker mt=new MediaTracker(this);
try{
mt.addImage(imgRed, 0);
mt.addImage(imgBlue, 1);
mt.addImage(imgGreen, 2);
mt.waitForAll();
}catch(Exception e){}
buff=createImage((int)dim.getWidth(), (int)dim.getHeight());
gb=(Graphics2D)buff.getGraphics();
redCar=new Car(imgRed, 80,250, dim);
for(int i=0;i10;i++){
enemy[i]=new Car(imgBlue, 0, 0);
}
for(int i=10;ienemy.length;i++){
enemy[i]=new Car(imgGreen, 0, 0);
}
for(int i=0;ienemy.length;i++){
setEnemy(i);
}
game=new Thread(this);
}
public void stop(){
loop=false;
}
public void run(){
while(loop){
drawScreen();
try{ Thread.sleep(50);}catch(Exception e){}
}
}
void initScreen(){
screen=new Canvas(){
public void paint(Graphics g){
if(gs==null){
gs=(Graphics2D)screen.getGraphics();
}
drawScreen();
}
};
screen.setSize(dim);
screen.addKeyListener(this);
}
void setEnemy(int en){
int x, y;
next:while(true){
x=rnd.nextInt((int)dim.getWidth()-enemy[en].getWidth());
y=-rnd.nextInt(5000)-200;
for(int j=0;jenemy.length;j++){
if(j!=en enemy[j].intersects(x, y))continue next;
}
enemy[en].setLocation(x, y);
break;
}
}
void check(Car en){
if(redCar.intersects(en)){
if(redCar.getX()en.getX()){
en.move(-20, 0);
redCar.move(20, 0);
}
else{
en.move(20,0);
redCar.move(-20, 0);
}
}
}
synchronized void drawScreen(){
gb.clearRect(0, 0, (int)dim.getWidth(), (int)dim.getHeight());
gb.setPaint(new Color(100, 100, 100));
gb.fillRect(0, 0, (int)dim.getWidth(), (int)dim.getHeight());
drawRoad();
for(int i=0;ienemy.length;i++){
enemy[i].move(0, 15);
enemy[i].draw(gb, screen);
if(enemy[i].getY()dim.getHeight())
setEnemy(i);
check(enemy[i]);
}
redCar.draw(gb, screen);
gs.drawImage(buff, 0,0, screen);
}
void drawRoad(){
road+=80;
gb.setPaint(Color.yellow);
gb.fillRect((int)dim.getWidth()/2, road,10,150);
if(road=dim.getHeight())road=-150;
}
public void keyPressed(KeyEvent ke){
if(ke.getKeyCode()==KeyEvent.VK_LEFT){
redCar.move(-10,0);
}
else if(ke.getKeyCode()==KeyEvent.VK_RIGHT){
redCar.move(10,0);
}
}
public void keyReleased(KeyEvent ke){}
public void keyTyped(KeyEvent ke){}
}
這個是一個典型的Applet,文件名應該是CarRace.java,需要圖片作為車子等等,本人也是別人給的,但是還要個.html文件來運行它,代碼為:
Applet code="CarRace.class" width=250 height=350
/Applet
請樓主采納
//都是從新手過來的,以下代碼供參考
//1.
public?class?BankAccount?{
private?static?String?acctnum;
private?static?double?money;
private?static?void?showAcct()?{
System.out.println("賬號為:?"?+?acctnum);
}
private?static?void?showMoney()?{
System.out.println("余額為:?"?+?money);
}
public?BankAccount(String?acc,?double?m)?{
this.acctnum?=?acc;
this.money?=?m;
}
public?static?void?main(String[]?args)?{
BankAccount?ba?=?new?BankAccount("626600018888",?5000.00);
ba.showAcct();
ba.showMoney();
}
}
//2.
public?class?Triangle?{
private?static?float?a;
private?static?float?b;
private?static?float?c;
public?Triangle(float?a,?float?b,?float?c)?{
this.a?=?a;
this.b?=?b;
this.c?=?c;
}
public?static?boolean?judgeTriangle(float?a,?float?b,?float?c)?{
if?((a??Math.abs(b?-?c)??a??b?+?c)
?(b??Math.abs(a?-?c)??b??a?+?c)
?(c??Math.abs(a?-?b)??c??a?+?b))
return?true;
else
return?false;
}
public?float?getCircumference()?{
return?this.a?+?this.b?+?this.c;
}
}
//3.
public?class?TestTriangle?{
public?static?void?main(String[]?args)?{
Triangle?t?=?new?Triangle(5.3f,7.8f,9.3f);
if(t.judgeTriangle(5.3f,7.8f,9.3f)){
System.out.print("能夠成三角形,周長為:?");
System.out.printf("%9.2f",t.getCircumference());}
else
System.out.println("不能構成三角形");
}
}
表1. CheckerDrag.java
// CheckerDrag.javaimport java.awt.*;import java.awt.event.*;public class CheckerDrag extends java.applet.Applet{ // Dimension of checkerboard square. // 棋盤上每個小方格的尺寸 final static int SQUAREDIM = 40; // Dimension of checkerboard -- includes black outline. // 棋盤的尺寸 – 包括黑色的輪廓線 final static int BOARDDIM = 8 * SQUAREDIM + 2; // Dimension of checker -- 3/4 the dimension of a square. // 棋子的尺寸 – 方格尺寸的3/4 final static int CHECKERDIM = 3 * SQUAREDIM / 4; // Square colors are dark green or white. // 方格的顏色為深綠色或者白色 final static Color darkGreen = new Color (0, 128, 0); // Dragging flag -- set to true when user presses mouse button over checker // and cleared to false when user releases mouse button. // 拖動標記 --當用戶在棋子上按下鼠標按鍵時設為true, // 釋放鼠標按鍵時設為false boolean inDrag = false; // Left coordinate of checkerboard's upper-left corner. // 棋盤左上角的左方向坐標 int boardx; // Top coordinate of checkerboard's upper-left corner. //棋盤左上角的上方向坐標 int boardy; // Left coordinate of checker rectangle origin (upper-left corner). // 棋子矩形原點(左上角)的左方向坐標 int ox; // Top coordinate of checker rectangle origin (upper-left corner). // 棋子矩形原點(左上角)的上方向坐標 int oy; // Left displacement between mouse coordinates at time of press and checker // rectangle origin. // 在按鍵時的鼠標坐標與棋子矩形原點之間的左方向位移 int relx; // Top displacement between mouse coordinates at time of press and checker // rectangle origin. // 在按鍵時的鼠標坐標與棋子矩形原點之間的上方向位移 int rely; // Width of applet drawing area. // applet繪圖區(qū)域的寬度 int width; // Height of applet drawing area. // applet繪圖區(qū)域的高度 int height; // Image buffer. // 圖像緩沖 Image imBuffer; // Graphics context associated with image buffer. // 圖像緩沖相關聯(lián)的圖形背景 Graphics imG; public void init () { // Obtain the size of the applet's drawing area. // 獲取applet繪圖區(qū)域的尺寸 width = getSize ().width; height = getSize ().height; // Create image buffer. // 創(chuàng)建圖像緩沖 imBuffer = createImage (width, height); // Retrieve graphics context associated with image buffer. // 取出圖像緩沖相關聯(lián)的圖形背景 imG = imBuffer.getGraphics (); // Initialize checkerboard's origin, so that board is centered. // 初始化棋盤的原點,使棋盤在屏幕上居中 boardx = (width - BOARDDIM) / 2 + 1; boardy = (height - BOARDDIM) / 2 + 1; // Initialize checker's rectangle's starting origin so that checker is // centered in the square located in the top row and second column from // the left. // 初始化棋子矩形的起始原點,使得棋子在第一行左數(shù)第二列的方格里居中 ox = boardx + SQUAREDIM + (SQUAREDIM - CHECKERDIM) / 2 + 1; oy = boardy + (SQUAREDIM - CHECKERDIM) / 2 + 1; // Attach a mouse listener to the applet. That listener listens for // mouse-button press and mouse-button release events. // 向applet添加一個用來監(jiān)聽鼠標按鍵的按下和釋放事件的鼠標監(jiān)聽器 addMouseListener (new MouseAdapter () { public void mousePressed (MouseEvent e) { // Obtain mouse coordinates at time of press. // 獲取按鍵時的鼠標坐標 int x = e.getX (); int y = e.getY (); // If mouse is over draggable checker at time // of press (i.e., contains (x, y) returns // true), save distance between current mouse // coordinates and draggable checker origin // (which will always be positive) and set drag // flag to true (to indicate drag in progress). // 在按鍵時如果鼠標位于可拖動的棋子上方 // (也就是contains (x, y)返回true),則保存當前 // 鼠標坐標與棋子的原點之間的距離(始終為正值)并且 // 將拖動標志設為true(用來表明正處在拖動過程中) if (contains (x, y)) { relx = x - ox; rely = y - oy; inDrag = true; } } boolean contains (int x, int y) { // Calculate center of draggable checker. // 計算棋子的中心位置 int cox = ox + CHECKERDIM / 2; int coy = oy + CHECKERDIM / 2; // Return true if (x, y) locates with bounds // of draggable checker. CHECKERDIM / 2 is the // radius. // 如果(x, y)仍處于棋子范圍內則返回true // CHECKERDIM / 2為半徑 return (cox - x) * (cox - x) + (coy - y) * (coy - y) CHECKERDIM / 2 * CHECKERDIM / 2; } public void mouseReleased (MouseEvent e) { // When mouse is released, clear inDrag (to // indicate no drag in progress) if inDrag is // already set. // 當鼠標按鍵被釋放時,如果inDrag已經為true, // 則將其置為false(用來表明不在拖動過程中) if (inDrag) inDrag = false; } }); // Attach a mouse motion listener to the applet. That listener listens // for mouse drag events. //向applet添加一個用來監(jiān)聽鼠標拖動事件的鼠標運動監(jiān)聽器 addMouseMotionListener (new MouseMotionAdapter () { public void mouseDragged (MouseEvent e) { if (inDrag) { // Calculate draggable checker's new // origin (the upper-left corner of // the checker rectangle). // 計算棋子新的原點(棋子矩形的左上角) int tmpox = e.getX () - relx; int tmpoy = e.getY () - rely; // If the checker is not being moved // (at least partly) off board, // assign the previously calculated // origin (tmpox, tmpoy) as the // permanent origin (ox, oy), and // redraw the display area (with the // draggable checker at the new // coordinates). // 如果棋子(至少是棋子的一部分)沒有被 // 移出棋盤,則將之前計算的原點 // (tmpox, tmpoy)賦值給永久性的原點(ox, oy), // 并且刷新顯示區(qū)域(此時的棋子已經位于新坐標上) if (tmpox boardx tmpoy boardy tmpox + CHECKERDIM boardx + BOARDDIM tmpoy + CHECKERDIM boardy + BOARDDIM) { ox = tmpox; oy = tmpoy; repaint (); } } } }); } public void paint (Graphics g) { // Paint the checkerboard over which the checker will be dragged. // 在棋子將要被拖動的位置上繪制棋盤 paintCheckerBoard (imG, boardx, boardy); // Paint the checker that will be dragged. // 繪制即將被拖動的棋子 paintChecker (imG, ox, oy); // Draw contents of image buffer. // 繪制圖像緩沖的內容 g.drawImage (imBuffer, 0, 0, this); } void paintChecker (Graphics g, int x, int y) { // Set checker shadow color. // 設置棋子陰影的顏色 g.setColor (Color.black); // Paint checker shadow. // 繪制棋子的陰影 g.fillOval (x, y, CHECKERDIM, CHECKERDIM); // Set checker color. // 設置棋子顏色 g.setColor (Color.red); // Paint checker. // 繪制棋子 g.fillOval (x, y, CHECKERDIM - CHECKERDIM / 13, CHECKERDIM - CHECKERDIM / 13); } void paintCheckerBoard (Graphics g, int x, int y) { // Paint checkerboard outline. // 繪制棋盤輪廓線 g.setColor (Color.black); g.drawRect (x, y, 8 * SQUAREDIM + 1, 8 * SQUAREDIM + 1); // Paint checkerboard. // 繪制棋盤 for (int row = 0; row 8; row++) { g.setColor (((row 1) != 0) ? darkGreen : Color.white); for (int col = 0; col 8; col++) { g.fillRect (x + 1 + col * SQUAREDIM, y + 1 + row * SQUAREDIM, SQUAREDIM, SQUAREDIM); g.setColor ((g.getColor () == darkGreen) ? Color.white : darkGreen); } } } // The AWT invokes the update() method in response to the repaint() method // calls that are made as a checker is dragged. The default implementation // of this method, which is inherited from the Container class, clears the // applet's drawing area to the background color prior to calling paint(). // This clearing followed by drawing causes flicker. CheckerDrag overrides // update() to prevent the background from being cleared, which eliminates // the flicker. // AWT調用了update()方法來響應拖動棋子時所調用的repaint()方法。該方法從 // Container類繼承的默認實現(xiàn)會在調用paint()之前,將applet的繪圖區(qū)域清除 // 為背景色,這種繪制之后的清除就導致了閃爍。CheckerDrag重寫了update()來 // 防止背景被清除,從而消除了閃爍。 public void update (Graphics g) { paint (g); }}
【ClientSocketDemo.java 客戶端Java源代碼】
import java點虐 .*;
import java.io.*;
public class ClientSocketDemo
{
//聲明客戶端Socket對象socket
Socket socket = null;
//聲明客戶器端數(shù)據輸入輸出流
DataInputStream in;
DataOutputStream out;
//聲明字符串數(shù)組對象response,用于存儲從服務器接收到的信息
String response[];
//執(zhí)行過程中,沒有參數(shù)時的構造方法,本地服務器在本地,取默認端口10745
public ClientSocketDemo()
{
try
{
//創(chuàng)建客戶端socket,服務器地址取本地,端口號為10745
socket = new Socket("localhost",10745);
//創(chuàng)建客戶端數(shù)據輸入輸出流,用于對服務器端發(fā)送或接收數(shù)據
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
//獲取客戶端地址及端口號
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
//向服務器發(fā)送數(shù)據
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
//從服務器接收數(shù)據
response = new String[3];
for (int i = 0; i response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
//執(zhí)行過程中,有一個參數(shù)時的構造方法,參數(shù)指定服務器地址,取默認端口10745
public ClientSocketDemo(String hostname)
{
try
{
//創(chuàng)建客戶端socket,hostname參數(shù)指定服務器地址,端口號為10745
socket = new Socket(hostname,10745);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
response = new String[3];
for (int i = 0; i response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
//執(zhí)行過程中,有兩個個參數(shù)時的構造方法,第一個參數(shù)hostname指定服務器地址
//第一個參數(shù)serverPort指定服務器端口號
public ClientSocketDemo(String hostname,String serverPort)
{
try
{
socket = new Socket(hostname,Integer.parseInt(serverPort));
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);
response = new String[3];
for (int i = 0; i response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}
public static void main(String[] args)
{
String comd[] = args;
if(comd.length == 0)
{
System.out.println("Use localhost(127.0.0.1) and default port");
ClientSocketDemo demo = new ClientSocketDemo();
}
else if(comd.length == 1)
{
System.out.println("Use default port");
ClientSocketDemo demo = new ClientSocketDemo(args[0]);
}
else if(comd.length == 2)
{
System.out.println("Hostname and port are named by user");
ClientSocketDemo demo = new ClientSocketDemo(args[0],args[1]);
}
else System.out.println("ERROR");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
【ServerSocketDemo.java 服務器端Java源代碼】
import java點虐 .*;
import java.io.*;
public class ServerSocketDemo
{
//聲明ServerSocket類對象
ServerSocket serverSocket;
//聲明并初始化服務器端監(jiān)聽端口號常量
public static final int PORT = 10745;
//聲明服務器端數(shù)據輸入輸出流
DataInputStream in;
DataOutputStream out;
//聲明InetAddress類對象ip,用于獲取服務器地址及端口號等信息
InetAddress ip = null;
//聲明字符串數(shù)組對象request,用于存儲從客戶端發(fā)送來的信息
String request[];
public ServerSocketDemo()
{
request = new String[3]; //初始化字符串數(shù)組
try
{
//獲取本地服務器地址信息
ip = InetAddress.getLocalHost();
//以PORT為服務端口號,創(chuàng)建serverSocket對象以監(jiān)聽該端口上的連接
serverSocket = new ServerSocket(PORT);
//創(chuàng)建Socket類的對象socket,用于保存連接到服務器的客戶端socket對象
Socket socket = serverSocket.accept();
System.out.println("This is server:"+String.valueOf(ip)+PORT);
//創(chuàng)建服務器端數(shù)據輸入輸出流,用于對客戶端接收或發(fā)送數(shù)據
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
//接收客戶端發(fā)送來的數(shù)據信息,并顯示
request[0] = in.readUTF();
request[1] = in.readUTF();
request[2] = in.readUTF();
System.out.println("Received messages form client is:");
System.out.println(request[0]);
System.out.println(request[1]);
System.out.println(request[2]);
//向客戶端發(fā)送數(shù)據
out.writeUTF("Hello client!");
out.writeUTF("Your ip is:"+request[1]);
out.writeUTF("Your port is:"+request[2]);
}
catch(IOException e){e.printStackTrace();}
}
public static void main(String[] args)
{
ServerSocketDemo demo = new ServerSocketDemo();
}
}