Developing Simple Chess Board With SWT


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.

27 thoughts on “Developing Simple Chess Board With SWT

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

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

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

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

  3. prpcrdryjozyvzfjwell, hi admin adn people nice forum indeed. how’s life? hope it’s introduce branch 😉

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

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

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

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

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

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