Developing Simple Chess Board With Swing in Java SE 6


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 https://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

25 thoughts on “Developing Simple Chess Board With Swing in Java SE 6”

  1. this programm is not executing . there r so many errors. first rectify it and then post the new one. i’m expecting it asap.

    even some of the calling methods doesn’t define.

    Like

  2. Hello Everyone,

    I am a golfer myself and I like to play whenever I get a chance.
    A short while ago, a very good friend of mine told me about a great golfing equipment and accessories website that has discounted prices on all their products, same day shipping in most cases and there is no state sales tax, they are paying that.
    So if any golfer here is ready to save some money on quality products at highly discounted prices, you might want to check out their site at; http://hoffmangolf.com

    Like

  3. Ðåãèñòðàöèÿ äîìåíà â çîíå .RU âñåãî 11$ ó êîãî óæå èìååòñÿ ñàéò íà .RU äëÿ âàñ âûãîäíîå ïðîäëåíèå!!!
    À äëÿ ÐÅÑÅËËÅÐÎÂ ñàìûå âûãîäíûå óñëîâèÿ è ëó÷øàÿ öåíà!
    Äëÿ âñåõ óäîáíûå àäìèíêè îòêóäà âñ¸ ëåãêî óïðàâëÿåòñÿ.
    Ïî âñåì âîïðîñàì â ICQ 413477227
    http://panel.domensell.ru

    Registracia domena v zone .RU vsego 11$ prodlenie 11$
    Dlia Resellerov ceni eshe menishe!
    Ydobnaia adminka vse legko ypravliaetsia
    Po vsem voprosam v ICQ 413477227
    http://panel.domensell.ru

    Like

  4. hi,
    its nice .iam new in java.pls can u send me. how to create website using java swing’s.i want source code.pls if u cant help.

    Like

  5. i found this post in google. thanks for the great example. but there’s something wrong about this line:

    for(int i=NUMBER_OF_ROWS; i>0; i–) {

    i guess this should be i–

    greets

    Like

  6. привет всем!
    Срочно надо выбрать 10 лучших фоток из нескольких десятков, я сама не могу выбрать, все нравятся.
    Помогите сделать выбор девушке, все фотки тут http://arina.labinfoz.com , желательно выбирать с мужской точки зрения :),
    жду помощи от обитателей ashikuzzaman.wordpress.com.

    Like


  7. Tori Spelling is seen her hanging out with her husband Dean as they get a break from the babies to go to La Scala in Beverly Hills for lunch. Isn t that the sweetest? I guess given the ever-present Miu Miu dress Tori must be having some issues losing the baby weight, perhaps someone should tell her that a La Scala lunch isn t going to help her much there. At least she is keeping her blonde locks maintained in a way that is most practical for new baby mamas. Tori has this season s look down, with cropped locks that are easy to manage, and far away from little grabbing fingers. I think a more polished look would work with her here though, perhaps with some extra time with the flat iron and some glossing serum for some extra polish. I mean, if you don t get out much, and finally get some time for a nice lunch with your hubby, you really deserve to spend a little extra time looking all gussied up for him.
    Welcome to the Hairstyles Top. Here you will find the latest top hair style pictures, and advice for new hairstyles: sedu hairstyles, short hairstyles, black hairstyles, how To Hair Tips, etc. Lots of celebrity haircuts.

    Like

  8. Берегите глаза с молоду! ГЛАЗА НУЖНО БЕРЕЧЬ С ДЕТС… [url=http://o-zrenii.blogspot.com/]Что самое важное для прогресса?

    Like

  9. Вопрос:   Я хочу познакомиться с красивой девушкой. Времени после занятий катастрофичеcки не остается, а в свободные дни обычно необходимо также  бегать по разным инстанциям. В общественных местах знакомиться не удобно.  Пока что на сайтах вижу  преимущественно продажных девушек. Предложите что-нибудь, пожалуйста. Наперед огромное спасибо ..

    Like

  10. Write A growing number of sites will pay for your articles or blog posts. Associated Content and Helium will “pay for performance” based on page views for just about anything you want to write about. Articles on specific topics they’re looking for can earn direct payments up to about $200. The rates are probably low for established writers, but if you’re trying to break into the field and have time on your hands, they’re a great way to start. Also, a lot of companies are looking for part-time bloggers. They may pay per post or on a steady contract. Our Weblogs Guide posts blogging jobs weekly in the forum

    Like

  11. scatslaves german enema black shits
    … band nylon let xenia seeberg porn xenia seeberg porn arm breast shaping …. watch free led scat men scat scat men scat imagine female orgasm squirts … … adult group activities, gym naked men, celebreties porn models, cfnm nurse, …. thick black ebony melons, girls doing scat, big clit free video, … anal sex scat shit eating pics sex scat porn videos gay scat · scat eating shit sex · scat shit eating sex · free scat shit videos · scat shit eating girls …
    shiting and pissing shitting in pantyhose desperate to poop

    Like

  12. What do you think about using meta keywords on blog posts?
    I heard told me to not bother with them a few months ago as they are no use anymore
    Shared this to my wall, very useful

    Like

Leave a comment

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