0
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?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user3244786
  • 19
  • 1
  • 4
  • Note: `public void paint(Graphics g) { ..` Since this is a `JComponent`, the correct method to override is `paintComponent` and we should always call the super method first to ensure that the BG is painted. So it would better be `protected void paintComponent(Graphics g) { super.paintComponent(g); ..` What is written above makes me think this code comes from some other source. Given the snippet overrides the wrong method and fails to paint the BG, I suggest to **find a new source of code examples.** – Andrew Thompson Apr 03 '15 at 06:47

1 Answers1

4

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.

Community
  • 1
  • 1
k_g
  • 4,333
  • 2
  • 25
  • 40