Chris Mowbray
Chris Mowbray

Reputation: 295

Graph Axis issue

I am creating line graph using outputs from a thread, the threads are simulations of incoming and outgoing bill that run over a course of 52 seconds and this will be dipicted on a line graph as shown below to show the bank balance over the 52 seconds!

The problem is I cannot seem to get the Y Axis calculating properly. The code below show output the red marker at the top right hand side of the axis but it does not

enter image description here

public void paintComponent(Graphics g) {

    int y = 10000; // balance
    int x = 52 ; // weeks
    int prevX, prevY;
    int maxX = 52;
    int maxY = 10000;

    int Xleft = 200;
    int Xright = 900;
    int Ytop = 50;  
    int Ybottom = 330;// defining axis

    Graphics2D g2 = (Graphics2D) g;
    super.paintComponent(g2);
    g2.setColor(Color.BLUE);

    BasicStroke pen = new BasicStroke(4F);
    g2.setStroke(pen);

    g2.drawLine(Xleft,Ytop,Xleft,Ybottom);
    g2.drawLine(Xleft,280,Xright,280);

    Font f = new Font("Serif", Font.BOLD, 14);
    g2.setFont(f); 
    g2.drawString("Account Balance (£)", 35, 200);
    g2.drawString("Elapsed Time (Weeks)", 475, 340);



//retrieve values from your model for the declared variables     

//calculate the coords  line on the canvas

double balance = (((double)y / maxY) * Y_AXIS_LENGTH) - Y_AXIS_OFFSET; //floating point arithmetic
double weeks = (((double)x / maxX) * X_AXIS_LENGTH) + X_AXIS_OFFSET;

int xPos = (int) Math.round (weeks);
int yPos = (int)Math.round(balance); // changing back to int to be used in drawing oval

g2.setColor(Color.RED);
g.drawOval( xPos, yPos, 2, 2);
System.out.println(xPos + "  " + yPos);

}

Upvotes: 1

Views: 221

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Shouldn't this:

double balance = (((double)y / maxY) * Y_AXIS_LENGTH) - Y_AXIS_OFFSET;

be this?

double balance = Y_AXIS_OFFSET - (((double)y / maxY) * Y_AXIS_LENGTH);

Upvotes: 2

Related Questions