Reputation: 19
public void paint(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fillOval(0, 0, 30, 30);
g2d.drawOval(0, 50, 30, 30);
g2d.fillRect(50, 0, 30, 30);
g2d.drawRect(50, 50, 30, 30);
g2d.draw(new Ellipse2D.Double(0, 100, 30, 30));
}
Well, I am new to JPanel
class and I have slight confusion. g
is an object of Graphics
class. So, what does (Graphics2D) g
mean as in this line g
seems as if it is a method and not an object? Further, can anyone tell me why Graphics2D
class cannot be instantiated?
Upvotes: 0
Views: 5695
Reputation: 4464
g
is a variable, not a method. It is declared in the method declaration because it is a parameter of the method (i.e., it needs to be passed whenever the function is called).
The (Graphics2D)
cast allows you to treat g
as a Graphics2D
object. See here for more information on casts.
You cannot initiate Graphics2D
because it is an abstract class, meaning that it has some methods that are specific to implementation.
Upvotes: 4