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 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
Advertisements

25 Comments »

  1. MSN I NIIPET
    MSN

    Comment by Bill — May 12, 2007 @ 5:25 am

  2. Looking at your site makes me wish I had started one like it….maybe I will now!

    Comment by Ancient History — May 23, 2007 @ 10:53 pm

  3. 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.

    Comment by sivamani — June 4, 2007 @ 9:24 pm

  4. hi sivamani,

    this program compiles and runs fine. Send me your code, environment variable configurations at ashikuzzaman@gmail.com so that I can investigate whats going wrong for you. Thanks.

    Comment by ashikuzzaman — June 4, 2007 @ 9:53 pm

  5. 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

    Comment by GoGolfer — July 12, 2007 @ 6:54 am

  6. Follow these guidelines and you will build that new home with little, or no, problems. 4 season sun room can help…

    Comment by JelaCaftNeolf — November 19, 2007 @ 1:24 am

  7. very interesting, but I don’t agree with you
    Idetrorce

    Comment by Idetrorce — December 15, 2007 @ 3:42 am

  8. Ðåãèñòðàöèÿ äîìåíà â çîíå .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

    Comment by noseTyncteddy — December 21, 2007 @ 6:49 pm

  9. 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.

    Comment by sachin — February 14, 2008 @ 1:30 am

  10. 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

    Comment by christian — June 18, 2008 @ 3:16 pm

  11. ok, this blog removes double minus, but i guess you get the point 😉

    Comment by christian — June 18, 2008 @ 3:17 pm

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

    Comment by Breessunc — July 7, 2008 @ 8:57 pm


  13. 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.

    Comment by Boosodslahted — July 19, 2008 @ 9:59 am

  14. 2kI’ll thingk about it.8g I compleatly agree with last post. ztr
    паркет 3r

    Comment by ламинат — August 24, 2008 @ 3:21 am

  15. 4qI’ll thingk about it.2b I compleatly disagree with last post . zyi
    паркет и ламинат 0x

    Comment by ламинат — August 24, 2008 @ 4:24 am

  16. 1mThank’s.5h I compleatly agree with last post. twj
    ламинат 9w

    Comment by ламинат — August 24, 2008 @ 5:01 am

  17. 1mI’ll thingk about it.1a I compleatly agree with last post. yjy
    ламинат 8z

    Comment by ламинат — August 24, 2008 @ 1:48 pm

  18. 4qGood idea.8g I compleatly disagree with last post . obz
    ламинат купить 9y

    Comment by ламинат — August 24, 2008 @ 6:02 pm

  19. 8dGood idea.0v I compleatly agree with last post. jqg
    паркет и ламинат 9w

    Comment by ламинат — August 24, 2008 @ 7:06 pm

  20. YAA Adding this to my bookmarks. Thank You

    Comment by gold high heel shoes — June 14, 2009 @ 6:55 am

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

    Comment by IrratryAcargy — April 23, 2010 @ 4:36 am

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

    Comment by mecountee — September 27, 2010 @ 3:13 pm

  23. 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

    Comment by rotzzips — September 29, 2010 @ 5:21 am

  24. 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

    Comment by scatpeeD — February 2, 2011 @ 2:19 pm

  25. 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

    Comment by malorie — May 12, 2017 @ 10:49 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: