Java Swing: Snake with different Guis

This is the first part of a Series about different Guis and how to implement them. To demonstrate the game Snake will be used. In this part I will show the development process of a Java Game using Java Swing.

The planned parts of this Series:
– Swing
– Android
I will start with Swing.

Java Swing

I already know Swing, and I suspect most of my readers do as well, so I will keep this part short. The documentation of Swing is quite good, but I do think that the api is overly complex and in some parts not completely thought through.

General Structure of Java Program

Here I will once describe the program structure. The structure will (or at least should) stay the same for all guis (this already proved to be a slight problem with android as android is quite demanding about the programs flow).

The program is structured using the mvc pattern. The model is not really important to the guis, so I will not describe it, if it interests you feel free to view the source.

The important controller is the AbstractGameController as it handles the logic of the game. It also reports changes of the game field to the gui and reads input from the IInputController interface. It does not contain an actual game loop (as android did not allow this to be realized easily) but can be easily extended. It also does not run in its own thread (again, because of android), but this too may be realized in the extended controller.

My key for Visual Paradigm for UML expired, so I used ArgoUML to create the following UML diagram. Sadly, I could not find functions I needed (such as copying a class or showing classes inside packages). I searched the web, but could not find any help, so I finished it with gimp… snake uml diagram

Swing implementation

There really is not much to say. I kept it as simple as possible: Only one Frame, it holds a JPanel which displays the field. On request, a JDialog opens for settings and a high score. The different squares of the game field each are represented by one JLabel in the panel (this allows for easy switch away from text look to actual pictures, if desired) and are updated when the Controller informs the gui about changes.

I do know that it does not look very good, but hey, it’s snake (in swing, which I think never *really* looks good, even when I do put an effort in it). The Android version will (well, already does) look nicer, I promise.


Download Snake and Source Code

Snake with Swing Gui [22.92 kB]
Snake with Swing Gui Source code [21.9 kB]

The second part is Android: Snake with different Guis

Related Posts:

2 thoughts on “Java Swing: Snake with different Guis

  1. @vishali oh, sorry, I thought that I added it to the jar, but seems like I forgot. Thanks for noticing, I added a link to the source code now.

Leave a Reply

Your email address will not be published.