下面的代码是在小程序中显示一个三角形。但它对我不起作用。如果我通过Graphics g
而不是Graphics2D g
那么它工作正常。但我想知道我在使用时犯了什么错误Graphics g
。我是 Java 新手,从一些在线教程中学习。所以请更正我的程序并告诉我我在做什么错误。
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Vehicle extends JFrame {
final int WIDTH = 900;
int HEIGHT = 650;
public void init() {
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void paint(Graphics2D g) {
Graphics2D g2 = (Graphics2D) g;
Dimension d = getSize();
System.out.println(d);
int[] yPoints={150,250,250};
int[] xPoints={200,150,250};
g2.setColor(Color.green);
g2.drawPolygon(xPoints, yPoints, 3);
g2.drawRect(100, 100, 100, 100);
g2.setColor(Color.red);
g2.fillPolygon(xPoints, yPoints, 3);
}
public static void main(String[] args) {
Vehicle v= new Vehicle();
v.init();
}
}