编辑:澄清一下,我的要求之一是使用单个数组。
我在将多个变量存储到数组中的单个元素时遇到麻烦。我们正在创建一个非常简单的程序来模仿Microsoft Paint。要求之一是将我绘制的每个元素存储到数组中,以便每次将窗口最小化然后重新显示时,“ paint”方法都会重新绘制图形。这是要求
我们假设数组的最大大小为20。每个元素应包含5个变量:
这是我的数组类代码:
class storeDraws {
final int MAXSIZE = 20;
static int S[];
static int n; //number of draws user makes
static char shape;
static double px, py, w, h;
storeDraws () {
S = new int [MAXSIZE];
n = 0;
shape = 'l';
px = 0;
py = 0;
w = 0;
h = 0;
}
}
我已经阅读了一些可以将数组输入为的地方(使用mouseReleased(MouseEvent e)方法):
storeDraws[] input = new storeDraws{value, value, value, value, value};
但是我认为这与我尝试使用“绘制”方法重绘形状的方式不起作用。我以为我可以使用S [n] =(字符,双精度,双精度,双精度,双精度,双精度)的标准格式通过它,但是我得到警告,这是非法的。
编辑上午8:30,我已开始执行此部分。在我的课堂上,现在是我的代码。
class storeDraws {
static char shape;
static int px, py, w, h;
storeDraws () {
shape = 'l';
px = 0;
py = 0;
w = 0;
h = 0;
}
}
然后,我在DrawPanel类中声明了这一点:
private storeDraws[] store = new storeDraws[20];
private int n = 0;
和DrawPanel的mouseReleased方法:
public void mouseReleased(MouseEvent e) {
if (drawShape == "line") {
store[n].shape = 'l';
store[n].px = p1.x;
store[n].py = p1.y;
store[n].w = p3.x;
store[n].h = p3.y;
n++;
}
和油漆:
public void paint(Graphics g) {
for (int i = 0; i < n; i++) {
if (store[i].shape == 'l')
g.drawLine(store[n].px, store[n].py, store[n].w, store[n].h);
但是,如果我绘制6条线,它只会重画最后一行。
我认为您需要分离一些所需的功能。您可以为每个元素都有一个类,然后将该类的实例存储在DrawingElement对象的数组中。
所以你会做这样的事情:
DrawingElement[] drawing = new DrawingElement[20];
DrawingElement circle = new DrawingElement('c', 10, 10, 10, 10);
DrawingElement rect = new DrawingElement('r', 20, 10, 10, 10);
drawing[0] = circle;
drawing[1] = rect;
注意:如果需要获取数组中对象的数量(n
代码中的变量),则可能需要使用链表(具有size()
方法)的某些实现,并在添加元素时进行一些检查以确保您添加的最大值不超过20。
LinkedList的示例:
LinkedList<DrawingElement> drawing = new LinkedList<DrawingElement>();
DrawingElement circle = new DrawingElement('c', 10, 10, 10, 10);
DrawingElement rect = new DrawingElement('r', 20, 10, 10, 10);
drawing.add(circle);
drawing.add(rect);
int n = drawing.size(); //will be 2
绘图元素类:
public class DrawingElement
{
char shape;
double px, py, w, h;
public DrawingElement(char shape, double px, double py, double w, double h)
{
this.shape = shape;
this.px = px;
this.py = py;
this.w = w;
this.h = h;
}
//Add getters and setters (accessors and mutators) for class variables
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句