到目前为止实现的功能为下图所示:
实现的过程:
1,封装了一个抽象类Layer,这个抽象类实现了绘制窗口的功能protected void createWindow(Graphics g),另外还定义了一个抽象方法abstract public void paint(Graphics g);
为方便后面子类进行继承重写。
具体代码如下所示:
package ui;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
/*绘制窗口
@author cm*/
public abstract class Lay {
private static final int SIZE=7;
private static Image WINDOW_IMG = new ImageIcon("graphics/window/window.png").getImage();
private static int WINDOW_W= WINDOW_IMG.getWidth(null);
private static int WINDOW_H = WINDOW_IMG.getHeight(null);
/* 窗口左上角x坐标*/
protected int x;
/*窗口左上角y坐标*/
protected int y;
/*窗口宽度*/
protected int w;
/*窗口高度*/
protected int h;
protected Lay(int x ,int y ,int w , int h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
/*绘制窗口*/
protected void createWindow(Graphics g){
//ctrl+shift+o能够快速引包
//左上
g.drawImage(WINDOW_IMG, x, y, x+SIZE, y+SIZE, 0, 0, SIZE, SIZE, null);
//中上
g.drawImage(WINDOW_IMG, x+SIZE, y, x+w-SIZE, y+SIZE, SIZE, 0, WINDOW_W-SIZE, SIZE, null);
//右上
g.drawImage(WINDOW_IMG, x+w-SIZE, y, x+w, y+SIZE, WINDOW_W-SIZE, 0, WINDOW_W, SIZE, null);
//左中
g.drawImage(WINDOW_IMG, x, y+SIZE, x+SIZE, y+h-SIZE, 0, SIZE, SIZE, WINDOW_H-SIZE, null);
//中
g.drawImage(WINDOW_IMG, x+SIZE, y+SIZE, x+w-SIZE, y+h-SIZE, SIZE, SIZE, WINDOW_W-SIZE, WINDOW_H-SIZE, null);
//右中
g.drawImage(WINDOW_IMG, x+w-SIZE, y+SIZE, x+w, y+h-SIZE, WINDOW_W-SIZE, SIZE, WINDOW_W, WINDOW_H-SIZE, null);
//左下
g.drawImage(WINDOW_IMG, x, y+h-SIZE, x+SIZE, y+h, 0, WINDOW_H-SIZE, SIZE, WINDOW_H, null);
//中下
g.drawImage(WINDOW_IMG, x+SIZE, y+h-SIZE, x+w-SIZE, y+h, SIZE, WINDOW_H-SIZE, WINDOW_W-SIZE, WINDOW_H, null);
//右下
g.drawImage(WINDOW_IMG, x+w-SIZE, y+h-SIZE, x+w, y+h, WINDOW_W-SIZE, WINDOW_H-SIZE, WINDOW_W, WINDOW_H, null);
}
abstract public void paint(Graphics g);
}
2.panel上面有8个窗口,所以定义八个子类从Layer继承,实现这八个窗口的绘制,这个八个类分别为:LayerDataBase,LayerDisk,LayerGame,LayerButton,LayerNext,LayerLevel,LayerPoint,LayerAbout
具体代码实现如下:(八个都类似)
package ui;
import java.awt.Graphics;
public class LayDataBase extends Lay {
public LayDataBase(int x ,int y, int w, int h){
super(x,y,w,h);
}
public void paint(Graphics g){
this.createWindow(g);
}
}
3.通过PanelGame类来具体实现
具体代码实现如下:
package ui;
import java.awt.Graphics;
import javax.swing.JPanel;
public class PanelGame extends JPanel {
//ctrl+d是直接删除行
/*private Lay lay1 = new Lay(40,32,334,279);
private Lay lay2 = new Lay(40,343,334,279);
private Lay lay3 = new Lay(414,32,334,590);*/
private Lay[] lays = null;
public PanelGame(){
lays = new Lay[]{
//硬编码,是非常不好的开发习惯,要尽量将数字
//或者字符串定义成常量,或者写入配置文件中。
new LayDataBase(40,32,334,279),
new LayDisk(40,343,334,279),
new LayGame(414,32,334,590),
new LayButton(788,32,334,124),
new LayNext(788,188,176,148),
new LayLevel(964,188,158,148),
new LayPoint(788,368,334,200),
};
}
@Override
public void paintComponent(Graphics g){
//循环刷新游戏画面
for(int i = 0; i < lays.length; i++){
//刷新层窗口
lays[i].paint(g);
}
}
}