我寫了一個代碼來繪製一個六角形。首先我使用這個公式繪製6點: (x + r * cos(i * 2 * pi/6),y + r * sin(i * 2 * pi/6)) 然後我繪製這些點後i試圖使用Bresnham的算法繪製線,我已經在一個方法中實現它之間的點之間進行匹配。 不幸的是,代碼無法成功工作,我得到這個而不是六角形。我認爲Bresnham的算法實現存在錯誤。此外,我試圖單獨繪製每個點,但它不會工作。 如果有人能幫助我?繪製六角形使用Java錯誤
而且這是我的代碼:
package javaapplication1;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.geom.Line2D;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class LinesDrawingExample extends JFrame {
public LinesDrawingExample() {
super("Lines Drawing Demo");
//Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
setSize(500, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
void drawLines(Graphics g , int x,int y) {
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.drawLine(x, y, x,y);
//g2d.draw(new Line2D.Double(59.2d, 99.8d, 419.1d, 99.8d));
// g2d.draw(new Line2D.Float(21.50f, 132.50f, 459.50f, 132.50f));
}
public void getvalue(Graphics g,double x1,double y1 ,double x2,double y2){
int x=(int)x1;
int y=(int)y1;
int deltax=(int)x2-(int)x1;
int deltay=(int)y2-(int)y1;
int twodeltay=2*deltay;
int var1=twodeltay-(2*deltax);
int p=twodeltay-deltax;
drawLines(g,x,y);
while(x<x2)
{
drawLines(g,x,y);
if(p>0)
{
y=y+1;
p=p+twodeltay-(2*deltax);
}
else
{
p=p+twodeltay;
}
x++;
}
}
public void paint(Graphics g) {
super.paint(g);
double r=50;
double pi=3.14;
int [] xval =new int [6];
int [] yval=new int [6];
int x=100,y=100;
for(int i=0; i<6; i++) {
getvalue(g,x + r*cos(i*2*pi/6), y + r*sin(i*2*pi/6),x + r*cos(i*2*pi/6),y + r*cos(i*2*pi/6));
xval[i]=(int)(x + r*cos(i*2*pi/6));
yval[i]=(int)(y + r*sin(i*2*pi/6));
}
getvalue(g,xval[4],yval[4],xval[5],yval[5]);
getvalue(g,xval[2],yval[2],xval[1],yval[1]);
getvalue(g,xval[3],yval[3],xval[2],yval[2]);
getvalue(g,xval[3],yval[3],xval[3],yval[3]);
getvalue(g,xval[4],yval[4],xval[4],yval[4]);
getvalue(g,xval[5],yval[5],xval[5],yval[5]);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new LinesDrawingExample().setVisible(true);
}
});
}
}
覆蓋'paintComponent(g)',而不是'paint(g)'。 – user3437460
@ user3437460我試圖覆蓋paintComponent(g),但它不包含在要覆蓋的方法中。 –
看看我的解決方案。 – user3437460