0

我试图演示 Bresenham 的线算法,而不是不太复杂的方法。我对编程很陌生,我确信我的问题是基本的,但是解决方案和解释将非常有帮助。谢谢!

第一个代码块直接来自我的书。

import java.awt.*;
import javax.swing.*;

public class lines extends JPanel {
    int deltaX;
    int deltaY;
    int DY2;
    int DX2;
    int Di;

    public void basic(int x1, int y1, int x2, int y2, Graphics
    g){
        int deltaX = x2-x1;
        int deltaY = y2-y1;
        float m = (float)deltaY/(float)deltaX;
        float c = y1 - (m*x1);
        for (int x=x1; x<x2; x++){
            float floatY = (m*x) + c;
            int y = Math.round(floatY);
            g.drawLine(x,y,x,y);
        }
    }

   public void brz(int x1, int y1, int x2, int y2,
    Graphics g){
    deltaX = x2-x1;
    deltaY = y2-y1;
    DY2 = 2* deltaY;
    DX2 = 2* deltaX;
    Di = DY2 - deltaX;
    int x = x1;
    int y = y1;
    int prevy;
    while (x<x2) {
        x++;
        prevy = y;
        if (Di > 0){
            y++;
        }
        g.drawLine(x,y,x,y);
        Di = Di + DY2 - (DX2 * (y - prevy));
    }
}

public void paintComponent(Graphics g){
    basic(10,10,40,30,g);
    basic(10,10,40,90,g);
    brz(50,50,150,60,g);
    brz(50,50,150,120,g);
    brz(50,50,150,140,g);
}

它告诉我我需要一个主类,所以我添加了这一点:

public static void main(String[] args) {
     paintComponent(Graphics g);
}

现在它给了我这个:

lines.java:15: ')' expected paintComponent(Graphics g);

lines.java:15: illegal start of expression paintComponent(Graphics g);

4

3 回答 3

2

在 main 内部将行更改为

    JFrame f = new JFrame("Swing Paint ");

    f.add(new YourPanelName());
    f.pack();
    f.setVisible(true);

然后做一些 j2ee swings api 研究:)

于 2013-09-13T22:57:41.583 回答
0

您在将类型传递给方法时声明类型。更改paintComponent(Graphics g);paintComponent(g);第 15 行。您仅在接受参数或声明字段/变量时声明类型。

于 2013-09-13T22:58:18.860 回答
0

您必须先构造对象,然后再将其放入方法中。

paintComponent(Graphics g);-
paintComponent(g);-

public static void main(String[] args) {
    Graphics g = new Graphics(); 
    paintComponent(g);
}

在此处阅读有关图形类的更多信息!

于 2013-09-13T23:03:02.947 回答