What is a good approach of to draw graphics with swing? - java

I am a complete novice when it comes to any kind of graphics. So, I want to create a method in a class Creature that would be able to draw lines on a screen (turtle graphics style). I have no idea what would be a good way of doing this. I mean I could store all lines drawn by user in a container or whatever and every time the repaint() method is called I would redraw all lines but it looks bothersome. Or perhaps it's the best way and I am just being silly? As I said, I don't have any experience with this and everything is starting to look like black magic to me. I would appreciate any help or suggestions. Thanks!

See Custom Painting Approaches for two common ways to do this:
Keep a List of objects to be painted and repaint them every time
Paint to a BufferedImage and just display the image

Updating what to draw and actually drawing it should be separate, because you can't control when repaint() is called. You usually want to control how often the updating is done so it's always a good idea to separate. This also reduces the time it takes to draw so it increases performance as well.

Related

Java Game moving real time(AP CS Final)

I'm taking the AP computer science class at my school. They never taught us about GUIs because the AP test didn't require you to know how to make one.
For our final project we wanted to make something like tron (game where bikes move around an are creating walls of light behind them in an attempt to crash the other player). Before we continue i just want to make sure we are going in the right direction. Should we use ImageIcon for the players or maybe something else?
We still have a lot to learn, but i thought this would be a good thing to start with. The reason why i'm asking is because i'm not sure if we would be able to move them without opening another window every time we want to move something.
This is probably a matter of opinion, but personally, I would use BufferedImage's as the primary image container.
The main reasons are:
They are easy to paint and easy to manipulate, you can actually draw onto them if you need to.
Loading a BufferedImage is done through ImageIO.read, it guarantees that the entire image is loaded before the read method returns and will throw an IOException if it can't read the image for some reason, which is better than ImageIcon which loads the image in a background thread and doesn't report errors if the image failed to load
Movement or placement of the images would be done, typically, by painting them onto an output Graphics context. This is (typically) done by overriding the paintComponent method of something that extends JComponent and using the passed Graphics context and Graphics#drawImage
Have a look at Performing Custom Painting, 2D Graphics and Reading/Loading an Image for more details

Array of JLabel vs. Graphics2D Painting

I have to create a connect 5 game with a GUI for my CS course final project. I worked with Graphics2D for the last project - a Maze - and working with Graphics2D was a nightmare. At most, the connect5 board will be 20x20, which would be an Area of 400. I was wondering what the performance implications of creating an Array of 400 JLabels to handle the GUI, since it will be easy to determine a mouse click within boundaries, get the array induces, and changing the color of space along with other similar operations whereas the same operations would be much more difficult with Graphics2D. So, my overall question is: would creating an array of that many JLabels be undesirable? If so, what other alternatives might I have? Thanks everyone!
I think the JLabel approach would be undesirable, I think one component with custom painting would be more desirable, because it seems a bit easier.
If you have your classes in that abstract format not tied to the UI or anything (so playable even on the command line where you could output in a text a representation of the board), then it should be simple to loop through the spaces representing the board and make the small set of drawing calls to draw each slot (empty or not).
Seems better to if you wanted to introduce animations like pieces falling down and then bumping up for a while when they hit the piece below it.

Optimizing Java Graphics

I have a custom UI drawn for my java application. Right now I draw the entire UI from scratch. I know for a fact some parts of the UI are static. I know I could save these static parts to an image, but will this yield a improvement in performance (Since even an image must be drawn every frame)?
Is it plausible to save a reference to the Graphics2D object after the UI has been drawn and assign that to the new graphics object every frame (starting from a point where all the static components are drawn)?
Thanks in advance,
Alan
You don't need to redraw everything in every frame. So if you have static parts of your UI (or even dynamic parts that you know haven't changed since last frame) then you simply don't need to repaint them.
In my code (Swing games and simulations mostly) I usually try to follow the following rules:
Pre-prepare static images (e.g. BufferedImage textures for UI elements)
Override the paintComponent() method for each UI element individually to do the painting
Only call the repaint() method of any given UI element if I know that something has changed
Call repaint() in a timer-based loop for animation, but only call it on the portion of the UI that is being animated (e.g. a nested JPanel)
This approach seems to work and perform pretty well (though I'd welcome comments if there are ways to improve it!!)
There are two main optimizations you can do here. The first is to make sure that when you cause your UI to be repainted, usually done by calling repaint, make sure you call the version of repaint where you specify a rectangle that has changed. Only make the rectangle big enough to encompass the parts that actually have changed, not the static parts. For this to be effective you also have to pay attention to the clipRect in the Graphics2D object you are passed in paint(). That is used by the system to tell you exactly what needs to be repainted, in the above case usually the rectangle that you passed to repaint. Don't paint anything that lies entirely outside that rectangle.
You can also get significant performance improvements by caching the static parts of your interface in an image. Writing an image is by far the fastest way of getting things onto a screen. My measurements indicate that small images are faster than even a few simple drawing primitives. However you need to make sure the image characteristics match the screen, by using createCompatibleImage().
Of course you may be using a lot of memory to get this speedup. I would recommend testing to see if you need to do image caching before implementing it.
if some parts of the screen is completely static, then never redraw that part. Don't do a full-screen/window clear, just clear the part of the screen/window that changes all the time.
This way, you don't unnecessarily redraw the static image.

scroll bar problems in java Layered Panes

I've been trying to build this small java app. I find it very difficult to design UI in java, tasks that seem very simple become complicated and all these strange misbehaviors occur. In my app I've created a JLayeredPane which contains two layers. One on top on the other, They both contain scrollbars.
Here's an explanation of the two layers:
Layer 1:
A very big image inside something similar to a scrollpane. The image is scrollable.
Layer 2:
A graphics2d object, this object draws an image. Once the image reaches a certain length, the layer gets a scrollpane that advances with the drawing with time.
I'd like to connect both layers. I want layer two to update the scrollbar on layer 1. Meaning that once it reaches a certain length, both scrollbars will advance together. When I try doing that, the two scroll bars really do advance, but ( ! ) this strange flickering occurs. I don't understand what is the reason for the flickering. Is there any other way to implement this in a simple manner? I must have the second layer on top of the first one (drawing on top of image)
since I cannot open a special post for thanking the wonderful people of this forum, I'll do it here. Thank you, you are great help. I hope this problem is solvable as well.
It sounds like you're repainting the entire component in some costly way each time - you could try to paint to a BufferedImage to save the image rather than re-generate it each time. Or you could try to mess around with how repaints are handled. I'd suggest this article and this page on Sun's website - both discuss performant painting practices.
Without seeing your code it's quite hard to guess where is the problem. Probably you're getting more paint() events than you really need.
Also you can try JXLayer (http://weblogs.java.net/blog/alexfromsun/archive/2008/06/the_new_jxlayer.html) to show your graphics2d layer.

How can I split up paint swing method in java?

I'm developing a fair sized hospital simulation game in java.
Right now, my pain method is starting to look a little big, and I need a way to split it up into different sections...
I have an idea, but I'm not sure if this is the best way.
It starts by painting the grass, then the hospital building, then any buildings, then people, then any building previews when building. The grass and hospital building will not change, so I only need to paint this once. The buildings themselves won't change very often, only when new ones are built.
I was thinking, use boolean values to determine which sections need repainting?
Ideal, id like to be able to split up the paint method, and then call each one when needed, but I'm unsure how to physically split it up.
I am still quite new to java, and learning on the go.
Thanks in advance.
Rel
Another idea is to create a super class or interface for all items that must be drawn on the screen. Lets cvall this class ScreenObject. You can then have a draw(Graphics2d g) method specified in the ScreenObject class. Next, each object that must be drawn implements the draw() method and is only concerned about drawing itself. You can even consider creating a variable that determines whether this draw method should be run at all.
In the main class that paints the screen you can have a reference to all ScreenObjects in an ArrayList and your paint() method will simply iterate over this calling draw() on each object.
I'm assuming from your description that your scene is split up into tiles. Keeping an array of booleans is a good way to keep track of which tiles need redrawn on the next update. A LinkedList might perform a little better in some situations. (I'm thinking of a Game of Life simulation where there are tons of tiles to redraw and you need to check each neighbor, so you may not need to go this route.)
Without seeing your code I can't give very specific advice on splitting up your paint method. I can tell you that in sprite animations, each sprite object typically has its own draw method that takes the main Graphics object (or more likely a buffer) as a parameter. Since the sprite should know its own image and location, it can then draw itself into the main image. Your paint method can then just loop through your list of sprites that need to be redrawn and call their draw method.
You might look to Killer Game Programming in Java for more detailed information.
Well I am not really an expert at programming but to split up my paint method Ive always just made a new method that takes a Graphics object and call that from paint, it has always helped me to keep my code organized but I have never had a big project like it sounds you are working on so it might not work for your situation.

Categories