Why does a short line segment appear instead of a full line graph?

103 Views Asked by At

My custom Canvas extends Canvas, and overrides the paint() method as below

@Override
public void paint(Graphics g) {

    Rectangle bounds = getBounds();

    g.translate(0, (bounds.y + bounds.height) / 2);

    int maxX = (int) bounds.getMaxX();

    g.drawLine(currX, currY, currX + 5, m_nextY);

    currX = currX > maxX ? maxX : currX + 5;
    currY = m_nextY;

    if (currX >= maxX) {
        currX = 0;
    }

}

int currX = 0;
int currY = 0;
int m_nextY;

public void setNextY(int pNext) {
    m_nextY = pNext;
}

The program entry-point runs a loop to retrieve random numbers which are scaled and set the location for the Y coordinate like this

java.util.Random engine = new Random();

while (Thread.currentThread().isAlive()) {
        myCanvas.setNextY((int) (engine.nextFloat() * -15f));
        myCanvas.paint(getGraphics());
        try {
            Thread.sleep(300);
        } catch (InterruptedException ex) {
         // Balderdash!
        }

    }

The expected output here should have been a line-graph. What appears instead is a single short segment with varying position and attitude.

What am I doing wrong here?

1

There are 1 best solutions below

1
On
  1. You normally never call paint() from your code. paint() will be called from the AWT framework. So your loop should go into the paint() method.

  2. What is engine ?