如何使用图形方法尤其是绘制多边形方法绘制等边三角形。我的问题是,要制作一个等边三角形我需要平方根3/2和drawPolygon方法我只能使用int [],int [],int,编译器不会让我加倍,因为它的长度不同。
感谢任何帮助。
import java.awt.*;
public class Triangle extends Shape {
// Instance variables
private int leng;
// Constructor
public Triangle(int x, int y, Color color,
int leng) {
super(x, y, color);
this.leng=leng;
}
// Instance methods
public void draw(Graphics g) {
double[] Xcoord = { getX(), getX() + leng, getX() + leng / 2};
double[] Ycoord = { getY(), getY(), getY()*(1.0+ Math.sqrt(3) / (2.0))};
g.drawPolygon(Xcoord,Ycoord,3);
}
public int getHeight() {
return leng;
}
public int getWidth() {
return leng;
}
}
答案 0 :(得分:2)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Polygon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JRisk {
private JFrame mainMap;
private Polygon poly;
public JRisk() {
initComponents();
}
private void initComponents() {
mainMap = new JFrame();
mainMap.setResizable(false);
mainMap.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
int xPoly[] = {150, 250, 325, 375, 450, 275, 100};
int yPoly[] = {150, 100, 125, 225, 250, 375, 300};
poly = new Polygon(xPoly, yPoly, xPoly.length);
JPanel p = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.drawPolygon(poly);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
};
mainMap.add(p);
mainMap.pack();
mainMap.setVisible(true);
}
/**
* @param args
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new JRisk();
}
});
}
}
这是在谷歌搜索后从about drawing a Polygon in java找到的。