Neutralise
Neutralise

Reputation: 329

Simple line drawing

I am trying to make a simple line drawing program in java, I am storing each pixel on the screen in an array for drawing. When a user drags the mouse, each pixel is set to 1, then I try to iterate through and draw a line between each pair of points. However it is not drawing properly, can someone see the problem here?

public void mouseDragged(MouseEvent m) {
    screen[m.getX()][m.getY()] = 1;
    drawOffscreen();
}

public void mouseReleased(MouseEvent e) {
    end[e.getX()][e.getY()] = true;     
}


int prex = -1;
int prey = -1;
public void paint(Graphics g) {
    g.drawImage(offscreen, 0, 0, null);     
    for (int x = 0; x < screen.length; x++){
        for (int y = 0; y < screen[0].length; y++){
            if(screen[x][y] == 1){
                if (prex != -1 && prey != -1 && !end[x][y]){
                    g.drawLine(prex, prey, x, y);                                               
                }
                prex = x;
                prey = y;
            }
        }
    }

}

Upvotes: 0

Views: 296

Answers (1)

Adrian Shum
Adrian Shum

Reputation: 40036

(I think it is a homework? if so, please tag it as homework)

I bet no one will clearly know what do u mean by "not drawing correctly". Anyway, one of the problem I can see.

I bet you are storing only 1 line. However the way you store and draw is problematic.

You stored a the coordinates that your mouse "passed" by marking the coordinate on the "virtual screen". However, when you draw that on screen, you are not following the order the mouse passed. Instead, you are drawing lines in the order from top to down, left to right, which is just giving you a mess.

You may consider storing a list of coordinate, and when you paint, you draw according to the coordinate.

Pseudo-code:

class Coordinate {  // there are some class in Java that already does that, 
                    //leave it to you to find out  :)
  int x;
  int y;
}

List<Coordinate> theOnlyLine=....;
public void mouseDragged(MouseEvent m) {
    theOnlyLine.add(new Coordinate(m.getX(), m.getY());
}

public void mouseReleased(MouseEvent e) {
    theOnlyLine.add(new Coordinate(m.getX(), m.getY());
}

public void paint(Graphics g) {

  int prevX = -1;
  int prevY = -1;
  for (Coordinate coordinate : theOnlyLine) {
    if (prevX > 0 && prevY > 0) {
      g.drawLine(prevX, prevY, coordinate.getX(), coordinate.getY());
    }
    prevX = coordinate.getX();
    prevY = coordinate.getY();
  }
}

Upvotes: 2

Related Questions