Java 为什么我不能用fillPolygon()绘制矩形
我正在学习Java图形。我试图画一些简单的数字。但是,我注意到以下代码无法正确绘制:Java 为什么我不能用fillPolygon()绘制矩形,java,swing,graphics,awt,Java,Swing,Graphics,Awt,我正在学习Java图形。我试图画一些简单的数字。但是,我注意到以下代码无法正确绘制: public class Draw extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); int[] xpoints = new int[] { 20, 50, 80 }; int[] ypoints = new int[] { 40, 10,
public class Draw extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int[] xpoints = new int[] { 20, 50, 80 };
int[] ypoints = new int[] { 40, 10, 40 };
g.fillPolygon(xpoints, ypoints, 3);
int[] recXp = new int[] { 20, 80, 20, 80 };
int[] recYp = new int[] { 50, 60, 50, 60 };
g.fillPolygon(recXp, recYp, 4);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
Draw panel = new Draw();
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
}
}
为了达到我想要的,我必须使用
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Draw extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
int[] xpoints = new int[] { 20, 50, 80 };
int[] ypoints = new int[] { 40, 10, 40 };
g.fillPolygon(xpoints, ypoints, 3);
g.fillRect(20, 50, 60, 10);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
Draw panel = new Draw();
frame.add(panel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
}
}
为什么会这样?我错过什么了吗?抱歉,如果这是一个微不足道的问题,我只是想更好地理解Java
int[] recXp = new int[] { 20, 80, 20, 80 };
int[] recYp = new int[] { 50, 60, 50, 60 };
您只有两组点
您需要4组不同的点。矩形的每个角一个
比如:
我把它改为int[]recXp=new int[]{20,80,80,20};int[]recYp=new int[]{50,50,60,60};它的显示正确,很抱歉这个愚蠢的问题:)@moe,同意c0der,有时使用方法会让我们感到困惑。您创建了一个很好的简单的测试方法,显示了您的尝试。我们很高兴为您提供帮助。