本示例實現一個基於 Swing 的圖形繪製工具,支持直線、圓形、圖片三種圖元繪製,並通過 DataOutputStream/DataInputStream 實現圖形對象的二進制序列化存儲與讀取,展示了 Java 圖形編程、事件監聽、文件 IO 序列化的綜合應用。
abstract class Shape {
int x, y, x1, y1;
Color color;
byte type; // 0=Line, 1=Oval, 2=Picture
public abstract void draw(Graphics g);
}
class LineShape extends Shape { ... } // 直線
class OvalShape extends Shape { ... } // 圓形
class Picture extends Shape { // 圖片(像素矩陣)
int a, b; int[][] cl;
public void draw(Graphics g) { ... }
}
PaintDemo 作為 ActionListener 與 MouseListener。實現 MouseListener、ActionListener,管理圖形列表 ArrayList<Shape>。
mousePressed:記錄起始坐標 (x, y)mouseReleased:記錄結束坐標 (x1, y1),根據當前模式創建對應 Shape,調用 draw() 繪製,加入列表public void saveFile(String path, ArrayList<Shape> shapes) {
DataOutputStream dos = new DataOutputStream(new FileOutputStream(path));
dos.writeInt(shapes.size()); // 寫入圖形總數
for (Shape shape : shapes) {
dos.writeByte(shape.type); // 寫入類型標識
switch (shape.type) {
case 0: // LineShape
LineShape line = (LineShape) shape;
dos.writeInt(line.x); dos.writeInt(line.y);
dos.writeInt(line.x1); dos.writeInt(line.y1);
dos.writeInt(line.color.getRGB());
break;
case 1: // OvalShape
OvalShape oval = (OvalShape) shape;
dos.writeInt(oval.x); dos.writeInt(oval.y);
dos.writeInt(oval.x1); dos.writeInt(oval.y1);
dos.writeInt(oval.color.getRGB());
break;
case 2: // Picture
Picture pic = (Picture) shape;
dos.writeInt(pic.a); dos.writeInt(pic.b);
for (int k=0; k
public ArrayList<Shape> readFile(String path) {
DataInputStream dis = new DataInputStream(new FileInputStream(path));
int len = dis.readInt();
for (int i=0; i<len; i++) {
byte type = dis.readByte();
switch (type) {
case 0: // Line
shapes.add(new LineShape(dis.readInt(), dis.readInt(), dis.readInt(), dis.readInt(), new Color(dis.readInt())));
break;
case 1: // Oval
shapes.add(new OvalShape(dis.readInt(), dis.readInt(), dis.readInt(), dis.readInt(), new Color(dis.readInt())));
break;
case 2: // Picture
int w = dis.readInt(), h = dis.readInt();
int[][] cl = new int[w][h];
for (int k=0; k
saveFile("D:\\test.txt", shapes)readFile 並遍歷重繪所有圖形