下面是用数组对画板上的图形进行存储
package 画板的重绘;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.JPanel;
/**
* 画图区域面板的实现类,该类继承自JPanel类
*
* @author Administrator
*
*/
public class DrawingPanel extends JPanel {
/**
* 构造方法
*/
public DrawingPanel() {
init();// 调用初始化面板的方法
}
// 实例化一个JPanel类的对象属性,用来获取画布
private JPanel panel = new JPanel(){
//方法重写
public void paint(Graphics g){
super.paint(g);
if(DrawingListener.a==false){
for(int i=0;i < array.length;i++){
for(int j =0;j<array[i].length;j++){
Color color = new Color(array[i][j]);
g.setColor(color);
g.drawLine(i, j, i, j);
}
}
}
}
};
//定义一个存画板上像素点的二维数组
public static int [][]array = new int [400][300];
/**
* 获取JPanel对象
*/
public JPanel getJPanel() {
return panel;
}
private void init() {
// 设置DrawingPanel的布局为流式布局布局
this.setLayout(new FlowLayout(FlowLayout.LEFT));
this.setBackground(Color.LIGHT_GRAY);
panel.setBackground(Color.WHITE);
panel.setPreferredSize(new Dimension(400, 300));
// 将panel添加到DrawingPanel上
this.add(panel);
}
}
数组列表
/**
* 数组队列
*
*/
public class MyArrayList<E> {
private Object[] array;// 属性数组
private int size = 0;// 记录元素总数的属性
/**
* 构造方法
*/
public MyArrayList() {
array = new Object[0];// 实例化一个数组
}
/**
* 构造方法
*
* @param length表示数组队列的长度
*/
public MyArrayList(int length) {
array = new Object[length];// 实例化一个数组
}
/**
* 定义添加元素的方法
*
* @param e要添加到数组队列中的元素
*/
public void add(E e) {
// 实例化一个新数组,长度是size+1
Object[] newarray = new Object[size + 1];
// 将array数组的内容添加到newarray数组中
for (int i = 0; i < size; i++) {
newarray[i] = array[i];
}
// 将新元素添加到newarray数组的最后一个位置
newarray[size] = e;
// size要加1
size++;
// 将newarray数组名中存储的地址赋给array
array = newarray;
}
/**
* 定义删除指定索引位置元素的方法
*
* @param index要被删除的元素下标
* @return 返回删除是否成功 ,如果返回true表示删除成功,返回false表示删除失败
*/
public boolean remove(int index) {
if (index >= 0 && index < size) {
// 实例化一个新数组,长度是size-1
Object[] newarray = new Object[size - 1];
// 将array数组的内容添加到newarray数组中
for (int i = 0; i < index; i++) {
newarray[i] = array[i];
}
for (int i = index+1; i < size; i++) {
newarray[i-1] = array[i];
}
// size要减1
size--;
// 将newarray数组名中存储的地址赋给array
array = newarray;
return true;
}
return false;
}
/**
* 获取数组队列的元素总数
* @return 返回size属性值
*/
public int size(){
return size;
}
/**
* 获取指定索引位置的元素
* @param index索引位置
* @return 如果返回null,则表示索引位置不存在;如果存在则返回对应的元素
*/
public E get(int index){
if(index >= 0 && index < size){
return (E)array[index];
}
return null;
}
}