Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Initializing Graphics (java)?

I posted earlier for help on GUI (I'm a beginner to java and GUI) and have been having trouble just getting some simple graphics drawn onto a screen. Before the problem was that apparently I was not initializing the Graphics (I'd be given a nullpointer exception) but when I added "= new Graphics();" to the program below I'm not given an error that it cannot instantiate type Graphics. Here's the class to draw:

public class dots extends JComponent

{

private int pwidth = 400;

private int pheight = 500;

Graphics dbg = new Graphics();

public dots()

{

draw(dbg);

}

public void draw(Graphics g)

{

g.setColor(Color.WHITE);

g.fillRect(0,0, pwidth, pheight);

g.fillOval(50,50, 25, 25);

}

}

and here's the class to run it:

public class dotshower extends JPanel

{

public static void main (String args[])

{

dots dotter = new dots();

JPanel p = new JPanel();

p.add(dotter);

}

}

Any help on solving this issue / helping me understand what I'm doing wrong is greatly appreciated. I've tried so many different things and nothing seems to be working.

3 Answers

Relevance
  • Anonymous
    5 years ago

    So basically, you want to draw something using Graphics and then display it on a JPanel? I think you should make a separate class for drawing the graphics. This class would extend JComponent so that you can draw it. Then to initialize it, in your main class, you just say MyPicture picture = new MyPicture ();. Obviously, you would have a mthod called paint inside of the MyPicture class and the constructor will have one line: repaint();. Then in your main class after you put the instantiating line, you put JPanel panel = new JPanel (); and then panel.add (picture);

  • ?
    Lv 4
    4 years ago

    Java Cannot Instantiate The Type

  • 1 decade ago

    You can't instantiate Graphics directly. Instead, just rename your draw() method to paintComponent(), remove the call to it from your dots constructor, and you'll be set. paintComponent() will be called automatically by the windowing system when your widget is displayed.

Still have questions? Get your answers by asking now.