Array of JLabel vs. Graphics2D Painting - java

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.

Related

Java platformer game performance

I recently started working on a 2d platformer in java, and am asking a performance related question.
In my game, I have a world (relatively small for now).
But over half+ of the world isn't visible to the players camera, however I'm still painting the entire world (even the unseen parts).
Here's what I'm doing right now.
#Override
public void paintComponent(Graphics g){
g.translate(player.camX(), player.camY());
for (GameObject gameObject : solidObjects){
if (gameObject.isTouching(player.getCameraRect()))
gameObject.paint(g);
}
player.paint(g);
for (GameObject gameObject : unSolidObjects){
if (gameObject.isTouching(player.getCameraRect()))
gameObject.paint(g);
}
}
So the question is, would it be faster having an if-statement checking if its on the screen before painting?
Yes.
Doing a check to see if it's on a screen should take no more than 1 or 2 steps.
Painting everything requires you to draw every single pixel on to the screen regardless of whether it's used or not.
If gameObject.paint(g); involves a lot of drawing calls, most likely the branching (check) would save more work than it costs. If it's only like one drawing call to paint a sprite though, your library would already perform such a check to avoid buffer overruns and yours would be redundant.
That said, if you are starting to face performance issues here, then I recommend using some kind of data structure. A simple one is a grid like so:
When your elements move, remove them from the grid cells they occupy and insert them to the new one(s) they occupy. That should just involve manipulating a few integers if you implement this efficiently.
Then when you want to draw elements on the screen, only draw the elements in the grid cells that overlap. That'll prevent you from looping over every single element in the game world. This also comes in handy for accelerated collision detection if you need it.
A quad-tree is an alternative though a little bit more costly to update, but it can provide better search quality if the elements in your game are sparsely distributed.

drawing complex generated image in java 2d

I have a very large complicated diagram that needs to be drawn on the fly.
I am already using a double buffered technique to paint the image (from this answer: Using threads to paint panel in java) however, the generated image that is being painted is so large that it cant be painted as a single image (and the multiple images required to paint it cant be stored in memory all at the same time). For this reason, I paint the currently visible area of the view + some margin. As I scroll, I paint the area that is going to come next, and remove from memory the area we just came from. However, if the user then decides to change direction, they need to wait for this area to be painted again. My question is this:
If a single "frame" of the screen being painted is approximately 1000*1000 pixels, in which approximately 5000 lines/circles are drawn (nodes/edges of a graph) is it likely to be more efficient to repaint this image each time, or is there a way to affectively cache the image to hard disk (to avoid java heap limitations).
Ive already optimised the paint method as much as I can think of, but there are still several seconds of delay if a user scrolls to quickly (i.e. moves out of the painted area before the next set of "frames" are painted). So my second question is this: Will moving to OpenGL offer a large improvement, and will it require major changes to the infrastructure of the code? (I tried doing this a couple of days ago, and found it was not as simple as I thought - often led to the computer crashing).
Several things come to mind:
Profile to verify your working hypotheses; self-time the animation budget on your target platform for comparison, as shown in this AnimationTest.
Compare your approach to the example cited here; it scales into the 1000's and accommodates dragging selections into the hundreds.
If your frames have a suitable geometry, consider adopting the flyweight pattern for rendering; JTable rendering is an example; the underlying mechanism using CellRendererPane is examined here.

Java GUI programming strategy?

Java Beginner.
Hi, I haven't got any much experience with GUI programming. So I'm after some hints on how to tackle this next project. Hopefully I can explain myself well enough.
(source: mobilehomeservicesltd.com)
(see above photo as a reference)
This GUI aspect of my program will be a 2D - Birds-eye-view of a static caravan and veranda/balcony made with basic shapes. So typically the caravan will be represented by a rectangle (just a rectangle, ignore the fill in diagram). Sometimes static caravans have shaped fronts so that would be represented by a polygon as opposed to a rectangle. All in scale dependant on the users input, as all caravans have their individual dimensions.
After the caravan unit is in place I then need to draw another polygon surrounding the caravan representing the balcony/veranda, all to scale. Understand so far?? Good. Here comes the challenge part (for me anyway).
On the polygon representing the balcony I need to be able to draw lines to represent the decking that will be nailed down as a surface (like the diagram above). Now because the caravan could possibly have a shaped front, the decking must follow the shape of the caravan. In other words, if the caravan has an oval or angled front the decking will have to be cut to follow that shaped.
Without boring you all too much with detail. The idea is to let the user decide whether they want the decking fitted in such a way that its running in the same direction as the caravan, or against. Once the user has decided I will then attempt to calculate from the drawing (as it will be to scale) how many full lengths of decking will it take to build this veranda (among various other items).
Now my knowledge is limited on GUI, but I'm up to scratch with panels and drawing lines, rectangles, polygons etc... My original idea was to manually draw the caravan using the g.drawLine method, same with the veranda and then base my calculations on pixel counting to calculate all the various components.
Am I out of my depth attempting this, or is this something relatively easy to program?? Is there a more efficient way of doing this that I should look up before attempting this?
What you want to do is achievable, but its not the simplest of tasks. But don't let that slow you down.
You'll want to get started by understanding how to draw in Swing. Take a look at
Graphics 2D
Custom Painting
You'll also want to be familiar with Swing in general
Creating a GUI with Swing
The basic concept with scaling, is assigning a weight to a pixel. The more distance that a pixel is responsible for, the small your image will become

Java swing small 2D game: how to modelize the view?

In a small java swing 2D game, what is the best solution for creating the board view?
Use a component for the board and custom paint it and each square of the checker at once?
Use a component for the board and create another component modelizing the square with its own paint component doing the job for the square only. Use a layout to place each Square instance in the board?
I know this is subjective and I don't want a fight about it. I just need some clues to figure myself which way I should go. I've begun a side project and I've using 1), with the feeling that there is something wrong.
Just go with one drawing panel/container for everything.
Consider a tile based game. Using your second solution each tile would be an object, memory would skyrocket and the game would slow to a crawl.
Using the first option you are flexiable. You draw what you want, you have the panel coordinates so everything is relative to this. Using the tile based example you'd know the height and width of the panel, draw your square and increment in the X and Y coordinates as appropriate.
GUI frameworks such as Swing or .NET's Winforms are expensive as they have a whole lot of other stuff that a game won't need. So to answer your question, go with option one, rather than say using a panel for every checker on your board.
One nice solution to using the second method, in combination with the first method is the Flyweight Design Pattern. You still get to use OO objects, but you'll have a fraction of the amount you normally would. Check it out.
Like Finglas, I lean toward your first approach. This tile-based game is a concrete example. In contrast, this component-based game uses a GridLayout of JToggleButton. The former is somewhat more complex but plays well even on large screens; the latter is simpler yet sufficient for reasonable games. You may have to experiment with your game's geometry and logic to decide which to prefer.

How to generate simple 2D graphics in real time?

For my internship on Brain-Computer Interfacing I need to generate some very fast flickering squares on a CRT monitor (flickering = alternating between two colors). The monitor's refresh rate is 85Hz and we would like this to be the bottleneck, which means that repainting all squares can take at most 1000/85 = 11ms.
My language of preference for GUI/graphics programming is Java, so I tried making a prototype with AWT, because it's synchronous (unlike Swing). I now seem to have two problems: the first is that time measurements show that the repainting of even 9 squares simply takes too long. My algorithm takes the desired frequency and calculates the times at which the system should repaint in advance and then uses a loop (with no sleep/wait delay) that checks everytime if the next 'time' was reached and if so, loops through all the squares to repaint them. The way I implemented it now is that the squares are Panels with background color A and are contained in another Panel with background color B and the flickering happens because the Panels' visibility is changed. I figured that this would be faster than one Panel that has to draw Rectangles all the time.
I don't have a decent profiling tool (can't get Eclipse TPTP or NetBeans profiler to work) so I can't be sure, but I have the feeling that the bottleneck is actually not in the repainting, but in the looping (with conditional checking etc.). Can you recommend anything about what I should do?
The second problem is that it seems like the squares are rendered top-to-bottom. It's like they unroll really fast, but still visibly. This is unacceptable. What I'm wondering though, is what causes this. Is it Java/AWT, or Windows, or just me writing a slow algorithm?
Can you recommend some things for me to try? I prefer to use Java, but I will use C (or something) if I must.
I would avoid any kind of high-level "components", like JPanels and the like. Try getting a Graphics2D representing the window's contents, and use its fillRect() method.
Failing that, you could probably do this easy enough in C and OpenGL. rasonly.c is a standard template program that sets up OpenGL to work as a "rasterizer" only, i.e. 2D mode. Using this as a starting point, you should be able to get something running that draws your desired "squares" without too much trouble.
You don't describe your desired scene very well, it sounds from that equation as if you want to draw 100 squares, each having a different color. For maximum performance in OpenGL, you should draw all squares of the same color together, to minimize the "state changes" between drawing calls. This is probably a purely theoretical point though, as drawing 100 2D squares at 85 Hz really shouldn't tax OpenGL.
UPDATE: Oh, so it's been a bunch of years, and nowadays you probably need to take the above with a grain of salt and read some modern tutorial. Things have changed. Look up the Vulkan API.
(I remember a demonstration of this using the BBC micro and palette switching, though that would be 50fps rather than 85, as it was a British domestic TV)
I'd switch to jogl and use display lists. They get very high fps rates in Java.

Categories