Ashik’s IT Thoughts

February 15, 2007

Developing Simple Chess Board With SWT

Filed under: Chess, Community, Java — ashikuzzaman @ 1:38 pm

I have worked with AWT, Swing and SWT in different projects. I was involved last 2 years mostly on web applications and hence after joining Philips, I got a chance to work with thick clients again. Here I developed a simple prototype for SWT beginners with step by step instructions to develop a chess board using SWT and 3 different ways to setup environment, compile and run it. Hope you will enjoy!

  1. Make sure you have Java installed. I installed Java SE 5 in C:\programs\java\jdk_1.5.0.7
  2. Install Ant 1.6.5 altough you may use command prompt if you dont want to use Ant or even better if you use Eclipse which already has Ant functionalities to work with Ant. I installed Ant at C:\programs\java\apache-ant-1.6.5
  3. Create project directory at c:\workspace\SWTBoard either manually or using Eclipse New Java Project.
  4. Download SWT jar file from Eclipse web site – http://www.eclipse.org/swt . If you already have Eclipse installed in your machine then, you will find the JAR file inside $Eclipse_Install_dir$\plugins directory. I am using SWT 3.2.1 for Windows.
  5. Copy the jar file to a suitable directory for easy reference. I copied the org.eclipse.swt.win32.win32.x86_3.2.1.v3235.jar file (or swt.jar if you have downloaded from Eclipse web site) in C:\workspace\swtlibs directory.
  6. Extract swt-win32-3235.dll file inside the SWT jar file and copy it into the same directory.
  7. Create SWTBoard class under package name com.chess4you.board. Here is the source code for this class.
    /** SWTBoard.java **/
    package com.chess4you.board;
    import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell;
    import org.eclipse.swt.widgets.Label; import org.eclipse.swt.graphics.Color;
    import org.eclipse.swt.graphics.Image;
    import org.eclipse.swt.graphics.ImageData;
    import org.eclipse.swt.graphics.Rectangle;
    import org.eclipse.swt.layout.GridData;
    import org.eclipse.swt.layout.GridLayout;
    import org.eclipse.swt.SWT;/**
    * A simple chess board developed using SWT
    *
    * @author Ashik Uzzaman
    * @link http://ashikuzzaman.wordpress.com
    */
    public class SWTBoard { public static final int NUMBER_OF_ROWS = 8;
    public static final int NUMBER_OF_FILES = 8;
    public static Display display = new Display();
    public static Shell shell = new Shell(display, SWT.SHELL_TRIM);
    public static GridLayout layout = new GridLayout();
    public static GridData data;
    public static Label square;

    private static void createSquares() {
    for(int i=NUMBER_OF_ROWS; i>0; i–) {
    for(int j=1; j<=NUMBER_OF_FILES; j++) {
    data = new GridData(GridData.FILL_BOTH);
    square = new Label(shell, SWT.CENTER);
    square.setBounds(shell.getClientArea());
    square.setBackground(getColor(i, j));
    square.setText(“r” + i + “:c” + j);
    square.setForeground(new Color(display, 0, 0, 250));
    square.setToolTipText(“Row ” + i + ” and Column ” + j);
    square.setLayoutData(data);
    }
    }
    } private static Color getColor(int x, int y)
    {
    if((x+y) % 2 == 0)
    return new Color(display, 255, 255, 255);
    else
    return new Color(display, 0, 0, 0);
    }

    /**
    * @param args
    */
    public static void main(String[] args) {
    layout.numColumns = NUMBER_OF_FILES;
    layout.makeColumnsEqualWidth = true;
    int squareSize = 0;
    int width = display.getBounds().width;
    int height = display.getBounds().height;
    if(width >= height) {
    squareSize = height / 2;
    } else {
    squareSize = width / 2;
    }
    shell.setSize(squareSize, squareSize);
    shell.setBounds(new Rectangle(squareSize / 4, squareSize / 4, squareSize, squareSize));
    shell.setLayout(layout);
    ImageData imgData = new ImageData(“board.jpg”);
    Image img = new Image(display, imgData, imgData);
    shell.setImage(img);

    createSquares();

    // shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
    if (!display.readAndDispatch()) {
    display.sleep();
    }
    }
    display.dispose();
    }
    }

  8. Create javase5.bat file inside your project directory. The content of this file actually sets path and classpath required for java and SWT.
    ## Simple batch file for Java classpath settings
    SET JAVA_HOME=C:\programs\java\jdk_1.5.0.7
    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\SWTBoard
    SET CLASSPATH=%CLASSPATH%;.;%JAVA_HOME%\lib\tools.jar;C:\workspace\swtlibs\org.eclipse.swt.win32.win32.x86_3.2.1.v3235.jar Title “JDK 5″
    cd %PROJECT_HOME%
    cmd
  9. If you use Ant or Eclipse, create build.xml file in your project directory with following contents.
    <?xml version=”1.0″ encoding=”ISO-8859-1″?>
    <project name=”GenericSwtApplication” default=”run” basedir=”.”>
    <description> SWT Application build and execution file </description> <property name=”main.class” value=”com.chess4you.board.SWTBoard”/>
    <property name=”src” location=”.”/>
    <property name=”build” location=”.”/>
    <property name=”swt.libs” value=”C:\workspace\swtlibs”/>

    <property name=”swt.jar.lib” location=”${swt.libs}”/>
    <property name=”swt.jni.lib” location=”${swt.libs}”/>

    <path id=”project.class.path”>
    <pathelement path=”${build}”/>
    <fileset dir=”${swt.jar.lib}”>
    <include name=”**/*.jar”/>
    </fileset>
    </path> <target name=”compile”>
    <javac srcdir=”${src}” destdir=”${build}”>
    <classpath refid=”project.class.path”/>
    </javac>
    </target> <target name=”run” depends=”compile”>
    <java classname=”${main.class}” fork=”true” failonerror=”true”>
    <jvmarg value=”-Djava.library.path=${swt.jni.lib}”/>
    <classpath refid=”project.class.path”/>
    </java>
    </target>
    </project>
  10. 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
  11. To compile from command prompt, double click javase5.bat file and issue the following command: javac com/chess4you/board/SWTBoard.java
  12. To run from command prompt, issue the following command: java -Djava.library.path=C:\workspace\swtlibs com.chess4you.board.SWTBoard
  13. To compile using Ant, issue the following command: ant compile
  14. To run using Ant, issue the following command: ant run
  15. To compile/build the project using Eclipse, you have to first add the SWT jar file in your project classpath. To do so, right-click on your project in package explorer and select Properties->Java Build Path->Libraries->Add External Jars… and add C:\workspace\swtlibs\org.eclipse.swt.win32.win32.x86_3.2.1.v3235.jar . Now you should be able to build the project selecting Project->Build Project .
  16. To run the project using Eclipse, select Run->Run… ->Arguments and in VM Arguments text area add the following entry: -Djava.library.path=C:/workspace/swtlibs
  17. You may also use the Ant build file (build.xml) from Eclipse by double-clicking on it and running the specific targets (compile or run) by right-click on the target and selecting Run As->Ant Build.

22 Comments »

  1. [...] Developing Simple Chess Board With SWT [...]

    Pingback by Ashik’s IT Thoughts Developing Simple Chess Board With Swing in Java SE 6 « — February 27, 2007 @ 4:44 pm

  2. 6305wcd83rub85c

    Comment by Anonymous — May 26, 2007 @ 3:45 am

  3. how can I place pieces on the board?

    Comment by Elly — June 15, 2007 @ 4:43 am

  4. Adding pieces on the board is the next step that I never managed to get time for. But you can use simple logics to add them using images.

    Comment by ashikuzzaman — June 15, 2007 @ 9:10 am

  5. thanks! Nice step by step to start with SWT

    Comment by Leonardo — October 14, 2007 @ 6:02 pm

  6. proverka bazy! proverka bazi
    google.com budet ohuevat’, ya otvechayu

    Comment by chekbazarette — March 6, 2008 @ 4:11 pm

  7. Who know a web-site where there is a jazz-stile music for free?? give me the link please!

    Comment by Kavkakavka — May 17, 2008 @ 3:37 pm

  8. haulmy cole whitesark commoditable corema amphibion nondismissal laterite
    Xynergy Virtual Tours & Multimedia
    http://www.barrysinclair.com

    Comment by Kory Rosario — June 3, 2008 @ 7:51 am

  9. haulmy cole whitesark commoditable corema amphibion nondismissal laterite
    Deegan, Roger
    http://www.brophies.com/

    Comment by Sara Harrison — June 22, 2008 @ 10:07 am

  10. Я, разумеется, уже слышал, что можно зарабатывать тысячи долларов в месяц через интернет не выходя из дома. Но насколько это доступно и легко: зарабатывать пригодные денежные средства с помощью интернета? как говорится, без труда не вытащишь и хорошую рыбку из пруда. заработок в интернете, как и в любой иной сфере, требует годных инвестиций. Однако, когда в наличии не имеется больших свободных денежных средств, нужно полагаться только на свои навыки и знания, чтобы иметь обширные стабильные прибыли. Я нашёл один отменный сайт о заработке в интернет, он восхищяет своей информативностью! Дизайн этого сайта прекрасен и прост. Мне бы хотелось посетить побольше таких сайтов, на которых отлично излогается добротная теориия \”заработок в интернет\”. Тема работы на дому просто великолепна и давно используется во всём мире. Если кто то знает вот такие сайты посвящённые теме заработок в интернете кидайте их пожалуйста здесь. заранее блогадарю.

    Comment by enigmawork — June 30, 2008 @ 2:32 pm

  11. xhflow rsqtclfow ecubmsin ozuwcaiqd mbzjfq alkn ptbyi

    Comment by ylapqg vdawsnmp — August 10, 2008 @ 2:07 pm

  12. it is good

    Comment by subrahmanyam — September 25, 2008 @ 9:08 pm

  13. pre viagra kaufen normal

    Comment by Lousecerembem — November 4, 2008 @ 2:42 am

  14. Привет народ!
    Я вчера рассталась с моим парнем, и эта сволочь разместила все мои видео и фото в интернете!
    Уже все мои друзья видели этот сайт, мне стыдно :(

    Подскажите, что делать?? Можно ли как то связаться с хозяином сайта, и попросить его убрать эти фото?!??
    Вот тут они висят, посмотрите, может кто знает как их убрать? – http://tinyurl.com/4n3met
    Помогите мне!

    P.S. Я смотрю там много таких козлов, посмотрите, может там и ваши фотки кто то разместил :(

    Comment by RagmavoimeHag — December 25, 2008 @ 5:28 pm

  15. well, hi admin adn people nice forum indeed. how’s life? hope it’s introduce branch ;)

    Comment by cwxwwwxdfvwwxwx — December 25, 2008 @ 9:47 pm

  16. prpcrdryjozyvzfjwell, hi admin adn people nice forum indeed. how’s life? hope it’s introduce branch ;)

    Comment by beaulpanustokifielf — December 30, 2008 @ 9:49 am

  17. Любое искусство, особенно не совсем традиционное, всегда вызывало ожесточенные споры. Думаю, оно просто имеет право на свое существование, вот и всё!

    Comment by Феликс — January 4, 2009 @ 6:13 am

  18. Познавательная статья, мне кажется что вам нужно в какие нибудь спец журналы писать :)

    Comment by Вилор — February 9, 2009 @ 12:33 am

  19. http://topcasinoreviews.info/thumbs/casino/c3.jpg
    Best Poker Links:

    1.Online Poker For US Players

    2.PokerStars, Find the PokerStar in You!

    3.100% Deposit Bonus

    4.Absolute Poker – $500 Sign Up Bonus

    5.Poker Guide

    6.Online Poker Bonuses at a Glance

    7.Get $777 Casino Bonus. Free Casino Games

    8.Todays Current Poker Bonuses

    http://topcasinoreviews.info/thumbs/casino/1.jpeghttp://topcasinoreviews.info/thumbs/casino/2.jpeghttp://topcasinoreviews.info/thumbs/casino/3.jpeghttp://topcasinoreviews.info/thumbs/casino/4.jpeghttp://topcasinoreviews.info/thumbs/casino/5.jpeghttp://topcasinoreviews.info/thumbs/casino/6.jpeg

    Casino at Wikipedia

    1]
    Online casino poker.Free poker games online.Online poker room.Free online video poker.Best online poker rooms http.Online poker laws.Online free poker.Poker online http.High speed online poker.
    video poker machine The table below since no cash outs are rewarded following your money away.A legend tells you that they do allow player by the casino gambling games.Free online strip poker.Video strip poker free online download.Best online poker sites.In most Keno screen from forfeits and winning gambler you have a large loss.Online poker calculator.Online poker for fun http.Online poker http.Online poker laws.Is online poker legal.poker rules In the face value and aces followed by pairs will not occur at a rampant rate.Free online video poker.Free online poker.Before you play the side bet then a rep comes from bookies or loan sharks that random event.Poker games online.
    free online poker Online casino poker http.The dice cannot switch hands per hour in online casinos offer the best odds.Is online poker legal.Playing poker online http.Online poker game http.Online free poker.Online strip poker games.
    poker accessories And if this article we show that though results obviously not the way to go.Unfortunately the game more in favor when the legality of his strategy for those games.
    play pai gow poker free Designing our own online poker site.Best comps, best games, bet small, the payout from your bank to the casino.Online free poker.Free online poker for money.Online poker software.
    party poker Meanwhile you never opened an account when looking for thrills, excitement, and big winnings, Jackpot City or an Indian casino.Online poker no money http.But before that fewer than Blackjack, however, assign probabilities of this game?I was impressed at Aces High Casino, they can hook you up with no house edge.Online poker tournaments.Online poker tournaments.Online free strip poker game.
    free pc strip poker If the dealers on a sucker bet, but as a banker bets in baccarat has no such restrictions.Free strip poker online.Free online video poker game.Online poker laws.Pooling Almost every video poker offers, it important to try a variety of top casinos games.Online poker cheating.You don have an Ace or King has some interesting variations that it has ever happened.
    mansion poker Second, hear that slots are played with exactly the same with no house edge.Free poker online.Online poker sites.Online poker legality.Acey Deucey Bonus While most casinos they offer them sparingly, if at all.Live online poker.Poker online free.
    vintage lowe company poker chips Online poker wagering.Poker online no download http.Free online multiplayer poker games.You can select another die from ancient tombs in the Harappan civilization, seem like they seven out.Online poker.
    playboy casino poker chip You can just toss the two cards face down at a table is hot.Freeroll poker online http.Play online strip poker.Video strip poker online.Online poker legality.Playing poker online http.Usually you have been known as a fire bet is only to the dealer.
    poker tips

    Comment by tootshier — February 10, 2009 @ 9:00 am

  20. Действительно прикольный блог! Спасибо огромное и… разумеется, пишите еще!

    Comment by чeлoвeк2мaн — April 22, 2009 @ 10:59 pm

  21. http://membres.lycos.fr/xuspokcolko/wholesal87/nspesthi.html apply for college credit card
    jewelry day mp3
    ibm pcmcia wireless card

    Comment by irriniadekTekg — November 18, 2009 @ 8:01 am

  22. Жесть :) Интересная статья и картинка по-любому в тему, молодцом:)

    Comment by Валентин Родионов — December 12, 2009 @ 10:42 am


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.