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!
- Make sure you have Java installed. I installed Java SE 5 in C:\programs\java\jdk_1.5.0.7
- 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
- Create project directory at c:\workspace\SWTBoard either manually or using Eclipse New Java Project.
- 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.
- 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.
- Extract swt-win32-3235.dll file inside the SWT jar file and copy it into the same directory.
- 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();
}
} - 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 - 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> - 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
- To compile from command prompt, double click javase5.bat file and issue the following command: javac com/chess4you/board/SWTBoard.java
- To run from command prompt, issue the following command: java -Djava.library.path=C:\workspace\swtlibs com.chess4you.board.SWTBoard
- To compile using Ant, issue the following command: ant compile
- To run using Ant, issue the following command: ant run
- 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 .
- 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
- 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.
[…] Developing Simple Chess Board With SWT […]
LikeLike
6305wcd83rub85c
LikeLike
how can I place pieces on the board?
LikeLike
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.
LikeLike
thanks! Nice step by step to start with SWT
LikeLike
proverka bazy! proverka bazi
google.com budet ohuevat’, ya otvechayu
LikeLike
Who know a web-site where there is a jazz-stile music for free?? give me the link please!
LikeLike
haulmy cole whitesark commoditable corema amphibion nondismissal laterite
Xynergy Virtual Tours & Multimedia
http://www.barrysinclair.com
LikeLike
haulmy cole whitesark commoditable corema amphibion nondismissal laterite
Deegan, Roger
http://www.brophies.com/
LikeLike
Я, разумеется, уже слышал, что можно зарабатывать тысячи долларов в месяц через интернет не выходя из дома. Но насколько это доступно и легко: зарабатывать пригодные денежные средства с помощью интернета? как говорится, без труда не вытащишь и хорошую рыбку из пруда. заработок в интернете, как и в любой иной сфере, требует годных инвестиций. Однако, когда в наличии не имеется больших свободных денежных средств, нужно полагаться только на свои навыки и знания, чтобы иметь обширные стабильные прибыли. Я нашёл один отменный сайт о заработке в интернет, он восхищяет своей информативностью! Дизайн этого сайта прекрасен и прост. Мне бы хотелось посетить побольше таких сайтов, на которых отлично излогается добротная теориия \”заработок в интернет\”. Тема работы на дому просто великолепна и давно используется во всём мире. Если кто то знает вот такие сайты посвящённые теме заработок в интернете кидайте их пожалуйста здесь. заранее блогадарю.
LikeLike
pre viagra kaufen normal
LikeLike
Привет народ!
Я вчера рассталась с моим парнем, и эта сволочь разместила все мои видео и фото в интернете!
Уже все мои друзья видели этот сайт, мне стыдно 😦
Подскажите, что делать?? Можно ли как то связаться с хозяином сайта, и попросить его убрать эти фото?!??
Вот тут они висят, посмотрите, может кто знает как их убрать? – http://tinyurl.com/4n3met
Помогите мне!
P.S. Я смотрю там много таких козлов, посмотрите, может там и ваши фотки кто то разместил 😦
LikeLike
well, hi admin adn people nice forum indeed. how’s life? hope it’s introduce branch 😉
LikeLike
prpcrdryjozyvzfjwell, hi admin adn people nice forum indeed. how’s life? hope it’s introduce branch 😉
LikeLike
Любое искусство, особенно не совсем традиционное, всегда вызывало ожесточенные споры. Думаю, оно просто имеет право на свое существование, вот и всё!
LikeLike
Познавательная статья, мне кажется что вам нужно в какие нибудь спец журналы писать 🙂
LikeLike
Действительно прикольный блог! Спасибо огромное и… разумеется, пишите еще!
LikeLike
http://membres.lycos.fr/xuspokcolko/wholesal87/nspesthi.html apply for college credit card
jewelry day mp3
ibm pcmcia wireless card
LikeLike
Жесть 🙂 Интересная статья и картинка по-любому в тему, молодцом:)
LikeLike
Да таков уж наш современный мир и боюсь с этим ни чего нельзя поделать:)
LikeLike
Wollte nur kurz hallo sagen
LikeLike
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
LikeLike
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.
LikeLike
Hello, I can not recognize how to add your web site in my rss reader. Can you Assist me, please
LikeLike
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.
LikeLike
Очень мне понравилось колечко с бриллиантом, а подарить некому.
Ищу красивые пальчики для самого прекрасного бриллианта в мире!!!
Милые, очаровательные девушки, отзовитесь !!! )))
LikeLike
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 🙂
LikeLike