java编程构建简单画图板4——重绘功能的完善

来源:互联网 发布:复制软件手机版 编辑:程序博客网 时间:2024/06/05 19:24

通过构建自定义队列存储图形的相关信息,利用paint方法利用存储信息绘制图形是重绘功能的实现方法,但由于不同图形的主要信息个数不同,图形信息的存储、调用、方法实现会比较麻烦,程序会更复杂、易出错,解决这一问题可以借助面向对象编程的思维,定义Shape抽象类以及继承自Shape抽象类的Line、Rect、Oval等基本图形子类,利用Shape抽象类及其子类通过构建图形对象实现图形信息的存储和调用,对于其他较复杂图形的实现也更方便。通过这种方式不仅可以有效地实现重绘功能,还使程序本身更加简洁、易读。


Shape抽象类:   

package com.huaxin.version4;

import java.awt.Color;
import java.awt.Graphics;


public abstract class Shape {
 public int x1,y1,x2,y2;
 public Color color;
 public Shape(int x1, int y1, int x2, int y2, Color color,int width) {
  this.x1 = x1;
  this.y1 = y1;
  this.x2 = x2;
  this.y2 = y2;
  this.color = color;.

  this.width=width;
 }
 public abstract void draw(Graphics g);
}

 

Line类:

package com.huaxin.version4;

import java.awt.Color;
import java.awt.Graphics;

public class Line extends Shape{

 public Line(int x1,int y1,int x2,int y2,Color color,int width){
  super(x1,y1,x2,y2,color,width);
 }
 public void draw(Graphics g){
  g.setColor(color);
  g.drawLine(x1,y1,x2,y2);
 }
}

 

矩形Rect类:

package com.huaxin.version4;

import java.awt.Color;
import java.awt.Graphics;


public class Rect extends Shape{
 public Rect(int x1,int y1,int x2,int y2,Color color,int width){
  super(x1,y1,x2,y2,color,width);
 }
 public void draw(Graphics g){
  g.setColor(color);
  g.drawRect(Math.min(x1,x2),Math.min(y1,y2),Math.abs(x2-x1),Math.abs(y2-y1));
 }
}

椭圆Oval类:

package com.huaxin.version4;

import java.awt.Color;
import java.awt.Graphics;

public class Oval extends Shape{
 
 public Oval(int x1,int y1,int x2,int y2,Color color,int widh){
  super(x1,y1,x2,y2,color,width);
 }
 
 public void draw(Graphics g){
  g.setColor(color);
  g.drawOval(Math.min(x1,x2),Math.min(y1,y2),Math.abs(x2-x1),Math.abs(y2-y1));
 }
}

 

Paint方法:

package com.huaxin.version4;

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JPanel;

import java.awt.BasicStroke;


public class DrawPanel extends JPanel{
 private MyList list;
 public void setList(MyList list){
  this.list = list;
 }
 public DrawPanel(){
  setPanel();
 }
 public void setPanel(){
  
   this.setBackground(Color.white);
 }

public void paint(Graphics g){
  
  super.paint(g);
  for(int i=0;i<mylist.getLength();i++){
   if(mylist.get(i).width==1){
    BasicStroke basicstroke1=new BasicStroke(mylist.get(i).width);
       Graphics2D gr=(Graphics2D) g;
       gr.setStroke(basicstroke1);                 
    mylist.get(i).draw(gr);
                        
      }
   if(mylist.get(i).width==5){
    BasicStroke basicstroke2=new BasicStroke(mylist.get(i).width);
       Graphics2D gr=(Graphics2D) g;
       gr.setStroke(basicstroke2);
       mylist.get(i).draw(gr);
   }
  }
 }
}



 

 

0 0