我正在做一个程序,其中包含在一个数组中的 8 个形状,当您单击鼠标时将显示这些形状。我是 Java 新手,对事件处理程序和侦听器不太熟悉。
我试图使形状出现在框架内单击鼠标的位置,但我遇到了麻烦,因为每个形状的构造函数都使用 2 Points 作为其参数。
这是代码中的一个示例:
import MyLibs.Circle;
import MyLibs.Rectangle;
import MyLibs.Shape;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
public class DrawInScreenOnClickTest extends javax.swing.JFrame {
private Image dbImage;
Shape[] sh = new Shape[] {
new Circle(new Point(50, 60), new Point(130, 180)),
new Rectangle(new Point(50, 200), new Point(150, 350)),
new Circle(new Point(200, 300), new Point(350, 350)),
new Rectangle(new Point(100, 100), new Point(250, 250)),
new Circle(new Point(150, 150), new Point(300, 300)),
new Circle(new Point(200, 200), new Point(450, 500)),
new Rectangle(new Point(300, 300), new Point(550, 550)),
new Circle(new Point(150, 150), new Point(320, 320))
};
Color[] colors = new Color[] {
Color.cyan, Color.green, Color.red, Color.blue, Color.magenta, Color.orange
};
Random random = new Random();
int i = 0;
Shape shape;
boolean first = true;
public DrawInScreenOnClickTest() {
initComponents();
}
private void formMouseClicked(java.awt.event.MouseEvent evt) {
repaint();
}
public class Mouse extends MouseAdapter {
@Override
public void mousePressed(MouseEvent e) {
int x = e.getX();
int y = e.getY();
}
}
public void paint(Graphics g) {
if (first == true) {
first = false;
} else {
int shapeColor = random.nextInt(6);
Shape shape = sh[i]; //calls shapes array
shape.setColor(colors[shapeColor]); //call colors array random
shape.drawShape(g); //display shape
if (i == 4) {
i = 0;
} else
i++;
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new DrawInScreenOnClickTest().setVisible(true);
}
});
}
}