Ashik’s IT Thoughts

February 27, 2007

Developing Simple Chess Board With Swing in Java SE 6

Filed under: Java — ashikuzzaman @ 4:44 pm

My first professional java project as a software developer was to build a client/server application using Java 2, Swing, RMI and Oracle database. Around 5 years back, it was a small team of 3 developers one project manager and one architect. At that time we used Forte For Java was facsinated how easily I could drag and drop swing components in a palette to build my GUI instead of the AWT way I learnt and taught my students during my Java Teaching career. However, immediately after finishing first few modules, we understood the problems of JFC/Swing components in Java 1.2 . They were so slow that a novice user could identify that and compare with a Visual Basic or C++ GUI application. We had hard time working with JTree and JTable components. But since then Java has crossed JDK 1.3, JDK 1.4 (a major improvement compared to other versions), Java SE 5 and now Java SE 6. While I am working with SWTand Java SE 5in one of my projects in office, I may get into a parallal project on Swing soon. So I thaught to prepare the same chess board using Swing and Java SE 6 and finally came up with this entry. You may compare this with the one that I prototypes using SWT as a practice. To my understanding while both SWT and Swing has its own places, Swing would be a better choice for my next java GUI development due to its intuitive, easy to use API. You dont any java IDE for the program I am going to show you today. However, for advanced GUI design purpose my favorite would be Netbeans 5.5 and as I want to continue using MyEclipse where most of my java projects are configured, I downloaded Matisse4MyEclipse in it.

 

Get tight and follow the steps!

  1. Make sure you have Java installed. I installed Java SE 6 in C:\programs\java\jdk_6
  2. Install Ant 1.6.5 altough you may use command prompt if you dont want to use Ant.
  3. Create project directory at c:\workspace\SwingBoard
  4. Create SwingBoard class under package name com.chess4you.board. Here is the source code for this class.
    /** SwingBoard.java **/
    package com.chess4you.board;import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.LayoutManager;
    import java.awt.Toolkit;import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;

    /**
    * A simple chess board using Swing
    *
    * @author Ashik Uzzaman
    * @link http://ashikuzzaman.wordpress.com
    */
    public class SwingBoard extends JFrame {

    public static final int NUMBER_OF_ROWS = 8;
    public static final int NUMBER_OF_FILES = 8;
    public static JLabel square;
    public static JPanel squarePanel = new JPanel();
    public static JPanel squaresPanel = new JPanel();

    private static void createSquares() {
    LayoutManager layout = new GridLayout(NUMBER_OF_ROWS, NUMBER_OF_FILES);
    squaresPanel.setLayout(layout);
    for(int i=NUMBER_OF_ROWS; i>0; i–) {
    for(int j=1; j<=NUMBER_OF_FILES; j++) {
    squarePanel = new JPanel();
    square = new JLabel (“r” + i + “:c” + j);
    squarePanel.add(square);
    squarePanel.setBackground(getColor(i, j));
    square.setForeground(new Color(0, 0, 250));
    squarePanel.setToolTipText(“Row ” + i + ” and Column ” + j);
    squaresPanel.add(squarePanel);
    }
    }
    }

    private static Color getColor(int x, int y)
    {
    if((x+y) % 2 == 0)
    return new Color(255, 255, 255);
    else
    return new Color(0, 0, 0);
    }
    public SwingBoard() {
    initComponents();
    }

    private void initComponents() {

    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    int boardSize = 0;
    int width = dim.width;
    int height = dim.height;
    if(width >= height) {
    boardSize = height / 2;
    } else {
    boardSize = width / 2;
    }
    createSquares();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle(“Swing Chess Board”);
    setIconImage(new ImageIcon(“board.jpg”).getImage());
    getContentPane().add(squaresPanel, BorderLayout.CENTER);
    setVisible(true);
    Dimension preferredSize = new Dimension();
    preferredSize.width = boardSize;
    preferredSize.height = boardSize;
    setPreferredSize(preferredSize);
    setBounds(boardSize / 4, boardSize / 4, boardSize, boardSize);
    pack();
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new SwingBoard();
    }
    });
    }
    }

  5. Create javase6.bat file inside your project directory. The content of this file actually sets path and classpath required for java.
    ## Simple batch file for Java classpath settings
    SET JAVA_HOME=C:\programs\java\jdk_6
    SET ANT_HOME=C:\programs\java\apache-ant-1.6.5
    SET PATH=%PATH%;%JAVA_HOME%\bin;%ANT_HOME%\bin
    SET PROJECT_HOME=C:\workspace\SwingBoard
    SET CLASSPATH=%CLASSPATH%;.;%JAVA_HOME%\lib\tools.jar
    Title “JDK 6″
    cd %PROJECT_HOME%
    cmd
  6. If you use Ant, create build.xml file in your project directory with following contents.
    <?xml version=”1.0″ encoding=”ISO-8859-1″?>
    <project name=”SwingBoard” default=”run” basedir=”.”>
    <description>
    Swing Application build and execution file
    </description><property name=”main.class” value=”com.chess4you.board.SwingBoard”/>
    <property name=”src” location=”.”/>
    <property name=”build” location=”.”/><target name=”compile”>
    <javac srcdir=”${src}” destdir=”${build}” />
    </target>

    <target name=”run” depends=”compile”>
    <java classname=”${main.class}” fork=”true” failonerror=”true” />
    </target>
    </project>

  7. Copy a small icon for a chess board in your project directory and name it board.jpg that is used in our code. You may download the icon that I used from http://farm1.static.flickr.com/160/391341494_669254c2c6_s.jpg
  8. To compile from command prompt, double click javase6.bat file and issue the following command: javac com/chess4you/board/SwingBoard.java
  9. To run from command prompt, issue the following command: java com.chess4you.board.SwingBoard
  10. To compile using Ant, issue the following command: ant compile
  11. To run using Ant, issue the following command: ant run

Blog at WordPress.com.