本文共 1609 字,大约阅读时间需要 5 分钟。
功能:代码重构(设置常量,比较简单)
内容:需要多处改变的量定义为常量。
public static final int GAME_WIDTH =800;public static final int GAME_HEIGHT=800;
然后想改成多少,就在这个位置改变 GAME_WIDTH 和GAME_HEIGHT的值
public static final int GAME_WIDTH =800;public static final int GAME_HEIGHT=600;全部代码:
public class TankClient extends Frame { public static final int GAME_WIDTH =800; public static final int GAME_HEIGHT =800; int x = 30; int y = 30; //定义在方法外面 Image offScreenImage = null; public void paint(Graphics g) { Color c = g.getColor(); g.setColor(Color.RED); g.fillOval(x, y, 30, 40); g.setColor(c); y += 5; } public void update(Graphics g) { if(offScreenImage == null){ offScreenImage = this.createImage(GAME_WIDTH,GAME_HEIGHT); } Graphics gOffScreen = offScreenImage.getGraphics(); Color c = gOffScreen.getColor(); gOffScreen.setColor(Color.GREEN); gOffScreen.fillRect(0, 0, 800, 600); gOffScreen.setColor(c); print(gOffScreen); g.drawImage(offScreenImage, 0, 0, null); } public void lauchFrame(){ this.setSize(GAME_WIDTH,GAME_HEIGHT); this.setTitle("TankWar"); this.setLocation(80, 60); this.setVisible(true); this.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e) { System.exit(0); } }); this.setResizable(false); new Thread(new paintThread()).start(); } public static void main(String[] args) { TankClient tc = new TankClient(); tc.lauchFrame(); } private class paintThread implements Runnable { //线程 内部类 为此线程服务 public void run() { while(true){ repaint(); try { Thread.sleep(50); } catch (Exception e) { e.printStackTrace(); } } } } }
转载地址:http://klrxb.baihongyu.com/