swing怎么画三角形
已知一个三角形的底和高,也就是知道了面积,不管画在window的什么位置,怎么画出来?
public abstract void fillPolygon(int[] xPoints,
int[] yPoints,
int nPoints)
这个方法么? 有谁能给写个小例子么?谢谢了。
------最佳解决方案--------------------方法一:
package test1;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestA {
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setContentPane(new MyPanelA());
jf.setSize(new Dimension(300,300));
jf.setVisible(true);
}
}
class MyPanelA extends JPanel{
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
int[] yPoints = {10,30,20};
int[] xPoints = {10,10,30};
int nPoints = 3;
g2.drawPolygon(xPoints, yPoints, nPoints);
}
}
方法二:
package test1;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestB {
public static void main(String[] args) {
JFrame jf = new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setContentPane(new MyPanelB());
jf.setSize(new Dimension(300,300));
jf.setVisible(true);
}
}
class MyPanelB extends JPanel{
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.drawLine(10, 10, 10, 30);
g2.drawLine(10, 30, 30, 20);
g2.drawLine(30, 20, 10, 10);
}
}
------其他解决方案--------------------至少有两种方法,一直画直线的
Point p1;
Point p2;
Point p3;
g.drawLine(p1.x, p1.y, p2.x, p2.y);
g.drawLine(p2.x, p2.y, p3.x, p3.y);
g.drawLine(p3.x, p3.y, p1.x, p1.y);
另外一种利用Swing 2D多边形API
int[] xPoints = {100, 100, 200};
int[] yPoints = {100, 200, 200};
g.drawPolygon(xPoints, yPoints, 3);
------其他解决方案--------------------知道三角形的底和高,这样的三角形有无数多个
------其他解决方案--------------------学习了楼主
------其他解决方案--------------------public abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)
主要是三个参数弄懂了就会用了,xPoints和yPoints的值是一一对应的,代表x、y坐标的集合,