Question:
How to initialize... or just make a java Graphics class?
2009-05-09 08:31:13 UTC
ok... I have my java program..

then I have a nice set of JFrames I can display..

now I have a class called GraphicMaster that is a swing form... using netbeans I can just throw in a bunch of little objects and add events.. that's nice. but when I tried displaying my images on a JPanel it just didn't show them..

so I know how to draw an image on a Graphics.. just g.drawImage(bla).

but what I need to know is how to create a Graphics that can actually
draw things on a specific JFrame...

I know how to send Graphics around- you just void bla(Graphics g)

but that doesn't really help in the whole term since I don't know how to
initialize that Graphics in the first place.

so if you could tell me how to make a Graphics on a specific JFrame that's already been created, that would be nice.

please don't just say- "go to imadipshit.com and all your needs to be met."

I need a very real code example.

Thanks so much, your help is greatly appreciated.
Four answers:
spiller
2009-05-09 08:42:27 UTC
On any AWT or Swing component or frame, you can call getGraphics():



http://java.sun.com/javase/6/docs/api/java/awt/Component.html#getGraphics()



E.g.,

Graphics g = myframe.getGraphics();

g.setColor(Color.GREEN);

g.fillRect(20, 20, 200, 200);
heike
2016-12-16 00:00:55 UTC
Initialize Graphics Java
e^(πi) = -1
2009-05-09 08:38:50 UTC
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);
Rhonda
2016-02-28 02:44:30 UTC
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.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...