Search code examples
javaswingjframejpanelpaintcomponent

Using PaintComponent to draw outside of Panel


Hey guys Iam new here and thus i apologies in advance for my vague Question. I have a school Project to finish, which goal it is to create a fully working Paint Programm. We were given 3 Classes. Oval, Line and Polygon. These Classes all work mostly the same with the main difference being the form they draw. One of those classes looks like this:

public class Oval extends Drawable{
    private int x1,y1,x2,y2;
    private Color c;
    private JFrame f;
/**
* Constructor of the Oval Class 
* Initialises the attributes of this Class
*
* @return void
*/
public Oval(int X, int Y, int width, int height, Color c){
    this.x1 = x1;
    this.y1= y1;
    this.x2 = x2;
    this.y2 = y2;
    this.c = c;
}
/**
* Draws an Oval based on the Values x1,y1,x2,y2
*
* @return void
*/
@Override
public void draw(Graphics g) {
    g.setColor(c);
    g.drawOval(x1, y1, x2, y2);
}
}

Now my Problem is that I have no idea how to call this class from my Panel. When i try to call draw(...) from my JPanel within the PaintComponent Method it does absolutely nothing. Here is my JPanel class which I DID add to my JFrame fyi.

public class PaintPanel extends JPanel {
    private PaintFrame f;
public PaintPanel(PaintFrame f){
    this.f = f;
}
@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Oval o = new Oval(100, 100, 50, 50, new Color(127, 184, 255), f);
    o.draw(g);
}
}

Dont mind the Frame in the Parameters this is for a clone method inside the oval, line and polygon Classes to avoid OutOfBounce Drawings.

Now for my Frame:

public class PaintFrame extends JFrame{
    private PaintPanel pp;
public PaintFrame(){
    pp = new PaintPanel(this);

    this.setSize(500, 500);
    this.setTitle("Paint");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setContentPane(pp);
    this.setVisible(true);
}
}

So this is pretty much it I guess. I would just like to make this work since this is pretty much the fundemental part of the whole project. Thanks in advance for any help and if you have any tips on making my next Question a bit better and more precise feel free to criticise :)


Solution

  • It looks like your coordinates for your Oval are not being properly set in your Oval constructor. What you need to do is calculate them using the initial x and y positions and the values of width and height like so:

    this.x1 = X;
    this.y1= Y;
    this.x2 = x+width;
    this.y2 = y+height;