Lets say I have a JPanel and an object called ball inside of it, instead of creating gets so the JPanel can draw the ball image I would like the ball object to draw itself on the JPanel.

Is it possible?

Thanks :D.

Recommended Answers

All 4 Replies

By draw itself do you mean using a method inside its own class to draw on the JPanel in another class?

By draw itself do you mean using a method inside its own class to draw on the JPanel in another class?

Yes xD, I wanted to pass a Graphics object to the JPanel using a method inside a Ball oject, but I saw that Graphics is abstract.

Inside the Ball class, import your java.awt.Graphics2D. Then create a method that takes a Graphics2D/Graphics paramater. Then just write the code to draw your ball in that method.

import java.awt.Graphics2D;
public void drawBall(Graphics2D g){
g.fillOval(...);
}

Then, in your paintComponent/paint method on your JPanel, call the method using the paints Graphics object. i.e. ball.drawBall(g2d);

Inside the Ball class, import your java.awt.Graphics2D. Then create a method that takes a Graphics2D/Graphics paramater. Then just write the code to draw your ball in that method.

import java.awt.Graphics2D;
public void drawBall(Graphics2D g){
g.fillOval(...);
}

Then, in your paintComponent/paint method on your JPanel, call the method using the paints Graphics object. i.e. ball.drawBall(g2d);

Thank you xD

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.