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

27 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. pre viagra kaufen normal

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  20. Да таков уж наш современный мир и боюсь с этим ни чего нельзя поделать:)

    Comment by Григорий Филатов — January 14, 2010 @ 1:17 am

  21. Wollte nur kurz hallo sagen

    Comment by Alan28 — January 14, 2011 @ 6:54 pm

  22. Interesting blog! Is your theme custom made or did you download it from somewhere? A design like yours with a few simple adjustements would really make my blog stand out. Please let me know where you got your theme. Cheers

    Comment by Michael Cifuentes — January 30, 2011 @ 6:10 am

  23. Hi Mike, thanks for the apprecaition. I just applied a theme available freely in wordpress. If you login as admin and check Settings -> Apperance for your blog, you will see several themes available to be picked. You can also see the “Edit CSS” link there for some minor adjustments.

    Comment by ashikuzzaman — January 30, 2011 @ 8:39 am

  24. Hello, I can not recognize how to add your web site in my rss reader. Can you Assist me, please

    Comment by Jamal Goodner — February 2, 2011 @ 10:03 am

  25. That depends on what RSS Reader you use. If you use Google Reader, simply click on “Add Subscription” button on top left and give this site’s URL – https://ashikuzzaman.wordpress.com and Google Reader will add it.

    Comment by ashikuzzaman — February 2, 2011 @ 4:17 pm

  26. Очень мне понравилось колечко с бриллиантом, а подарить некому.
    Ищу красивые пальчики для самого прекрасного бриллианта в мире!!!
    Милые, очаровательные девушки, отзовитесь !!! )))

    Comment by Diamondsboy — May 27, 2011 @ 7:34 am

  27. You get 20pounds EXTRA CASH when you create an account with Casino Riva. No deposit, No credit card needed. You can spend them on any Casino game.
    This opportunity is now up for grabs for the first 1000 users of the site. I recommend you Create an account here http://tinyurl.com/6yamxnw. You can also rate and review the site here – http://mycasinoreview.net
    After you have created your account, send an email to ‘promotions@casinoriva.co.uk’ with the subject, ‘Riva 20 free’. Live it up 🙂

    Comment by NickHold — June 22, 2011 @ 10:36 am


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: