Search code examples
javaswingpaintcomponentgraphics2d

How do I flip the drawRect so that it draws up?


I have some code here, and it graphs exponentially but, it graphs the wrong way. negative exponential growth. Here is my code, I'm trying to flip it up. I'll be working on it, but if you have an answer please tell me.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Graphics extends JPanel{   
    public static void main(String[] args) {    
        JFrame f =new JFrame ("Function");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Graphics g = new Graphics();
        f.add(g);
        f.setSize(700, 700);
        f.setVisible(true); 
}
public void paintComponent (java.awt.Graphics g) {
    super.paintComponent(g);
    int i = this.getWidth()-this.getWidth() + 5;

    int xoffset = this.getWidth()/2;
    int yoffset = this.getHeight()/2;

     for (int x = 0 ; x < 20 ; x++){
         g.setColor(Color.BLACK);
         this.setBackground(Color.WHITE);
         int p = x*x;
         g.fillRect(i+xoffset,10+yoffset,5,p);
         i = i + 10;
      } 
    }
  }

Does anyone know how to fix this?


Solution

  • Change the x/y position at where the rectangle starts to draw from (it always draws right/down)

    So instead of

    g.fillRect(i+xoffset,10+yoffset,5,p);
    

    you could have...

    g.fillRect(i + xoffset, 10 + yoffset - p, 5, p);
    

    Onwards and upwards

    I've got no idea what your intentions are for int i = this.getWidth()-this.getWidth() + 5;, but clearly makes no sense (width - width == 0?)