显示窗体
package package1;
import javax.swing.JFrame;
public class SimpleFrame extends JFrame {
public SimpleFrame() {
//设置框架大小
setSize(WIDTH, HEIGHT);
}
public static final int WIDTH = 300;
public static final int HEIGHT = 200;
}
package package1;
import javax.swing.*;
public class StudyFrame {
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成的方法存根
SimpleFrame frame = new SimpleFrame();
//设置用户关闭框架时的响应动作
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//显示该框架
frame.setVisible(true);
}
}
为窗体添加 其他控件:
package package1;
import javax.swing.*;
import javax.swing.JButton;
public class StudyFrame extends JFrame {
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成的方法存根
SimpleFrame frame = new SimpleFrame();
//设置用户关闭框架时的响应动作
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//显示该框架
frame.setLayout(null); //设置布局管理器
JButton button1=new JButton("我的按钮1 ");
button1.setSize(110, 130);
button1.setLocation(50, 50);
frame.add(button1);
JButton button2=new JButton("我的按钮2 ");
button2.setSize(120, 130);
button2.setLocation(400, 150);
frame.add(button2);
frame.setVisible(true);
}
}
窗体的布局:
package package1;
import javax.swing.*;
import javax.swing.JButton;
import java.awt.BorderLayout;
import javax.swing.JFrame;
public class StudyFrame extends JFrame {
private JButton north=new JButton("北");
private JButton south=new JButton("男");
private JButton east=new JButton("东");
private JButton west=new JButton("西");
private JButton center=new JButton("中");
public StudyFrame(){
setSize(300,300); //设置窗体的大小
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置窗体默认关闭事件
setLayout(new BorderLayout()); //设置布局管理器BorderLayout
add(north,BorderLayout.NORTH);
add(south,BorderLayout.SOUTH);
add(east,BorderLayout.EAST);
add(west,BorderLayout.WEST);
add(center,BorderLayout.CENTER);
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
StudyFrame frame=new StudyFrame();
frame.setVisible(true); //显示窗体
}
}
受到了房间啊说了算发动机
组件对象.addXXXListener(new事件监听器(){
//定义匿名内部类
public void 监听器接口说明的方法1(){
……
}
public void 监听器接口说明的方法n(){
……
}
}
);
//结束匿
实验代码:
package package1;
import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class StudyFrame extends JFrame {
private JButton button=new JButton("我的按钮");
public StudyFrame(){
setSize(300,300);
setLocation(400,400);
setTitle("ButtonFrame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
JOptionPane.showMessageDialog(null, "我单击了按钮");
}
});
add(button);
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
StudyFrame frame=new StudyFrame();
frame.setVisible(true);
}
}
===============================
Java applet
代码:
package package1;
import java.applet.Applet;
import java.awt.*;
public class StudyFrame extends Applet {
public void paint(Graphics g){
g.drawString("Hello,world",40,60);
}
}
14.1.1 用Applet实现HelloWorld
Applet的运行方法有很多,下面对这几种方法都做下介绍。
(1)在Eclipse中编写Applet,编写完成后直接右击源文件,选择run as的Java Applet命令即可。
(2)Applet程序是放在浏览器中运行的。
(3)用Java提供的工具运行。在命令行中进入上面的文件存放的目录,输入appletviewer HelloWorld.htm。
(4)上面的方法都略显复杂(当然不包括使用Eclipse的情况)。
http://www.cnblogs.com/yoogoo/archive/2012/04/23/2467276.html
使用 Graphics 画出 线段 矩形 圆 等图形
代码如下:
package package1;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.awt.*;
/**
*
* @author Administrator
*/
public class drawBall extends Panel {
private int x;
private int y;
private int diameter;
private int width;
private int heigth;
public drawBall() {
x=50;
y=50;
diameter=100;
width=500;
heigth=500;
setBackground(Color.pink);
setPreferredSize(new Dimension(width, heigth));
}
public void paint(Graphics g) {
g.setColor(Color.BLUE);
g.fillOval(x,y,diameter,diameter);
}
}
package package1;
import java.awt.*;
import java.awt.event.*;
public class GameFrame {
public GameFrame() {
Frame app = new Frame("GameFrame");
app.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
app.setLocation(100, 100);
drawBall drawB = new drawBall();
app.add(drawB, BorderLayout.CENTER);
app.pack();
app.setVisible(true);
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
new GameFrame();
}
}
=============================================
小球运动
代码:
package package1;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.awt.*;
/**
*
* @author Administrator
*/
public class drawBall extends Panel {
private int x;
private int y;
private int diameter;
private int width;
private int heigth;
public drawBall() {
x=50;
y=50;
diameter=100;
width=500;
heigth=500;
setBackground(Color.pink);
setPreferredSize(new Dimension(width, heigth));
}
public void gameLoop(){
while(true){
x++;
for(int i=1;i<10000000;i++)
{}
repaint();
}
}
public void paint(Graphics g) {
g.setColor(Color.BLUE);
g.fillOval(x,y,diameter,diameter);
}
}
package package1;
import java.awt.*;
import java.awt.event.*;
public class GameFrame {
public GameFrame() {
Frame app = new Frame("GameFrame");
app.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
app.setLocation(100, 100);
app.setSize(1000, 3000);
drawBall drawB = new drawBall();
app.add(drawB, BorderLayout.CENTER);
app.pack();
app.setVisible(true);
drawB.gameLoop();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new GameFrame();
// TODO code application logic here
}
}
图像双缓冲机制:
package package1;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.awt.*;
/**
*
* @author Administrator
*/
public class drawBall extends Panel {
private int x;
private int y;
private int diameter;
private int width;
private int heigth;
private Image im;
private Graphics dbg;
public drawBall() {
x=50;
y=50;
diameter=100;
width=500;
heigth=500;
setBackground(Color.pink);
setPreferredSize(new Dimension(width, heigth));
}
public void gameLoop(){
while(true){
x++;
if (im == null) {
im = createImage(width, heigth);
if (im == null) {
System.out.println("im is null");
} else {
dbg = im.getGraphics();
}
}
dbg.setColor(Color.pink);
dbg.fillRect(0, 0, width, heigth);
dbg.setColor(Color.blue);
dbg.fillOval(x, y, diameter, diameter);
Graphics g;
try{
g=this.getGraphics();
if (g!=null&&im!=null){
g.drawImage(im, 0, 0, null);
}
g.dispose();
}
catch (Exception e){}
}
}
}
package package1;
import java.awt.*;
import java.awt.event.*;
public class GameFrame {
public GameFrame() {
Frame app = new Frame("GameFrame");
app.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
app.setLocation(100, 100);
drawBall drawB = new drawBall();
app.add(drawB, BorderLayout.CENTER);
app.pack();
app.setVisible(true);
drawB.gameLoop();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new GameFrame();
// TODO code application logic here
}
}
=============================================================================================
设置帧速率
package package1;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.awt.*;
import java.awt.image.*;
import java.util.*;
/**
*
* @author Administrator
*/
public class drawBall extends Panel implements Runnable {
private int x;
private int y;
private int diameter;
private int width;
private int heigth;
private Image im;
private Graphics dbg;
private Thread gamethread;
private static final int FPS=50;
public drawBall() {
x=50;
y=50;
diameter=100;
width=500;
heigth=500;
setBackground(Color.pink);
setPreferredSize(new Dimension(width, heigth));
}
public void gameStart(){
gamethread = new Thread(this);
gamethread.start();
}
public void gamePaint() {
Graphics g;
try {
g = this.getGraphics();
if (g != null && im != null) {
g.drawImage(im, 0, 0, null);
}
g.dispose();
} catch (Exception e) {
}
}
public void gameRender() {
if (im == null) {
im = createImage(width, heigth);
if (im == null) {
System.out.println("im is null");
} else {
dbg = im.getGraphics();
}
}
dbg.setColor(Color.pink);
dbg.fillRect(0, 0, width, heigth);
dbg.setColor(Color.blue);
dbg.fillOval(x, y, diameter, diameter);
}
public void gameUpdate() {
Random rand = new Random();
switch (rand.nextInt(4)) {
case 0:
x += 10;
break;
case 1:
x -= 10;
break;
case 2:
y += 10;
break;
case 3:
y -= 10;
break;
}
if (x > width) {
x = -diameter;
}
if (y > heigth) {
y = -diameter;
}
if (x < -diameter) {
x = width;
}
if (y < -diameter) {
y = heigth;
}
}
public void run() {
long t1,t2,dt,sleepTime;
long period=1000/FPS; //计算每一次循环需要的执行时间,单位毫秒
t1=System.nanoTime(); //保存游戏循环执行前的系统时间,单位纳秒
while(true){
gameUpdate();
gameRender();
gamePaint();
t2= System.nanoTime() ; //游戏循环执行后的系统时间,单位纳秒
dt=(t2-t1)/1000000L; //本次循环实际花费的时间,并转换为毫秒
sleepTime = period - dt;//计算本次循环剩余的时间,单位毫秒
if(sleepTime<=0) //防止sleepTime值为负数
sleepTime=2;
try {
Thread.sleep(sleepTime); //让线程休眠,由sleepTime值决定
} catch (InterruptedException ex) { }
t1 = System.nanoTime(); //重新获取当前系统时间
System.out.println("sleepTime is:"+sleepTime);
}
}
}
package package1;
import java.awt.*;
import java.awt.event.*;
public class GameFrame {
public GameFrame() {
Frame app = new Frame("GameFrame");
app.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
app.setLocation(100, 100);
drawBall drawB = new drawBall();
app.add(drawB, BorderLayout.CENTER);
app.pack();
app.setVisible(true);
drawB.gameStart();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new GameFrame();
// TODO code application logic here
}
}
===================================================================
小球 随机运动:利用了 线程来实现
package package1;
import java.awt.*;
import java.awt.image.*;
import java.util.*;
/**
*
* @author Administrator
*/
public class drawBall extends Panel implements Runnable {
private int x;
private int y;
private int dx;
private int dy;
private int dcx;
private int dcy;
private int diameter;
private int width;
private int heigth;
private Image im;
private Graphics dbg;
private Thread gamethread;
private static final int FPS=30;
public drawBall() {
x=50;
y=50;
diameter=100;
width=500;
heigth=500;
dx=0;
dy=0;
dcx=1;
dcy=1;
setBackground(Color.pink);
setPreferredSize(new Dimension(width, heigth));
}
public void gameStart(){
gamethread = new Thread(this);
gamethread.start();
}
public void gamePaint() {
Graphics g;
try {
g = this.getGraphics();
if (g != null && im != null) {
g.drawImage(im, 0, 0, null);
}
g.dispose();
} catch (Exception e) {
}
}
public void gameRender() {
if (im == null) {
im = createImage(width, heigth);
if (im == null) {
System.out.println("im is null");
} else {
dbg = im.getGraphics();
}
}
dbg.setColor(Color.pink);
dbg.fillRect(0, 0, width, heigth);
dbg.setColor(Color.blue);
dbg.fillOval(x, y, diameter, diameter);
}
public void gameUpdate() {
Random rand = new Random();
switch (rand.nextInt(4)) {
case 0:
dx+=dcx;
x += dx;
break;
case 1:
dx+=dcx;
x -= dx;
break;
case 2:
dy+=dcy;
y += dy;
break;
case 3:
dy+=dcy;
y -= dy;
break;
}
if (x > width) {
x = -diameter;
}
if (y > heigth) {
y = -diameter;
}
if (x < -diameter) {
x = width;
}
if (y < -diameter) {
y = heigth;
}
}
public void run() {
long t1,t2,dt,sleepTime;
long period=1000/FPS; //计算每一次循环需要的执行时间,单位毫秒
t1=System.nanoTime(); //保存游戏循环执行前的系统时间,单位纳秒
while(true){
gameUpdate();
gameRender();
gamePaint();
t2= System.nanoTime() ; //游戏循环执行后的系统时间,单位纳秒
dt=(t2-t1)/1000000L; //本次循环实际花费的时间,并转换为毫秒
sleepTime = period - dt;//计算本次循环剩余的时间,单位毫秒
if(sleepTime<=0) //防止sleepTime值为负数
sleepTime=2;
try {
Thread.sleep(sleepTime); //让线程休眠,由sleepTime值决定
} catch (InterruptedException ex) { }
t1 = System.nanoTime(); //重新获取当前系统时间
}
}}
package package1;
import java.awt.*;
import java.awt.event.*;
public class GameFrame {
public GameFrame() {
Frame app = new Frame("GameFrame");
app.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
app.setLocation(100, 100);
drawBall drawB = new drawBall();
app.add(drawB, BorderLayout.CENTER);
app.pack();
app.setVisible(true);
drawB.gameStart();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new GameFrame();
}
}
=======================================================================
小球的 直线 匀速运动
package package1;
import java.awt.*;
import java.awt.image.*;
import java.util.*;
/**
*
* @author Administrator
*/
public class drawBall extends Panel implements Runnable {
private int x;
private int y;
private int dx;
private int dy;
private int dcx;
private int dcy;
private int diameter;
private int width;
private int heigth;
private Image im;
private Graphics dbg;
private Thread gamethread;
private static final int FPS=30;
public drawBall() {
x=50;
y=50;
diameter=100;
width=500;
heigth=500;
dx=0;
dy=0;
dcx=1;
dcy=1;
setBackground(Color.pink);
setPreferredSize(new Dimension(width, heigth));
}
public void gameStart(){
gamethread = new Thread(this);
gamethread.start();
}
public void gamePaint() {
Graphics g;
try {
g = this.getGraphics();
if (g != null && im != null) {
g.drawImage(im, 0, 0, null);
}
g.dispose();
} catch (Exception e) {
}
}
public void gameRender() {
if (im == null) {
im = createImage(width, heigth);
if (im == null) {
System.out.println("im is null");
} else {
dbg = im.getGraphics();
}
}
dbg.setColor(Color.pink);
dbg.fillRect(0, 0, width, heigth);
dbg.setColor(Color.blue);
dbg.fillOval(x, y, diameter, diameter);
}
public void gameUpdate() {
x += 10;
y +=10;
if (x > width) {
x = 0;
}
if (y > heigth) {
y = 0;
}
}
public void run() {
long t1,t2,dt,sleepTime;
long period=1000/FPS; //计算每一次循环需要的执行时间,单位毫秒
t1=System.nanoTime(); //保存游戏循环执行前的系统时间,单位纳秒
while(true){
gameUpdate();
gameRender();
gamePaint();
t2= System.nanoTime() ; //游戏循环执行后的系统时间,单位纳秒
dt=(t2-t1)/1000000L; //本次循环实际花费的时间,并转换为毫秒
sleepTime = period - dt;//计算本次循环剩余的时间,单位毫秒
if(sleepTime<=0) //防止sleepTime值为负数
sleepTime=2;
try {
Thread.sleep(sleepTime); //让线程休眠,由sleepTime值决定
} catch (InterruptedException ex) { }
t1 = System.nanoTime(); //重新获取当前系统时间
}
}}
package package1;
import java.awt.*;
import java.awt.event.*;
public class GameFrame {
public GameFrame() {
Frame app = new Frame("GameFrame");
app.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
app.setLocation(100, 100);
drawBall drawB = new drawBall();
app.add(drawB, BorderLayout.CENTER);
app.pack();
app.setVisible(true);
drawB.gameStart();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new GameFrame();
}
}
==============================================
4——2daima 有些复杂,先测试简单的代码: 添加 键盘 事件。
自己修改后的 小球按照键盘指示运动:
package package1;
import java.awt.*;
import java.awt.image.*;
import java.util.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.*;
/**
*
* @author Administrator
*/
public class drawBall extends Panel implements Runnable , KeyListener{
private int x;
private int y;
private int diameter;
private int width;
private int heigth;
private Image im;
private Graphics dbg;
private Thread gamethread;
private static final int FPS=30;
private int direction;
public static final int SOUTH = 0;
public static final int NORTH = 1;
public static final int EAST = 2;
public static final int WEST = 3;
public drawBall() {
x=50;
y=50;
diameter=50;
width=500;
heigth=500;
setBackground(Color.pink);
setPreferredSize(new Dimension(width, heigth));
setFocusable(true);
this.addKeyListener(this);
}
public void gameStart(){
gamethread = new Thread(this);
gamethread.start();
}
public void gamePaint() {
Graphics g;
try {
g = this.getGraphics();
if (g != null && im != null) {
g.drawImage(im, 0, 0, null);
}
g.dispose();
} catch (Exception e) {
}
}
public void gameRender() {
if (im == null) {
im = createImage(width, heigth);
if (im == null) {
System.out.println("im is null");
} else {
dbg = im.getGraphics();
}
}
dbg.setColor(Color.pink);
dbg.fillRect(0, 0, width, heigth);
dbg.setColor(Color.blue);
dbg.fillOval(x, y, diameter, diameter);
}
public int getDirection() {
return direction;
}
public void gameUpdate() {
switch (getDirection()) {
case 0:
y += 10;
break;
case 1:
y -= 10;
break;
case 2:
x += 10;
break;
case 3:
x -= 10;
break;
}
}
public void run() {
long t1,t2,dt,sleepTime;
long period=1000/FPS; //计算每一次循环需要的执行时间,单位毫秒
t1=System.nanoTime(); //保存游戏循环执行前的系统时间,单位纳秒
while(true){
gameUpdate();
gameRender();
gamePaint();
t2= System.nanoTime() ; //游戏循环执行后的系统时间,单位纳秒
dt=(t2-t1)/1000000L; //本次循环实际花费的时间,并转换为毫秒
sleepTime = period - dt;//计算本次循环剩余的时间,单位毫秒
if(sleepTime<=0) //防止sleepTime值为负数
sleepTime=2;
try {
Thread.sleep(sleepTime); //让线程休眠,由sleepTime值决定
} catch (InterruptedException ex) { }
t1 = System.nanoTime(); //重新获取当前系统时间
}
}
public void keyPressed(KeyEvent e) {
int keycode = e.getKeyCode();
switch (keycode) {
case KeyEvent.VK_DOWN:
direction = SOUTH;
System.out.println("key is down" + direction);
break;
case KeyEvent.VK_UP:
direction = NORTH;
System.out.println("key is up" + direction);
break;
case KeyEvent.VK_RIGHT:
direction = EAST;
System.out.println("key is right" + direction);
break;
case KeyEvent.VK_LEFT:
direction = WEST;
System.out.println("key is left" + direction);
break;
}
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
}
package package1;
import java.awt.*;
import java.awt.event.*;
public class GameFrame {
public GameFrame() {
Frame app = new Frame("GameFrame");
app.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
app.setLocation(100, 100);
drawBall drawB = new drawBall();
app.add(drawB, BorderLayout.CENTER);
app.pack();
app.setVisible(true);
drawB.gameStart();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new GameFrame();
}
}
==================================
===================================================================================
游戏中的物体运动:
package package1;
import java.awt.*;
import java.awt.event.*;
public class GameFrame {
public GameFrame() {
Frame app = new Frame("GameFrame");
app.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
app.setLocation(100, 100);
drawBall drawB = new drawBall();
app.add(drawB, BorderLayout.CENTER);
app.pack();
app.setVisible(true);
drawB.gameStart();
}
public static void main(String[] args) {
new GameFrame();
}
}
package package1;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.*;
import java.util.*;
/**
*
* @author Administrator
*/
public class drawBall extends Panel implements Runnable, KeyListener {
private int x;
private int y;
private int diameter;
private int width;
private int heigth;
private Image im;
private Graphics dbg;
private Thread gamethread;
private static final int FPS = 50;
private boolean running = true;
private boolean isPaused = false;
public drawBall() {
x = 50;
y = 50;
diameter = 100;
width = 500;
heigth = 500;
setBackground(Color.pink);
setPreferredSize(new Dimension(width, heigth));
this.addKeyListener(this);
}
public void gameStart() {
gamethread = new Thread(this);
gamethread.start();
}
public void gamePaint() {
Graphics g;
try {
g = this.getGraphics();
if (g != null && im != null) {
g.drawImage(im, 0, 0, null);
}
g.dispose();
} catch (Exception e) {
}
}
public void gameRender() {
if (im == null) {
im = createImage(width, heigth);
if (im == null) {
System.out.println("im is null");
} else {
dbg = im.getGraphics();
}
}
dbg.setColor(Color.pink);
dbg.fillRect(0, 0, width, heigth);
dbg.setColor(Color.blue);
dbg.fillOval(x, y, diameter, diameter);
}
public void gameUpdate() {
Random rand = new Random();
switch (rand.nextInt(4)) {
case 0:
x += 10;
break;
case 1:
x -= 10;
break;
case 2:
y += 10;
break;
case 3:
y -= 10;
break;
}
if (x > width) {
x = -diameter;
}
if (y > heigth) {
y = -diameter;
}
if (x < -diameter) {
x = width;
}
if (y < -diameter) {
y = heigth;
}
}
public void run() {
long t1,t2,dt,sleepTime;
long period=1000/FPS; //计算每一次循环需要的执行时间,单位毫秒
t1=System.nanoTime(); //保存游戏循环执行前的系统时间,单位纳秒
while (running) {
if (!isPaused) {
gameUpdate();
}
gameRender();
gamePaint();
t2= System.nanoTime() ; //游戏循环执行后的系统时间,单位纳秒
dt=(t2-t1)/1000000L; //本次循环实际花费的时间,并转换为毫秒
sleepTime = period - dt;//计算本次循环剩余的时间,单位毫秒
if(sleepTime<=0) //防止sleepTime值为负数
sleepTime=2;
try {
Thread.sleep(sleepTime); //让线程休眠,由sleepTime值决定
} catch (InterruptedException ex) { }
t1 = System.nanoTime(); //重新获取当前系统时间
}
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
running = false;
System.out.println("key is ESC" );
}
if (e.getKeyCode() == KeyEvent.VK_P) {
isPaused = !isPaused;
System.out.println("key is P" );
}
}
public void keyReleased(KeyEvent e) {
}
}
===========================================================================
模拟直线运动
package package1;
import java.awt.*;
import java.awt.event.*;
public class GameFrame {
public GameFrame() {
Frame app = new Frame("GameFrame");
app.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
app.setLocation(100, 100);
gamePanel drawB = new gamePanel();
app.add(BorderLayout.CENTER, drawB);
app.pack();
app.setVisible(true);
drawB.gameStart();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new GameFrame();
// TODO code application logic here
}
}
package package1;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
/**
*
* @author Administrator
*/
public class gamePanel extends Panel implements Runnable, KeyListener {
public int width;
public int heigth;
private Image im;
private Graphics dbg;
private Thread gamethread;
private static final int FPS = 50;
private boolean running = false;
private boolean isPaused = false;
private int direction;
public static final int SOUTH = 0;
public static final int NORTH = 1;
public static final int EAST = 2;
public static final int WEST = 3;
private ball sk;
public gamePanel() {
width = 500;
heigth = 500;
setBackground(Color.pink);
setPreferredSize(new Dimension(width, heigth));
sk = new ball(this);
setFocusable(true);
requestFocus();
addKeyListener(this);
}
public int getDirection() {
return direction;
}
public void gameStart() {
if (!running) {
gamethread = new Thread(this);
gamethread.start();
}
}
public void gameStop() {
running = false;
}
public void gamePaint() {
Graphics g;
try {
g = this.getGraphics();
if (g != null && im != null) {
g.drawImage(im, 0, 0, null);
}
g.dispose();
} catch (Exception e) {
}
}
public void gameRender() {
if (im == null) {
im = createImage(width, heigth);
if (im == null) {
System.out.println("im is null");
} else {
dbg = im.getGraphics();
}
}
dbg.setColor(Color.pink);
dbg.fillRect(0, 0, width, heigth);
sk.draw(dbg);
}
public void gameUpdate() {
if (!isPaused) {
sk.move();
}
}
public void run() {
long t1,t2,dt,sleepTime;
long period=1000/FPS; //计算每一次循环需要的执行时间,单位毫秒
t1=System.nanoTime(); //保存游戏循环执行前的系统时间,单位纳秒
while(true){
gameUpdate();
gameRender();
gamePaint();
t2= System.nanoTime() ; //游戏循环执行后的系统时间,单位纳秒
dt=(t2-t1)/1000000L; //本次循环实际花费的时间,并转换为毫秒
sleepTime = period - dt;//计算本次循环剩余的时间,单位毫秒
if(sleepTime<=0) //防止sleepTime值为负数
sleepTime=2;
try {
Thread.sleep(sleepTime); //让线程休眠,由sleepTime值决定
} catch (InterruptedException ex) { }
t1 = System.nanoTime(); //重新获取当前系统时间
}
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
int keycode = e.getKeyCode();
if (keycode == KeyEvent.VK_ESCAPE) {
running = false;
System.out.println("key is escape");
}
if (keycode == KeyEvent.VK_P) {
isPaused =!isPaused;
System.out.println("key is P");
}
if (!isPaused ) {
switch (keycode) {
case KeyEvent.VK_DOWN:
direction = SOUTH;
System.out.println("key is down" + direction);
break;
case KeyEvent.VK_UP:
direction = NORTH;
System.out.println("key is up" + direction);
break;
case KeyEvent.VK_RIGHT:
direction = EAST;
System.out.println("key is right" + direction);
break;
case KeyEvent.VK_LEFT:
direction = WEST;
System.out.println("key is left" + direction);
break;
}
}
}
public void keyReleased(KeyEvent e) {
}
}
package package1;
import java.awt.*;
public class ball {
gamePanel gameP;
private int x;
private int y;
private int speed;
private int diameter;
public ball(gamePanel gp) {
gameP = gp;
x = 50;
y = 50;
diameter = 10;
speed = 10;
}
public void move() {
int direction=gameP.getDirection();
switch (direction) {
case gamePanel.SOUTH:
y += speed;
break;
case gamePanel.NORTH:
y -= speed;
break;
case gamePanel.EAST:
x += speed;
break;
case gamePanel.WEST:
x -= speed;
break;
}
if (x > gameP.width) {
x = -diameter;
}
if (y > gameP.heigth) {
y = -diameter;
}
if (x < -diameter) {
x = gameP.width;
}
if (y < -diameter) {
y = gameP.heigth;
}
}
public void draw(Graphics g) {
g.setColor(Color.blue);
g.fillOval(x, y, diameter, diameter);
}
}
==================================================================================
物体运动:
package package1;
import java.awt.*;
import java.awt.event.*;
public class GameFrame {
public GameFrame() {
Frame app = new Frame("GameFrame");
app.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
app.setLocation(100, 100);
GamePanel drawB = new GamePanel();
app.add(drawB, BorderLayout.CENTER);
app.pack();
app.setVisible(true);
drawB.gameStart();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new GameFrame();
// TODO code application logic here
}
}
package package1;
import java.awt.*;
import java.awt.event.*;
/**
*
* @author Administrator
*/
public class GamePanel extends Panel implements Runnable, KeyListener{
public int width;
public int heigth;
public int incre=1;
private Image im;
private Graphics dbg;
private Thread gamethread;
private static final int FPS = 30;
private boolean running = false;
private boolean isPaused = false;
private int direction;
public static final int SOUTH = 0;
public static final int NORTH = 1;
public static final int EAST = 2;
public static final int WEST = 3;
private Ball myball;
public GamePanel() {
width = 300;
heigth = 300;
setPreferredSize(new Dimension(width, heigth));
myball = new Ball(this);
setFocusable(true);
requestFocus();
addKeyListener(this);
}
public int getDirection() {
return direction;
}
public void gameStart() {
if (!running) {
gamethread = new Thread(this);
gamethread.start();
}
}
public void gameStop() {
running = false;
}
public void gamePaint() {
Graphics g;
try {
g = this.getGraphics();
if (g != null && im != null) {
g.drawImage(im, 0, 0, null);
}
g.dispose();
} catch (Exception e) {
}
}
public void gameRender() {
if (im == null) {
im = createImage(width, heigth);
if (im == null) {
System.out.println("im is null");
} else {
dbg = im.getGraphics();
}
}
dbg.setColor(Color.white);
dbg.fillRect(0, 0, width, heigth);
myball.draw(dbg);
}
public void gameUpdate() {
if (!isPaused) {
myball.update();
}
}
public void run() {
long t1,t2,dt,sleepTime;
long period=1000/FPS; //计算每一次循环需要的执行时间,单位毫秒
t1=System.nanoTime(); //保存游戏循环执行前的系统时间,单位纳秒
while(true){
gameUpdate();
gameRender();
gamePaint();
t2= System.nanoTime() ; //游戏循环执行后的系统时间,单位纳秒
dt=(t2-t1)/1000000L; //本次循环实际花费的时间,并转换为毫秒
sleepTime = period - dt;//计算本次循环剩余的时间,单位毫秒
if(sleepTime<=0) //防止sleepTime值为负数
sleepTime=2;
try {
Thread.sleep(sleepTime); //让线程休眠,由sleepTime值决定
} catch (InterruptedException ex) { }
t1 = System.nanoTime(); //重新获取当前系统时间
}
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
int keycode = e.getKeyCode();
if (keycode == KeyEvent.VK_P) {
isPaused =!isPaused;
System.out.println("key is P");
}
if (keycode == KeyEvent.VK_I) {
if (incre<20) {
incre++;
}
System.out.println("key is I");
}
if (!isPaused ) {
switch (keycode) {
case KeyEvent.VK_DOWN:
direction = SOUTH;
System.out.println("key is down" + direction);
break;
case KeyEvent.VK_UP:
direction = NORTH;
System.out.println("key is up" + direction);
break;
case KeyEvent.VK_RIGHT:
direction = EAST;
System.out.println("key is right" + direction);
break;
case KeyEvent.VK_LEFT:
direction = WEST;
System.out.println("key is left" + direction);
break;
}
}
}
public void keyReleased(KeyEvent e) {
}
}
package package1;
import java.awt.*;
public class Ball {
GamePanel gameP;
private Point[] body;
public static final int MAXLENTH = 20;
private int head;
private int tail;
public int length;
private int speed;
public int x;
public int y;
public int diameter;
public Ball(GamePanel gp) {
gameP = gp;
body = new Point[MAXLENTH];
head = -1;
tail = -1;
length = 1;
speed = 10;
x = 50;
y = 50;
diameter = 10;
}
public void update() {
int direction=gameP.getDirection();
switch (direction) {
case GamePanel.SOUTH:
y += speed;
break;
case GamePanel.NORTH:
y -= speed;
break;
case GamePanel.EAST:
x += speed;
break;
case GamePanel.WEST:
x -= speed;
break;
}
if (x > gameP.width) {
x = -diameter;
}
if (y > gameP.heigth) {
y = -diameter;
}
if (x < -diameter) {
x = gameP.width;
}
if (y < -diameter) {
y = gameP.heigth;
}
length = gameP.incre;
head = (head + 1) % body.length;
tail = (head + body.length - length + 1) % body.length;
body[head] = new Point(x, y);
}
public void draw(Graphics g) {
g.setColor(Color.blue);
if (length > 1) {
int i = tail;
while (i != head) {
g.fillOval(body[i].x, body[i].y, diameter, diameter);
i = (i + 1) % body.length;
}
}
g.setColor(Color.red);
g.fillOval(body[head].x, body[head].y, diameter, diameter);
}
}
===========================
添加 图像 基础代码
package package1;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
import java.awt.image.*;
public class tu_xing extends JFrame {
int xpoint = 100, ypoint = 100;
public tu_xing() {
//Do frame stuff.
super("MyFrame");
}
public void paint(Graphics g) {
URL imgURL = getClass().getResource("/Images/player_left.gif");
ImageIcon icon = new ImageIcon(imgURL);
g.drawImage(icon.getImage(),xpoint,ypoint,this);
}
public static void main(String[] args) {
tu_xing frame = new tu_xing();
frame.pack();
frame.setVisible(true);
}
}
===========================
========================================================================
碰撞检测:
代码 4_6
============================================================
贪吃蛇代码:
package package1;
import java.awt.*;
import java.awt.event.*;
public class GameFrame {
public GameFrame() {
Frame app = new Frame("GameFrame");
app.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
app.setLocation(100, 100);
GamePanel drawB = new GamePanel();
app.add(drawB, BorderLayout.CENTER);
app.pack();
app.setResizable(false);
app.setVisible(true);
drawB.gameStart();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new GameFrame();
// TODO code application logic here
}
}
package package1;
import java.awt.*;
public class Snake {
GamePanel gameP;
private Point[] body;
public static final int MAXLENTH = 20;
private int head;
private int tail;
public int length;
private int speed;
public int x;
public int y;
public int diameter;
public Snake(GamePanel gp) {
gameP = gp;
body = new Point[MAXLENTH];
head = -1;
tail = -1;
length = 1;
speed = 10;
x = 50;
y = 50;
diameter = 10;
}
public void update() {
int direction=gameP.getDirection();
switch (direction) {
case GamePanel.SOUTH:
y += speed;
break;
case GamePanel.NORTH:
y -= speed;
break;
case GamePanel.EAST:
x += speed;
break;
case GamePanel.WEST:
x -= speed;
break;
}
if (x > gameP.width) {
x = -diameter;
}
if (y > gameP.heigth) {
y = -diameter;
}
if (x < -diameter) {
x = gameP.width;
}
if (y < -diameter) {
y = gameP.heigth;
}
head = (head + 1) % body.length;
tail = (head + body.length - length + 1) % body.length;
body[head] = new Point(x, y);
}
public void draw(Graphics g) {
g.setColor(Color.blue);
if (length > 1) {
int i = tail;
while (i != head) {
g.fillOval(body[i].x, body[i].y, diameter, diameter);
i = (i + 1) % body.length;
}
}
g.setColor(Color.red);
g.fillOval(body[head].x, body[head].y, diameter, diameter);
}
}
package package1;
import java.awt.*;
import java.awt.event.*;
public class GamePanel extends Panel implements Runnable, KeyListener{
public int width;
public int heigth;
public int incre=1;
private Image im;
private Graphics dbg;
private Thread gamethread;
private static final int FPS = 30;
private boolean running = false;
private boolean isPaused = false;
private int direction;
public static final int SOUTH = 0;
public static final int NORTH = 1;
public static final int EAST = 2;
public static final int WEST = 3;
private Snake sk;
private Food bk;
public GamePanel() {
width = 300;
heigth = 300;
setPreferredSize(new Dimension(width, heigth));
sk = new Snake(this);
bk = new Food(this, sk);
setFocusable(true);
requestFocus();
addKeyListener(this);
}
public int getDirection() {
return direction;
}
public void gameStart() {
if (!running) {
gamethread = new Thread(this);
gamethread.start();
}
}
public void gameStop() {
running = false;
}
public void gamePaint() {
Graphics g;
try {
g = this.getGraphics();
if (g != null && im != null) {
g.drawImage(im, 0, 0, null);
}
g.dispose();
} catch (Exception e) {
}
}
public void gameRender() {
if (im == null) {
im = createImage(width, heigth);
if (im == null) {
System.out.println("im is null");
} else {
dbg = im.getGraphics();
}
}
dbg.setColor(Color.white);
dbg.fillRect(0, 0, width, heigth);
sk.draw(dbg);
bk.draw(dbg);
}
public void gameUpdate() {
if (!isPaused) {
sk.update();
bk.update();
}
}
public void run() {
long t1,t2,dt,sleepTime;
long period=1000/FPS; //计算每一次循环需要的执行时间,单位毫秒
t1=System.nanoTime(); //保存游戏循环执行前的系统时间,单位纳秒
while(true){
gameUpdate();
gameRender();
gamePaint();
t2= System.nanoTime() ; //游戏循环执行后的系统时间,单位纳秒
dt=(t2-t1)/1000000L; //本次循环实际花费的时间,并转换为毫秒
sleepTime = period - dt;//计算本次循环剩余的时间,单位毫秒
if(sleepTime<=0) //防止sleepTime值为负数
sleepTime=2;
try {
Thread.sleep(sleepTime); //让线程休眠,由sleepTime值决定
} catch (InterruptedException ex) { }
t1 = System.nanoTime(); //重新获取当前系统时间
}
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
int keycode = e.getKeyCode();
if (keycode == KeyEvent.VK_P) {
isPaused = !isPaused;
System.out.println("key is P");
}
if (!isPaused ) {
switch (keycode) {
case KeyEvent.VK_DOWN:
direction = SOUTH;
System.out.println("key is down" + direction);
break;
case KeyEvent.VK_UP:
direction = NORTH;
System.out.println("key is up" + direction);
break;
case KeyEvent.VK_RIGHT:
direction = EAST;
System.out.println("key is right" + direction);
break;
case KeyEvent.VK_LEFT:
direction = WEST;
System.out.println("key is left" + direction);
break;
}
}
}
public void keyReleased(KeyEvent e) {
}
}
package package1;
import java.awt.*;
import java.util.Random;
public class Food {
public Point location;
public Point size;
private GamePanel gameP;
private Snake snk;
private Random rand;
public Food(GamePanel gp, Snake sk) {
gameP = gp;
snk = sk;
rand = new Random();
location = new Point(Math.abs(rand.nextInt() % gameP.width), Math.abs(rand.nextInt() % gameP.heigth));
size = new Point(sk.diameter, sk.diameter);
}
public void update() {
if ((Math.abs((snk.x + snk.diameter / 2) - (location.x + size.x / 2)) < snk.diameter) &&
(Math.abs((snk.y + snk.diameter / 2) - (location.y + size.y / 2)) < snk.diameter)) {
location = new Point(Math.abs(rand.nextInt() % gameP.width), Math.abs(rand.nextInt() % gameP.heigth));
if (snk.length < Snake.MAXLENTH) {
snk.length++;
}
}
}
public void draw(Graphics g) {
g.setColor(Color.black);
g.fillRect(location.x, location.y, size.x, size.y);
}
}
=======================================
转载文章:
http://blog.csdn.net/zhai56565/article/details/8799497