Sun Java SDK adalah sebuah produk open source dengan lisensi GPL. Source
codenya dapat didownload diwebsitenya, yang ajaib dari source code Sun
Java SDK ini adalah memiliki lisensi yang bermacam-macam selain GPL,
yaitu SCSL dan JRL.
Tutorial Cara Membuat Photo Album Pada HandPhone dengan Sun Java.
1.
Cari file Wireless Tool Kit atau dapat anda download di
http://java.sun.com/products/j2mewtoolkit
2.
Anda cari terlebih dahulu aplikasi aplikasi pendukung
sun java itu sendiri seperti
jdk-6u2-windows-i586-p.exe yang
dapat anda download pada link http://java.sun.com/products/j2mewtoolkit
atau
npp.5.9.8.Installer.
3.
Hal pertama yang harus anda lakukan adalah install
antara kedua file di atas.
4.
Jika kita telah mendownload file wireless tool kit
tersebut langkah selanjutnya anda buka dan jalankakn file yang telah anda
download seperti dibawah ini.
5.
Seteleh instalasi selesai langkah selanjutnya anda
jalankan program WTK 2.5.2 yang telah kita install.
6.
Untuk membuat sebuah aplikasi handhone yang baru dengan
extension .jar .java langkah yang harus anda lakukan adalah klik icon new
project pada toolbar.
7.
Setelah anda klik new project, maka akan muncul jendela
new project dan langkah yang harus anda lakukan adalah isikan project name dan
MIDlet Class Name dengan nama aplikasi yang akan kita buat. Kemudian klik
create project.
8.
Setelah kita create maka akan muncul jendela Setting
for project “PhotoAlbum”, disini anda dapat mengatur platform yang akan anda
gunakan agar sesuai/cocok dengan spesifikasi handphone yang anda akan buat.
Lalu klik OK jika telah selesai.
9.
Stelah and klik OK maka kita akan kembali ke jendela
utama dari WTK 2.5.2, dan akan di jelaskan letak/penempatan file pendukung aplikasi
baik itu gambar maupun script java.
Creating project
"PhotoAlbum"
1.
Untuk meletekan file dengan extension java anda simpan
pada direktori berikut
Place Java source files in
"C:\Documents and
Settings\dian\j2mewtk\2.5.2\apps\PhotoAlbum\src"
2.
Untuk menyimpan file gambar dengan extension .jpg .png
dll anda simpan pada direktori berikut
Place application resource files
in "C:\Documents and
Settings\dian\j2mewtk\2.5.2\apps\PhotoAlbum\res"
3.
Sedangkkan untuk menyimpan pustaka aplikasi yang akan
di masukan pada handphone anda masukan pada direktori berikut.
Place application library files
in "C:\Documents and
Settings\dian\j2mewtk\2.5.2\apps\PhotoAlbum\lib"
Settings updated
Project settings saved
10. Setelah itu anda ketikan file-fila java
pendukung sebagai interface untuk user pengguna agar dapat mengaoperasikan
aplikasi yang kita buat.
Untuk membuat aplikasi Photo
album kita memerlukan 3 buah file yaitu :
1. PhotoAlbum.java
package example.photoalbum;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Vector;
import
javax.microedition.io.Connector; import
javax.microedition.io.ContentConnection; import
javax.microedition.io.HttpConnection; import javax.microedition.lcdui.*; import
javax.microedition.midlet.*;
import javax.microedition.rms.*;
public class PhotoAlbum extends MIDlet implements
CommandListener, ItemStateListener, Runnable {
private Command
exitCommand;
private Command
okCommand;
private Command
optionsCommand;
private Command
backCommand;
private Command
cancelCommand;
private Form
progressForm;
private Gauge
progressGauge;
private Form
optionsForm;
private ChoiceGroup
borderChoice;
private ChoiceGroup
speedChoice;
private Display
display;
private PhotoFrame
frame;
private Alert
alert;
private Vector
imageNames;
private List
imageList;
private String
imageName;
private Thread
thread;
private final
String optionsName = "PhotoAlbum";
private
RecordStore optionsStore;
private boolean
firstTime = true;
public PhotoAlbum() { display = Display.getDisplay(this);
exitCommand = new
Command("Exit", Command.EXIT, 1); optionsCommand = new
Command("Options", Command.SCREEN, 1); okCommand = new
Command("Ok", Command.OK, 3);
backCommand = new Command("Back", Command.BACK, 3); cancelCommand = new
Command("Cancel", Command.CANCEL, 1);
frame = new PhotoFrame(); frame.setStyle(2);
frame.setSpeed(2);
frame.addCommand(optionsCommand);
frame.addCommand(backCommand);
frame.setCommandListener(this);
alert = new Alert("Warning"); setupImageList(); firstTime = true;
}
protected void startApp() { if (firstTime) { if (imageList.size() > 0)
{
display.setCurrent(imageList); openOptions(); restoreOptions();
} else {
alert.setString("No images
configured.");
display.setCurrent(alert, imageList);
}
firstTime
= false;
}
openOptions();
restoreOptions();
}
protected void pauseApp() { saveOptions();
}
protected void destroyApp(boolean
unconditional) {
saveOptions();
frame.reset(); // Discard images cached in the frame.
saveOptions();
closeOptions();
}
public void
commandAction(Command c, Displayable s) {
if (c ==
exitCommand) {
destroyApp(false); notifyDestroyed(); } else if (c == optionsCommand) {
display.setCurrent(genOptions());
} else if ((c
== okCommand) && (s == optionsForm)) { display.setCurrent(frame);
} else if (c
== List.SELECT_COMMAND) {
int i =
imageList.getSelectedIndex();
imageName = (String)imageNames.elementAt(i); display.setCurrent(genProgress(imageList.getString(i))); thread = new Thread(this); thread.start();
} else if (c
== backCommand) {
display.setCurrent(imageList); } else if (c == cancelCommand) {
thread =
null;
alert.setString("Loading
images cancelled.");
display.setCurrent(alert, imageList);
}
}
public void
itemStateChanged(Item item) {
if (item ==
borderChoice) {
frame.setStyle(borderChoice.getSelectedIndex());
} else if
(item == speedChoice) {
frame.setSpeed(speedChoice.getSelectedIndex());
}
}
private Screen genOptions() { if (optionsForm == null) { optionsForm = new
Form("Options");
optionsForm.addCommand(okCommand);
optionsForm.setCommandListener(this);
optionsForm.setItemStateListener(this);
speedChoice = new ChoiceGroup("Speed", Choice.EXCLUSIVE);
speedChoice.append("Stop", null);
speedChoice.append("Slow", null); speedChoice.append("Medium",
null);
speedChoice.append("Fast", null);
speedChoice.append("Unlimited", null); speedChoice.setSelectedIndex(frame.getSpeed(),
true);
optionsForm.append(speedChoice);
borderChoice = new ChoiceGroup("Borders",
Choice.EXCLUSIVE);
borderChoice.append("None", null);
borderChoice.append("Plain", null);
borderChoice.append("Fancy", null);
borderChoice.setSelectedIndex(frame.getStyle(), true); optionsForm.append(borderChoice);
}
return
optionsForm;
}
private Screen genProgress(String name)
{ if (progressForm == null)
{ progressForm = new
Form(name);
progressForm.addCommand(cancelCommand);
progressForm.setCommandListener(this);
progressGauge = new
javax.microedition.lcdui.Gauge("Loading images...", false, 9, 0);
progressForm.append(progressGauge);
} else {
progressGauge.setValue(0);
progressForm.setTitle(name);
}
return
progressForm;
}
private void setupImageList() { imageNames = new Vector(); imageList = new
List("Images", List.IMPLICIT);
imageList.addCommand(exitCommand);
imageList.setCommandListener(this);
for (int n = 1; n < 100; n++) { String nthImage =
"PhotoImage-" + n;
String
image = getAppProperty(nthImage);
if ((image == null) ||
(image.length() == 0)) {
break;
}
String
nthTitle = "PhotoTitle-" + n;
String
title = getAppProperty(nthTitle);
if ((title == null) ||
(title.length() == 0)) {
title = image;
}
imageNames.addElement(image); imageList.append(title, null);
}
imageNames.addElement("testchart:");
imageList.append("Test Chart", null);
}
public void run()
{
Thread
mythread = Thread.currentThread();
Vector images
= new Vector(5);
frame.reset();
try { try {
if
(imageName.startsWith("testchart:")) {
TestChart t = new TestChart(frame.getWidth(), frame.getHeight()); images = t.generateImages();
} else
{
images.addElement(createImage(imageName));
}
} catch
(IOException ex) {
try {
int namelen = imageName.length();
StringBuffer buf = new StringBuffer(namelen + 8); buf.append(imageName);
Runtime rt = Runtime.getRuntime();
for (int i = 0;; i++) {
progressGauge.setValue(i % 10);
if (thread != mythread) {
break;
}
buf.setLength(namelen);
buf.append(i);
buf.append(".png");
String name = buf.toString();
images.addElement(createImage(name));
}
}
catch (IOException io_ex) {
}
} catch
(SecurityException se_ex) {
}
if (thread
!= mythread) {
return;
}
if (images.size() > 0) { frame.setImages(images); display.setCurrent(frame);
} else {
alert.setString("Images could not be loaded.");
display.setCurrent(alert, imageList);
}
}
catch (OutOfMemoryError err) {
int size = images.size();
if (size
> 0) {
images.setSize(size - 1);
}
if (thread
!= mythread) {
return;
}
alert.setString("Not enough memory for
all images.");
if
(images.size() <= 0) {
display.setCurrent(alert, imageList);
} else {
frame.setImages(images);
display.setCurrent(alert, frame);
}
}
}
private Image createImage(String name)
throws IOException { if
(name.startsWith("/")) {
// Load as a resource with
Image.createImage return
Image.createImage(name); } else
if (name.startsWith("http:")) {
// Load
from a ContentConnection
HttpConnection c = null;
DataInputStream is = null;
try {
c =
(HttpConnection)Connector.open(name);
int
status = c.getResponseCode();
if
(status != 200) {
throw new IOException("HTTP Response Code = " + status);
}
int
len = (int)c.getLength();
String
type = c.getType();
if
(!type.equals("image/png") &&
!type.equals("image/jpeg")) { throw new
IOException("Expecting image, received " + type);
}
if
(len > 0) {
is
= c.openDataInputStream();
byte[] data = new
byte[len];
is.readFully(data);
return Image.createImage(data, 0, len);
} else
{
throw new IOException("Content length is missing");
}
} finally
{ if (is != null) { is.close();
}
if (c != null) { c.close();
}
}
} else {
throw new
IOException("Unsupported media");
}
}
void openOptions()
{
try {
optionsStore = RecordStore.openRecordStore(optionsName, true);
} catch
(RecordStoreException ex) {
alert.setString("Could not access options storage");
display.setCurrent(alert);
optionsStore = null;
}
}
void saveOptions() { if (optionsStore != null) { byte[] options = new byte[2]; options[0] =
(byte)frame.getStyle();
options[1]
= (byte)frame.getSpeed();
try {
optionsStore.setRecord(1, options,
0, options.length);
} catch
(InvalidRecordIDException ridex) {
// Record 1 did not exist,
create a new record (Should be 1) try {
int rec = optionsStore.addRecord(options, 0, options.length);
} catch (RecordStoreException
ex) {
alert.setString("Could not add options record");
display.setCurrent(alert);
}
} catch (RecordStoreException ex)
{
alert.setString("Could not save options"); display.setCurrent(alert);
}
}
}
void
restoreOptions() {
if (optionsStore != null) { try {
byte[]
options = optionsStore.getRecord(1);
if (options.length == 2) {
frame.setStyle(options[0]);
frame.setSpeed(options[1]);
if (optionsForm != null)
{
borderChoice.setSelectedIndex(options[0], true);
speedChoice.setSelectedIndex(options[1], true);
}
return; // Return all set
}
} catch
(RecordStoreException ex) {
//
Ignore, use normal defaults
}
}
}
void closeOptions() {
if (optionsStore != null) { try {
optionsStore.closeRecordStore(); optionsStore = null;
} catch (RecordStoreException ex)
{
alert.setString("Could not close options storage");
display.setCurrent(alert);
}
}
}
}
2. Photo Frame.java
package example.photoalbum;
import java.util.Vector;
import javax.microedition.lcdui.*;
class PhotoFrame extends Canvas implements Runnable {
private static
final int[] speeds = { 999999999, 500, 250, 100, 0 };
private int style;
private int speed;
private Vector
images;
private int index;
private int
imageX;
private int
imageY;
private int imageWidth;
private int
imageHeight;
private Thread
thread;
private Image
image;
private Image
bimage;
private long
paintTime;
private long
statsTime;
int frameCount;
int frameRate;
PhotoFrame() {
image = Image.createImage(getWidth(),
getHeight()); setStyle(0); setSpeed(0);
}
void
setImages(Vector images) {
this.images =
images;
if
(images.size() > 0) {
Image image =
(Image)images.elementAt(0);
imageWidth = image.getWidth();
imageHeight = image.getHeight();
} else { imageWidth = 0; imageHeight = 0; }
index = 0;
imageX = (getWidth() - imageWidth) /
2; imageY = (getHeight() -
imageHeight) / 2;
genFrame(style, imageX, imageY, imageWidth, imageHeight);
}
void next() {
if ((images == null) || (++index >=
images.size())) { index = 0;
}
}
void previous() {
if ((images != null) &&
(--index < 0)) { index =
images.size() - 1;
} else { index = 0;
}
}
void reset() { images = null; thread = null;
}
protected void
keyPressed(int keyCode) {
int action =
getGameAction(keyCode);
switch (action) { case RIGHT:
if (thread
== null) {
next(); repaint();
}
break;
case LEFT:
if (thread == null) { previous(); repaint();
}
break;
case FIRE:
if (thread == null) { thread = new Thread(this);
thread.start(); } else {
synchronized (this) {
this.notify();
}
thread
= null;
}
break;
}
}
protected void keyRepeated(int keyCode)
{ keyPressed(keyCode);
}
void setSpeed(int speed) { this.speed = speed;
statsTime = 0;
}
int getSpeed() { return speed;
}
void setStyle(int
style) {
this.style =
style;
genFrame(style, imageX, imageY, imageWidth, imageHeight);
}
int getStyle() { return style;
}
protected void showNotify() { if ((images != null) &&
(images.size() > 1)) {
thread = new Thread(this);
thread.start();
}
}
protected void hideNotify()
{
thread = null;
}
boolean intersectsClip(Graphics g, int x,
int y, int w, int h) { int cx =
g.getClipX();
if ((x + w) <= cx) { return false;
}
int cw =
g.getClipWidth();
if (x > (cx + cw)) { return false;
}
int cy =
g.getClipY();
if ((y + h) <= cy) { return false;
}
int ch =
g.getClipHeight();
if (y > (cy + ch)) { return false;
}
return true;
}
public void run()
{
Thread mythread =
Thread.currentThread(); long
scheduled = System.currentTimeMillis();
statsTime = scheduled;
paintTime = scheduled;
frameCount = 0;
frameRate = 0;
while (thread
== mythread) {
scheduled
+= speeds[speed];
long delta
= scheduled - paintTime;
if (delta
> 0) {
synchronized (this) {
try {
this.wait(delta);
}
catch (InterruptedException e) {
}
}
}
next(); repaint();
serviceRepaints();
}
}
protected void
paint(Graphics g) {
paintTime =
System.currentTimeMillis();
if (image !=
null) {
int cx =
0;
int cy =
0;
int cw =
0;
int ch =
0;
if (((cx = g.getClipX()) <
imageX) || ((cy = g.getClipY()) < imageY) || ((cx + (cw =
g.getClipWidth())) > (imageX + imageWidth)) || ((cy + (ch = g.getClipHeight()))
> (imageY + imageHeight))) {
g.drawImage(image, 0, 0, Graphics.LEFT | Graphics.TOP);
if
(frameRate > 0) {
g.fillRect(0, getHeight(), 60, 20);
g.drawString("FPS = " + frameRate, 0, getHeight(),
Graphics.BOTTOM | Graphics.LEFT);
}
}
if ((images != null) &&
(index < images.size()) && intersectsClip(g, imageX,
imageY, imageWidth, imageHeight)) {
g.drawImage((Image)images.elementAt(index), imageX, imageY,
Graphics.LEFT | Graphics.TOP);
}
frameCount++;
int delta
= (int)(paintTime - statsTime);
if ((delta > 1000) &&
(delta < 10000)) {
frameRate = (((frameCount * 1000) + 500) / delta); frameCount = 0; statsTime = paintTime;
repaint(); // queue full repaint to display frame rate
}
}
}
private void
genFrame(int style, int x, int y, int width, int height) {
Graphics g =
image.getGraphics();
g.setColor(0xffffff);
g.fillRect(0,
0, image.getWidth() + 1, image.getHeight() + 1);
g.translate(x,
y);
paintBorder(g,
style, width, height);
}
private void paintBorder(Graphics g, int
style, int w, int h) { if (style
== 1) {
g.setGrayScale(128);
g.drawRect(-1, -1, w + 1, h + 1);
g.drawRect(-2,
-2, w + 3, h + 3);
}
if (style ==
2) {
if (bimage
== null) {
bimage
= genBorder(); // Generate the border image
}
int bw = bimage.getWidth(); int bh = bimage.getHeight();
int i;
g.setGrayScale(128);
g.drawRect(-1, -1, w + 1, h + 1);
g.drawRect(-bw - 2, -bh - 2, w + (bw * 2) + 3, h + (bh * 2) + 3);
g.drawImage(bimage, -1, -1, Graphics.BOTTOM | Graphics.RIGHT);
g.drawImage(bimage, -1, h + 1, Graphics.TOP | Graphics.RIGHT);
g.drawImage(bimage, w + 1, -1, Graphics.BOTTOM | Graphics.LEFT);
g.drawImage(bimage,
w + 1, h + 1, Graphics.TOP | Graphics.LEFT);
for (i =
((h % bh) / 2); i < (h - bh); i += bh) {
g.drawImage(bimage, -1, i, Graphics.RIGHT | Graphics.TOP);
g.drawImage(bimage, w + 1, i, Graphics.LEFT | Graphics.TOP);
}
for (i =
((w % bw) / 2); i < (w - bw); i += bw) {
g.drawImage(bimage, i, -1, Graphics.LEFT | Graphics.BOTTOM);
g.drawImage(bimage, i, h + 1, Graphics.LEFT | Graphics.TOP);
}
}
}
private Image
genBorder() {
Image image =
Image.createImage(5, 5);
Graphics g = image.getGraphics(); g.setColor(255, 255, 255);
g.fillRect(0,
0, 5, 5);
g.setColor(128, 0, 255);
g.drawLine(2,
1, 2, 3); // vertical
g.drawLine(1,
2, 3, 2); // horizontal
return image;
}
}
3. TestChart.java
package example.photoalbum;
import java.util.Vector;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
class TestChart { /** lebar canvas */
int w;
/** tinggi canvas */
int h;
/** tulisan untuk
drawing text */
Font font;
/** tinggi tulisan
*/
int fh;
/** tinggi judul
*/
int titleHeight;
/** jarak antara
item */
int pad;
/** ukuran Pie chart digunakan untuk
mengatur tinggi dan lebar */ int
pieSize;
/** ukuran Bar chart digunakan untuk
mengatur tinggi dan lebar */ int
barSize;
/** nomor-nomor
frame */
int frameno;
public
TestChart(int width, int height) {
w = width; h = height;
font =
Font.getFont(Font.FACE_SYSTEM, Font.STYLE_PLAIN, Font.SIZE_SMALL);
fh =
font.getHeight();
pad = 2; titleHeight = fh + (pad * 2);
barSize = h -
(titleHeight + pad);
if (barSize
< 10) { // Don't let them get too small
barSize =
10;
}
if (barSize > ((w - pad) / 2)) { //
Shrink to 1/2 width barSize =
(w - pad) / 2;
}
pieSize =
barSize;
}
public Vector
generateImages() {
Vector v = new
Vector(4);
for (frameno = 0; frameno < 4;
frameno++) { Image image =
Image.createImage(w, h);
paint(image.getGraphics());
v.addElement(image);
}
return v;
}
public void paint(Graphics g) { g.setFont(font);
g.setGrayScale(255);
g.fillRect(0,
0, w, h);
int swidth = (pad * 2) +
font.stringWidth("Chart Samples"); int title_x = (w - swidth) / 2;
g.setGrayScale(128);
g.fillRoundRect(title_x, 0, swidth, fh, 5, 5);
g.setGrayScale(0);
g.drawRoundRect(title_x, 0, swidth, fh, 5, 5);
g.setColor(0,
0, 0);
g.drawString("Chart Samples", title_x + pad, pad, Graphics.TOP
|
Graphics.LEFT);
g.translate(0,
titleHeight + pad); // Translate to below title text
g.setColor(255, 0, 0);
g.fillArc(0,
0, pieSize, pieSize, 45, 270);
g.setColor(0,
255, 0);
g.fillArc(0,
0, pieSize, pieSize, 0, 45);
g.setColor(0,
0, 255);
g.fillArc(0,
0, pieSize, pieSize, 0, -45);
g.setColor(0);
g.drawArc(0,
0, pieSize, pieSize, 0, 360);
int yorig = barSize; int h1 = barSize / 3; int h2 = barSize / 2; int h3 = barSize; int avg = (h1 + h2 + h3) / 3;
g.translate((w
+ pad) / 2, 0);
int bw =
pieSize / 7;
if (bw < 2) { bw = 2;
}
if (frameno
> 0) {
g.setColor(255, 0, 0);
g.fillRect(bw * 1, yorig - h1, bw + 1, h1);
}
if (frameno
> 1) {
g.setColor(0, 255, 0);
g.fillRect(bw * 3, yorig - h2, bw + 1, h2);
}
if (frameno
> 2) {
g.setColor(0, 0, 255);
g.fillRect(bw * 5, yorig - h3, bw + 1, h3);
}
g.setColor(0);
g.drawRect(bw
* 1, yorig - h1, bw, h1);
g.drawRect(bw
* 3, yorig - h2, bw, h2);
g.drawRect(bw
* 5, yorig - h3, bw, h3);
// sumbu dari bar chart. g.setGrayScale(0);
g.drawLine(0,
0, 0, yorig);
g.drawLine(0,
yorig, barSize, yorig);
g.setStrokeStyle(Graphics.DOTTED);
g.drawLine(0,
yorig - avg, barSize, yorig - avg);
g.setStrokeStyle(Graphics.SOLID);
// kembali ke
kiri dan geser ke bawah
g.translate(-(w + pad) / 2, pieSize + pad);
}
}
11. Setelah itu ketiga file di atas anda simpan pada
direktori berikut :
C:\Documents and Settings\dian\j2mewtk\2.5.2\apps\Photoalbum\src\example\photoalbum
12. Langkah
selanjutnya anda masukan file gambar yang akan anda tampilkan. Masukan file
gambar pada direktori berikut :
C:\Documents and
Settings\dian\j2mewtk\2.5.2\apps\Photoalbum\res\example\photoalbum\images
13. Jika
file telah selesai anda masukan pada direktori yang sesuai maka anda kembali
pada jendela WTK 2.5.3 awal
14. Klik
open project untuk membuka project yang telah anda buat sebelumnya.
15. Setelah
itu anda pilih project photoAlbum yang telah anda buat sebelumnya.
lalu klik open project.
16. Jika
sukses maka akan muncul tampila Proeject
“PhotoAlbum” Loaded pada layar console
17. Untuk
menjalankan project yang kita buat kita klik run pada toolbar WTK 2.5.2
18. Setelah
kita run maka akan muncul tampilan di bawah ini, dan jalankan dengan menekan
tombol handphone menggunakan mouse.
19. Jika
aplikasi tersebut telah selesai dan berjalan dengan baik maka langkah
selanjutnya adalah menjadikan file tersebut dengan extension jar atau java aga
dapat di letakan pada handphone yang sebenaya dengan cara klik build pada
handphone.
20. Namun
anda harus menentukan tipe atau jenis handphone sebelum mem-build kedalam jar
atau java. Pilihan nya seperti gambar berikut. pada device kita pilih tipe
handphone yang akan anda berikan aplikasi ini.
21. Jika
telah kita pilih jenis device yang anda gunakan lalu klik bulid pada toolbar.
22. Tunggu
hingga muncul tulisan build complete pada layar console.
23. File
jar dan java dapat kita cari pada direktori berikut
24. Lalu
kita copy pada handphone kita sesuai dengan system operasi yang digunakan.
25. Install
pada handphone yang telah anda berikan file PhotoAlbum.jar atau
PhotoAlbum.java
Tidak ada komentar:
Posting Komentar