Adam Feoras
Adam Feoras

Reputation: 47

How can I get these java line algorithms working?

I'm trying to demonstrate Bresenham's line algorithm as opposed to a less sophisticated approach. I'm very new to programming and I'm sure my problems are elementary, but a solution and an explanation would be hugely helpful. Thanks!

This first block of code comes straight out of my book.

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);
}

It told me I need a main class, so I added this bit:

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

Now it's giving me this:

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

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

Upvotes: 0

Views: 790

Answers (3)

Akhilesh Singh
Akhilesh Singh

Reputation: 2586

inside main change the line to

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

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

then do some j2ee swings api study :)

Upvotes: 2

progrenhard
progrenhard

Reputation: 2363

You have to construct the object before putting it into the method.

paintComponent(Graphics g); - NO
paintComponent(g); - YES

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

Read more about the graphics class here!

Upvotes: 0

nanofarad
nanofarad

Reputation: 41281

You're declaring the type when passing it into a method. Change paintComponent(Graphics g); to paintComponent(g); on what appears to be line 15. You only declare a type when accepting arguments or declaring fields/variables.

Upvotes: 0

Related Questions