This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes getting an object to draw itself - I'm clueless Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "getting an object to draw itself - I Watch "getting an object to draw itself - I New topic

getting an object to draw itself - I'm clueless

angus weir

Joined: Feb 10, 2012
Posts: 4
I'm trying to learn Java, have programmed procedural languages for decades - OO is totally new :0

I'm trying to write a game, I'm using eclipse under windows.

I'm writing a tabletop wargame with two armies of different groups of soldiers(squadrons) controlled by two players.

I've written a class for a squad of soldiers, which implements the rules for how squadrons will move, fight etc based on numeric values and random numbers. This all works OK, although the algorithms are trivial at present (but that's just simple programming to fix!) I've also written a second class for soldiers with distance weapons (guns, spears...) as a subclass of the first to add additional methods for shooting etc.. This also works OK.

I've coded a class to create the window (mostly just cobbled from places I've found), the menu items, the jframe and jpanel - also working.

What I now want to do is have each squadron object draw itself when it should (after it moves mainly). I can make no sense of where I put the draw command, and what I need to do to make it work. I have loaded an image into a BufferredImage object (will be based on the squadron name in due course) within the constructor method and started trying to create a draw method within the class, I'm currently using a JLabel object to hold the image.

How and where do I create the graphics context, within main() or my window creation class and then how do I pass it to my squadron objects (there may be many at any one time) and I keep seeing classes which extend JPanel - why and how?

I know this is pretty basic stuff - but after a few days of fruitless searching and getting more confused, I thought I'd try asking for a simple answer I can understand. I have more java projects waiting to be coded, but most will need to create graphics canvases on which objects draw themselves, so I thought it worth finding out the right way early on.

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 37926
I shall move this discussion to our GUIs forum.

I presume you want an object-oriented way to do these things. Create an interface like Drawable.You will need to use the javadoc tool on that, then you can see the API documentation and (I hope) how to use a Drawable object.
angus weir

Joined: Feb 10, 2012
Posts: 4
Thanks for response - it looks really good, but I don't understand

I'll do some digging and try to get javadoc to work in eclipse (it's not currently) and see if that helps. My problem stems from the fact that I have coded lots (including machine code and high level languages), but the oo approach for handling graphics leaves me bemused and none of the tutorials I have found explain it to me so I can understand. I keep waiting for the penny to drop, but it is persistently defying gravity!!!
Darryl Burke

Joined: May 03, 2008
Posts: 4523

Keep it simple. A Graphics is like a paint brush: it covers a drawing surface with pixels, according to the instructions you give it - the methods you call. You can discover all these methods from the API.

Excepting in the very earliest days of Java, every Graphics reference refers to an instance of a Graphics2D subclass. (Note that Graphics and Graphics2D are abstract classes; the concrete subclasses are private implementation details, not part of the puvlic API.)

What Campbell is suggesting is that you give your classes, each of which represents or encapsulates a 2D drawing, their own method with a signatureYou enforce this by defining an interface, and ensure that all those classes implement the interface.

Now every JDK class that know about painting and drawing has a way to either obtain the Graphics associated with an instance -- BufferedImage#get/createGraphics() -- which returns a Graphics reference that can modify the pixels of the BufferedImage, or a method or method to paint itself -- Component#paint/paintAll/update(Graphics g), JComponent#paintComponent/paintBorder/paintChildren(Graphics g). All these methods are called by the JRE internals and passed a Graphics reference that modifies the pixels of their drawing surfac -- an area of the screen.

Now, to draw your object to a JComponent subclass, you would override a painting method, typically paintComponent(...) and invoke your object's painting method with the Graphics reference that draws to the component.

BTW, I differ with Campell's recommendation in respect of the method name; I would call the method paint(...) to conform with the familiar method name from the JDK. And I would name the interface Paintable.

luck, db
There are no new questions, but there may be new answers.
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 37926
You mean you agree with 90-something % of what I suggested
angus weir

Joined: Feb 10, 2012
Posts: 4
guys, apologies for the delay but I've been away from the internet

I really appreciate your help, but the more I try to understand the more confused I get.

On the plus side, I have created an interface and told my main class to implement it. Then the confusion starts.

Most of the stuff I read seems to be extending the JPanel class, but this doesn't feel right and I think is different from your suggestions. I want my objects to draw themselves when they see fit and to do this I think I need the object to be able to draw itself in my window. Is this the right approach?

Do you mind if I start my questions again?

I have created a class (unitWarrior) which has a few methods for calculating its size and position (and other stuff too). I want a method within it to draw onto my window a little image to represent itself. This image should be read from a file (a jpeg file, but pretty small) within the class constructor method. I am currently reading it into a BufferedImage object using imageIO.Read:

Is this the right object to receive my image from the file in the firstplace?

I have created a GUI class which creates the main window and a menu system (which currently isn't coded to do anything, but I reckon 1 challenge at a time).

My main() routing runs:
which does what I expect and want, so I think is OK, but here is the method:

I haven't shown each of the methods I call as I think they are OK and do what their names suggest.

the main() then creates an object of type unitwarrior and then a second object of type unitwarrior so the two objects can do battle.

One of the methods is for the object to change its position, when this happens I want to update the screen to show the new position.

Now for some questions....

When I create the JPanel, do I need to get the graphics context returned so I can pass it to each unitWarrior instance so it knows where to draw itself? and to do this would I get the showJPanel method to return mainframe which I then pass to each unitWarrior instance (or is there a global-type variable - or is that question betraying my non-oo roots?)

I can't find the Paint method within bufferedImage to override (is that a clue that I shouldn't be using BufferedImage?)

I am really keen to understand this stuff, but everytime I think I see a glimmer it turns out that there are just more layers of confusion - I am coming to the conclusion that I am asking the wrong questions in the wrong way, and please feel free to point me to a book or something if the missing layers of knowledge are too big for a forum to tackle.
angus weir

Joined: Feb 10, 2012
Posts: 4
Another week of fruitless confusion and hair pulling - I'll be bald soon.

I have tried loads of things, read loads of things, understood a few of them and now do the following:

my class now extends JPanel and I can display an icon when I add the jpanel to the jframe - a few issues I'm working on, but I'll deal with those in due course. The main thought is "is this the right way to go?" It feels wrong to build a class to extend jpanel which also adds so many other methods to do with fighting soldiers?

I don't think this is anything like the suggestions so kindly proferred, but I couldn't make any progress with the suggestions as I couldn't understand what to put where.

Have I structured all my stuff wrong? I want to do this the proper oo way, but to a procedural programmer the learning curve is pretty steep.

Help desperately wanted.
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
Just a thought:

check the source code for (e.g.) JLabel
and its methods setLocation(), setIcon() etc
where no additional code is required to
'redraw' itself.

can't check myself, pc has died, just waiting
on delivery of 16lb sledge for funeral service.
I agree. Here's the link:
subject: getting an object to draw itself - I'm clueless
Similar Threads
Drawing a Transparent PNG
jpanel paint image using method like jpanel1.paint
How to Draw a Line in Java?
Servlet limitations?
Showing image in JPanel - it disappears