(1) Сначала определите класс, который будет реализован, я сначала определяю абстрактный класс
Кода -копия выглядит следующим образом:
//Графика
Абстрактная форма класса {
int x, y;
int x1, y1;
Цвет цвета;
Графика G;
тип байта;
Общественная абстрактная void Draw (Graphics G);
}
// прямая линия
класс Lineshape расширяет форму {
Public Lineshape (int x, int y, int x1, int y1, color) {
this.x = x;
this.y = y;
this.x1 = x1;
this.y1 = y1;
this.color = color;
this.Type = 0;
}
@Override
public void Draw (Graphics G) {
g.setcolor (цвет);
g.drawline (x, y, x1, y1);
}
}
// Circle Class
класс ovalshape расширяет форму {
public ovalshape (int x, int y, int x1, int y1, color) {
this.x = x;
this.y = y;
this.x1 = x1;
this.y1 = y1;
this.color = color;
this.Type = 1;
}
@Override
public void Draw (Graphics G) {
g.setcolor (цвет);
G.Drawoval ((x+x1)/2, (y+y1)/2, (x1-x)/2, (y1-y)/2);
}
}
// картинки
Изображение класса расширяет форму {
int a;
int b;
int cl [] [];
Общественная картина (int a, int b, int cl [] []) {
this.Type = 2;
this.a = a;
this.b = b;
this.cl = cl;
}
public void Draw (Graphics G) {
for (int k = 0; k <a; k ++) {
for (int j = 0; j <b; j ++) {
Цвет C = новый цвет (Cl [k] [j]);
g.setcolor (c);
G.Drawline (K+100, J+100, K+100, J+100);
}
}
}
}
(2) Общий класс метода
Кода -копия выглядит следующим образом:
открытый класс bmpsavestart {
Графика G;
public static void main (string [] args) {
new bmpsavestart () .ui ();
}
public void UI () {
Jframe jf = new jframe ();
jf.setsize (600 600);
jf.settitle («хранение изображения»);
jf.setbackground (color.white);
Jmenubar bar = new jmenubar ();
JMENU MENU1 = новый JMENU ("Option");
Jmenuitem m1 = new jmenuitem («нарисуйте круг»);
Jmenuitem m2 = new jmenuitem ("Draw Line");
Jmenuitem m3 = new jmenuitem ("Storage");
Jmenuitem m4 = new jmenuitem ("open");
Jmenuitem m5 = new jmenuitem ("picture");
Menu1.add (M1);
Menu1.add (M2);
Menu1.add (M3);
Menu1.add (M4);
Menu1.add (M5);
bar.add (Menu1);
jf.setjmenubar (бар);
JF.SetDefaultCloseoperation (3);
jf.setvisible (true);
PaintDemo P = новый PaintDemo (G, JF);
M1.SetActionCommand («Нарисуйте круг»);
m2.setActionCommand ("Draw Line");
M3.SetActionCommand («Хранение»);
M4.SetActionCommand («Open»);
m5.setActionCommand («картинка»);
M1.AddactionListener (P);
m2.addactionListener (P);
M3.AddactionListener (P);
M4.AddactionListener (P);
m5.addactionListener (P);
}
}
(3) Мониторинг класса
Кода -копия выглядит следующим образом:
класс PaintDemo реализует Mouselestener, ActionListener {
ImageICon img = new ImageICon ("Image/100.gif");
BufferedImage bufimage = new BufferedImage (img.geticonWidth (), img.geticOnheight (), BufferedImage.type_int_rgb);
int x, y;
int x1, y1;
JFrame JF;
Графика G;
String Str;
Цвет C;
int cr;
int cl [] [] = new int [1000] [1000];
ArrayList <Shape> shapes = new ArrayList <Shore> ();
Случайный случайный = new Random ();
int r;
int g;
int b;
Public PaintDemo (Graphics G, Jframe JF) {
this.jf = jf;
this.g = jf.getGraphics ();
}
@Override
public void mouseclicked (mouseevent e) {
// TODO Автогенерированный метод заглушка
}
@Override
public void mousepressed (mouseevent e) {
x = e.getx ();
y = e.gety ();
}
@Override
public void museereleaded (museevent e) {
x1 = e.getx ();
y1 = e.gety ();
setColor ();
if (str.equals ("нарисуйте круг") {
// paintoval ();
Форма формы = новая овальсхапа (x, y, x1, y1, c);
Shape.draw (g);
формы. Адд (форма);
}
if (str.equals ("Draw Line") {
// paintline ();
Форма формы = новый Lineshape (x, y, x1, y1, c);
Shape.draw (g);
формы. Адд (форма);
/*Файл f = новый файл ("d: //test.txt");
if (f == null) {
пытаться {
f. createnewfile ();
} catch (Exception e1) {
// Todo Auto Generated Catch Blach
e1.printstacktrace ();
}
}*/
}
}
public void Said -file (String Path, ArrayList <Shape> Formes) {
пытаться{
// Файл выходной поток
FileOutputStream fos = new FileOutputStream (path);
// Оберните выходной поток файла в поток базового типа записываемых
DataOutputStream dos = new DataOutputStream (FOS);
dos.writeint (shapes.size ()); // Количество цифр, записанных в очередь
// читать очередь
for (int i = 0; i <shapes.size (); i ++) {
// выслушать форму
Форма формы = фигуры.get (i);
byte type = shape.type;
if (type == 0) {// судить тип в соответствии с типом, если это прямая линия
System.out.println ("Start хранение строки");
dos.writebyte (type);
Lineshape Line = (Lineshape) Shape; // Captively Converting в линейный класс
// записать данные по прямым линиям;
int x = line.x;
int y = line.y;
int x1 = line.x1;
int y1 = line.y1;
Цвет цвета = line.color;
cr = color.getrgb ();
dos.writeint (x);
dos.writeint (y);
dos.writeint (x1);
dos.writeint (y1);
dos.writeint (Cr);
} else if (type == 1) {
dos.writebyte (type);
System.out.println («Начать хранение круга»);
Ovalshape oval = (ovalshape) форма; // панно конвертируется в класс круга
// записать данные по прямым линиям;
int x = oval.x;
int y = oval.y;
int x1 = oval.x1;
int y1 = oval.y1;
Цвет цвета = oval.color;
cr = color.getrgb ();
dos.writeint (x);
dos.writeint (y);
dos.writeint (x1);
dos.writeint (y1);
dos.writeint (Cr);
} else if (type == 2) {
dos.writebyte (type);
изображение PL = (изображение) форма;
System.out.println ("Начать хранение картин");
int width = pl.a;
int height = pl.b;
dos.writeint (ширина);
dos.writeint (высота);
for (int k = 0; k <ширина; k ++) {
for (int j = 0; j <height; j ++) {
int t = pl.cl [k] [j];
dos.writeint (t);
}
}
}
}
dos.flush ();
fos.close ();
} catch (Exception e) {
e.printstacktrace ();
}
}
public arraylist <shape> readfile (String Path) {
пытаться{
// Создать поток ввода объекта файла
FileInputStream fis = new FileInputStream (Path);
// Заверните потоки ввода файла в поток читаемых основных типов
DataInputStream dis = new DataInputStream (FIS);
// сначала прочитайте длину файла, то есть общее количество форм
int len = dis.readint ();
для (int i = 0; i <len; i ++) {
byte type = dis.readbyte ();
if (type == 0) {
int a = dis.readint ();
int b = dis.readint ();
int c = dis.readint ();
int d = dis.readint ();
Цвет f = новый цвет (dis.readint ());
Lineshape Line = New Lineshape (A, B, C, D, F);
// Читать настройки прямых линий
// Сохранить прямые линии в очередь
Shapes.Add (Line);
} else if (type == 1) {
int a = dis.readint ();
int b = dis.readint ();
int c = dis.readint ();
int d = dis.readint ();
Цвет f = новый цвет (dis.readint ());
System.out.println ("Начать кружок чтения");
OvalShape Oval = новый овальсхей (A, B, C, D, F);
Formes.Add (Oval);
} else if (type == 2) {
int a = dis.readint ();
int b = dis.readint ();
for (int k = 0; k <a; k ++) {
for (int j = 0; j <b; j ++) {
cl [k] [j] = dis.readint ();
}
}
Picture Pic = New Picture (A, B, CL);
Shapes.Add (PIC);
}
}} catch (Exception e) {
e.printstacktrace ();
}
вернуть формы;
}
@Override
public void MouseEndered (MouseEvent E) {
// TODO Автогенерированный метод заглушка
}
@Override
public void mouseexited (mouseevent e) {
// TODO Автогенерированный метод заглушка
}
public void setColor () {
R = random.nextint (255);
G = random.nextint (255);
B = random.nextint (255);
c = новый цвет (r, g, b);
}
/* public void paintline () {
setColor ();
g.drawline (x, y, x1, y1);
}
public void paintoval () {
setColor ();
G.Drawoval ((x+x1)/2, (y+y1)/2, (x1-x)/2, (y1-y)/2);
}
*/
@Override
public void actionperformed (actionEvent e) {
str = e.getActionCommand ();
jf.addmouseListener (это);
if (str.equals ("storage")) {
SaveFile ("d: //test.txt", формы);
}
if (str.equals ("open")) {
readfile ("d: //test.txt");
for (int i = 0; i <shapes.size (); i ++) {
Форма формы = фигуры.get (i);
if (shape.type == 0) {
System.out.println («Определите, что это тип круга»);
Lineshape Line = (Lineshape) форма;
line.draw (g);
} else if (shape.type == 1) {
System.out.println («Определите, что это тип круга»);
Овальсхап -овальная = (овальсхапа) форма;
oval.draw (g);
} else if (shape.type == 2) {
System.out.println («Подтвердите, что это тип изображения»);
изображение PL = (изображение) форма;
pl.draw (g);
}
}
}
if (str.equals ("picture")) {
Thread th = new Thread (new Runnable () {
public void run () {
while (true) {
пытаться{
Thread.sleep (30);
Graphics G1 = bufimage.getGraphics ();
g1.drawimage (img.getimage (), 0,0, null);
jf.getGraphics (). DrawMage (Bufimage, 100 100, NULL);
int width = bufimage.getwidth ();
int height = bufimage.getheight ();
for (int k = 0; k <ширина; k ++) {
for (int j = 0; j <height; j ++) {
int p = bufimage.getrgb (k, j);
cl [k] [j] = p;
}
}
изображение PE = новая картина (ширина, высота, CL);
Formes.Add (PE);
} catch (Exception e) {
e.printstacktrace ();
}
}
}});
th.start ();
}
}
}