swing

Java Swingx Game Example

1. Introduction

Swing is a GUI widget toolkit for Java. It is part of Oracle’s Java Foundation Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs. Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT). JAVA provides a rich set of libraries to create Graphical User Interface in platform independent way.

Swing API is set of extensible GUI Components to ease developer’s life to create JAVA based Front End/ GUI Applications. It is build upon top of AWT API and acts as replacement of AWT API as it has almost every control corresponding to AWT controls. Swing component follows a Model-View-Controller architecture to fulfill the following criteria.

  • A single API is to be sufficient to support multiple look and feel.
  • API is to model driven so that highest level API is not required to have the data.
  • API is to use the Java Bean model so that Builder Tools and IDE can provide better services to the developers to use it.

2. JAVA Swing

Unlike AWT, Java Swing provides platform-independent and lightweight components. The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

2.1 MVC Architecture

Swing API architecture follows loosely based MVC architecture in the following manner.

  • A Model represents component’s data.
  • View represents visual representation of the component’s data.
  • Controller takes the input from the user on the view and reflects the changes in Component’s data.
  • Swing component have Model as a seperate element and View and Controller part are clubbed in User Interface elements. Using this way, Swing has pluggable look-and-feel architecture.

Every user interface considers the following three main aspects:

  • UI elements : These are the core visual elements the user eventually sees and interacts with. GWT provides a huge list of widely used and common elements varying from basic to complex.
  • Layouts: They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface).
  • Behavior: These are events which occur when the user interacts with UI elements.

2.2 Swing Features

  • Light Weight – Swing component are independent of native Operating System’s API as Swing API controls are rendered mostly using pure JAVA code instead of underlying operating system calls.
  • Rich controls – Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, table controls.
  • Highly Customizable – Swing controls can be customized in very easy way as visual apperance is independent of internal representation.
  • Pluggable look-and-feel– SWING based GUI Application look and feel can be changed at run time based on available values.

2.3 Setup

Popular Java Editors:
To write your java programs you will need a text editor. There are even more sophisticated IDE available in the market. But for now, you can consider one of the following:

  • Notepad: On Windows machine you can use any simple text editor like Notepad TextPad.
  • NetBeans: is a Java IDE that is open source and free which can be downloaded from http://www.netbeans.org/index.html.
  • Eclipse: is also a java IDE developed by the eclipse open source community and can be downloaded from http://www.eclipse.org

Prerequisite
This example is developed on Eclipse therefore a compatible Eclipse IDE is required to be installed on the system.
We also need WindowBuilder tool to be installed on Eclipse IDE for the easiness of the work. To learn how to install WindowBuilder tool please visit the Setup section 2.1 of the following link click here.

2.4 Class and description

  • Component: A Component is the abstract base class for the non menu user-interface controls of SWING. Component represents an object with graphical representation.
  • Container: A Container is a component that can contain other SWING components.
  • JComponent: A JComponent is a base class for all swing UI components. In order to use a swing component that inherits from JComponent, component must be in a containment hierarchy whose root is a top-level Swing container.

2.5 SWING UI Elements

    • JLabel: A JLabel object is a component for placing text in a container.
    • JButton This class creates a labeled button.
    • JColorChooser A JColorChooser provides a pane of controls designed to allow a user to manipulate and select a color.
    • JCheck Box A JCheckBox is a graphical component that can be in either an on (true) or off (false) state.
    • JRadioButton The JRadioButton class is a graphical component that can be in either an on (true) or off (false) state. in a group.
    • JList A JList component presents the user with a scrolling list of text items.
    • JComboBox A JComboBox component presents the user with a to show up menu of choices.
    • JTextField A JTextField object is a text component that allows for the editing of a single line of text.
    • JPasswordField A JPasswordField object is a text component specialized for password entry.
    • JTextArea A JTextArea object is a text component that allows for the editing of a multiple lines of text.
    • ImageIcon A ImageIcon control is an implementation of the Icon interface that paints Icons from Images.
    • JScrollbar A Scrollbar control represents a scroll bar component in order to enable user to select from range of values.
    • JOptionPane JOptionPane provides set of standard dialog boxes that prompt users for a value or informs them of something.

3. Creating Swing Game

We will learn Swing basics through this example i.e, JavaSwingExample.java

Code for JavaSwingExample.java

SwingGameExample.java

import javax.swing.*;         


public class SwingGameExample implements Runnable{
   
   final int WIDTH = 1000;
   final int HEIGHT = 700;
   
   JFrame frame;
   Canvas canvas;
   BufferStrategy bufferStrategy;
   
   public SwingGameExample(){
      frame = new JFrame("Basic SwingGameExample");
      
      JPanel panel = (JPanel) frame.getContentPane();
      panel.setPreferredSize(new Dimension(WIDTH, HEIGHT));
      panel.setLayout(null);
      
      canvas = new Canvas();
      canvas.setBounds(0, 0, WIDTH, HEIGHT);
      canvas.setIgnoreRepaint(true);
      
      panel.add(canvas);
      
      canvas.addMouseListener(new MouseControl());
      
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setResizable(false);
      frame.setVisible(true);
      
      canvas.createBufferStrategy(2);
      bufferStrategy = canvas.getBufferStrategy();
      
      canvas.requestFocus();
   }
           
 

This is one of the simplest Swing Game application you can write. It doesn’t do much, but the code demonstrates the basic code in every Swing program:

1.Import the pertinent packages.
2.Set up a top-level container.
3.Display the container.
4.Be thread-safe.

The first line imports the main Swing package:

SwingGameExample.java

import javax.swing.*;

This is the only package that JavaSwingExample needs. However, most Swing programs also need to import two AWT packages:

SwingGameExample.java

import java.awt.*; 
import java.awt.event.*; 

These packages are required because Swing components use the AWT infrastructure, including the AWT event model. The event model governs how a component reacts to events such as button clicks and mouse motion. You’ll learn more about events in the upcoming section Handling Events (in the Creating a GUI with JFC/Swing trail).

Every program with a Swing GUI must has at least one top-level Swing container. A top-level Swing container provides the support Swing components need for painting and event handling. There are three commonly used top-level Swing containers: JFrame, JDialog, and (for applets) JApplet. Each JFrame object implements a single main window, and each JDialog implements a secondary window (a window dependent on another window). Each JApplet object implements an applet’s display area within a browser window. (JApplet is covered in How to Make Applets(in the Creating a GUI with JFC/Swing trail).)

The JavaSwingExample example has only one top-level container, a JFrame. Imple­mented as an instance of the JFrame class, a frame is a window that, by default, has dec­orations such as a border, a title, and buttons for iconifying and closing the window. Applications with a GUI typically use at least one frame.

The Output of the code when executed will look like the one below.

GameExample
GameExample

4. Download The Source Code

Here we have demonstrated how to develop a game using JAVA Swing.


You can download the full source code of this example hereSwingGameExample

Jyoti Jha

Jyoti is a tech enthusiast and is an avid programmer. She holds a post graduation degree in (M.Tech) Computer Science Engineering from Thapar Univeristy, Patiala, India. Post her graduate studies, she has worked in Software companies such as SLK Software and Aricent, India as Software Engineer in various projects primarily in the field of Requirement analysis and design, implementing new algorithms in C++ and JAVA used in ISDN network and designing databases and. She is inquisitive about socio economic reforms as well as advancement in technical fronts and keep herself informed with TED talks and various blogs.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button