我正在尝试做一个关于事件侦听器的练习。为了绘制三角形,我使用了drawPolygon方法,但我不知道如何将其添加到buttonListener中以执行actionListener。这是代码的一部分:
public class Triangle extends Figure {
int x[];
int y[];
int n;
Triangle(boolean f, Color c, int x, int y, int n) {
super(f, c, x, y);
int xPoints[];
int yPoints[];
int nPoints[];
}
@Override
public void drawMySelf(Graphics g) {
int xPoints[] = {80, 150, 80};
int yPoints[] = {80, 150, 150};
int nPoints = 3;
Polygon P = new Polygon(x, y, n);
if (filled)
g.fillPolygon(P);
else g.drawPolygon(P);
}
}
@Override
public void actionPerformed(ActionEvent e) {
String kommando = e.getActionCommand();
int width = drawPanel.getWidth();
int heigth = drawPanel.getHeight();
if (kommando.equals("Cercle")) {
theFigures.add(new Circle(false, Color.BLUE, 20, 20, 50));
} else if (kommando.equals("Rektangle")) {
theFigures.add(new Rectangle(false, Color.BLACK, 300, 100,
150, 100));
} else if (kommando.equals("Triangele")) {
theFigures.add(___my problem is here___);
} else if (kommando.equals("Cercle rempli")) {
theFigures.add(new Circle(true, Color.YELLOW, 50, 100, 100));
} else if (kommando.equals("Rektangle rempli")) {
theFigures.add(new Rectangle(true, Color.GREEN, 500, 50,
100, 250));
}
首先,您必须创建一些按钮(用于圆形,矩形等),并通过setActionCommand方法配置它们。然后将带有button.addActionListener的actionListener添加到其中。我认为这篇文章会对你有所帮助。