编辑:澄清一下,我的要求之一是使用单个数组。
我无法将多个变量存储到数组中的单个元素。我们正在创建一个非常简单的程序来模仿 Microsoft Paint。要求之一是将我绘制的每个元素存储到一个数组中,以便每次最小化窗口然后重新显示时“paint”方法都会重新绘制图形。要求如下
我们假设数组的最大大小为 20。 每个元素应包含 5 个变量:
- 字符形状(l 表示直线,r 表示矩形,c 表示圆形)
- 起始x值
- 起始 y 值
- 宽度(矩形)、或结束 x(直线)或半径(圆形)
- 高度(矩形),或结束 y(直线),或半径(圆形)
这是我的数组类代码:
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};
但我认为这不适用于我尝试使用“paint”方法重绘形状的操作。我以为我可以使用标准格式 S[n] = (char, double, double, double, double) 来传递它,但我收到警告说这是非法的。
编辑上午 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<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
}
关于java - 单个数组在每个元素中存储多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30052235/