Wednesday, January 14, 2009

The BlueJ Discuss forum

I ask many question on that milis(mailing list)

I try to ask some question on the BlueJ discuss.

The question is, How to connect using the real Mobile phones..
So my later script is REALY working :)
http://groups.google.com/group/bluej-discuss?hl=en

Wednesday, December 31, 2008

Server act

when server receive the datagram..

public void run() {
..
....
DatagramConnection dc = (DatagramConnection) Connector.open("datagram://:" + portString);
f.insert(1,new StringItem("Server ready on port "+portString,""));
sender = new Sender(dc);
while (true) {
Datagram dg = dc.newDatagram(100);
dc.receive(dg);
address = dg.getAddress();
f.insert(1,new StringItem(address+" : ",new String(dg.getData(), 0, dg.getLength())));
}
}
The dialog, ...:

Server : waiting in the front house (near street)
Server : I'm ready at here !
Server : (making sender)
Server : prepare for receiving my goods(making a box, 10 x 2 x 5)
Server : waiting until I receiving my goods
Server : I get the goods! I'll put in the box.
Server : (See the sender label) aaah, from my client!
Server : (Placing the goods)I opened the box, and place the data in the "f" table.

The receive method at DatagramConnection class



This important !
I think in the while(){} loop at the Server class, The Server is always receiving a blank datagram. But when i see in the Java Tutorial.

"The receive method waits forever until a packet is received. If no packet is received, the server makes no further progress and just waits. "

Monday, December 29, 2008

Connection ? : Datagram

I'm always been very interested in connection in mobile phone, because phone comes handy, most of all my friend have phone and still connected. Now i want to LEARN connection, a Datagram connection. Datagram connection is simpler than Socket, that's what Java Tutorial said.

So.. let's begin.
First, I copied all of class in the WTK2.5.2_01 (C:\WTK2.5.2_01\apps\NetworkDemo\classes\datagram) to BlueJ! (The Readme.txt file also :D )
Compile all, deploy.

As seen in the readme file, "Run two instances of the emulator", "One acts as the datagram server, and the other as the datagram client". So, i click the Deploy button twice, and i get two emulator. After that, i go to the first emulator, and set that as server, and then set the client. I try to send a message to server, and in the server phone, i get the message. And then i try the other way. It Work !

That is the basic connection, i gonna edit them all.

updated!
The first thing that I do is, give the Server a Name !
So, in the Server class, I declare new variable called ServerName, and add new Constructor. Also a method that return the server name.
The variable
..
....

private DatagramMIDlet parent;
private Display display;
private String serverName; /**here*/
private Form f;
private StringItem si;
private TextField tf;
..
..

the new Constructor
..
...
display.setCurrent(f);
}

public Server(DatagramMIDlet m, int p, String name) {
parent = m;
port = p;
serverName = name;
display = Display.getDisplay(parent);
f = new Form(name);
si = new StringItem("Status:", " ");
tf = new TextField("Send:", "", 30, TextField.ANY);
f.append(si);
f.append(tf);
f.addCommand(sendCommand);
f.addCommand(exitCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
...
..

And.. getServerName() method,
public String getServerName()
{
return serverName;
}

I also edited the DatagramMIDlet class, so the server implementing my constructor(look at the commandAction method)
if (name.equals(SERVER)) {
Server server = new Server(this, port,"The Server !");
server.start();
} else {
Client client = new Client(this, port);
client.start();
}

Compile, Deploy, try becoming the Server, see what i have been changed ? :)

updated!
I have been edited many code of the server and client class
because of to much, i copy paste it directly

first, the server class

import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;

public class Server implements Runnable, CommandListener {

private DatagramMIDlet parent;
private Display display;
private String serverName;
private Form f;
private TextField tf;
private Command sendCommand = new Command("Send", Command.ITEM, 1);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
Sender sender;
private String address;
private int port;

..
......
...

public Server(DatagramMIDlet m, int p, String name) {
parent = m;
port = p;
serverName = name;
display = Display.getDisplay(parent);
f = new Form(name);
tf = new TextField("Send:", "", 30, TextField.ANY);
f.append(tf);
f.addCommand(sendCommand);
f.addCommand(exitCommand);
f.setCommandListener(this);
display.setCurrent(f);
}

....
.......
....

public void run() {
String portString = String.valueOf(port);
try {
f.insert(1,new StringItem("Waiting for connection on port"+portString,""));/**here*/
DatagramConnection dc = (DatagramConnection) Connector.open("datagram://:" + portString);

sender = new Sender(dc);

while (true) {
Datagram dg = dc.newDatagram(100);
dc.receive(dg);
address = dg.getAddress();
f.insert(1,new StringItem(address+" : ",new String(dg.getData(), 0, dg.getLength())));/**here*/
}
} catch (IOException ioe) {
Alert a = new Alert("Server", "Port " + portString
+ " is already taken.", null, AlertType.ERROR);
a.setTimeout(Alert.FOREVER);
a.setCommandListener(this);
display.setCurrent(a);
} catch (Exception e) {
e.printStackTrace();
}
}

public void commandAction(Command c, Displayable s) {
if ((c == sendCommand) && !parent.isPaused()) {
if (address == null) {
f.insert(3,new StringItem("Ooops! ","No destination address")); /**here*/
} else {
sender.send(address, tf.getString()); /**here*/
f.insert(1,new StringItem("Me(Server) : ",tf.getString()));/**here*/
tf.setString("");/**here*/
}
}

public String getServerName()
{
return serverName;
}

public String[] breakString(String s)
{
char[] ca = s.toCharArray();
String[] sa = {};
int h = 0;

for(int w = 0;w <= ca.length-1;w++)
{
if(ca.equals(" "))
{
h = h + 1;
}
else
{
sa[h] = sa[h]+ca[w];
}
}
return sa;
}

}

The Client class

import java.io.IOException;

import javax.microedition.io.*;
import javax.microedition.lcdui.*;


public class Client implements Runnable, CommandListener {
private DatagramMIDlet parent;
private int port;
private String ip; /**here*/
private Display display;
private Form f;
private TextField tf;

private Command sendCommand = new Command("Send", Command.ITEM, 1);
private Command exitCommand = new Command("Exit", Command.EXIT, 1);

Sender sender;

..
...
...

public Client(DatagramMIDlet m, int p, String IP) {
parent = m;
port = p;
this.ip = IP; /**here*/
display = Display.getDisplay(parent);
f = new Form("Datagram Client");
tf = new TextField("Send:", "", 30, TextField.ANY);
f.append(tf);
f.addCommand(sendCommand);
f.addCommand(exitCommand);
f.setCommandListener(this);
display.setCurrent(f);
}
..
...
...
public void run() {
String portString = String.valueOf(port);
try {
DatagramConnection dc = (DatagramConnection) Connector.open("datagram://"+ip+":" + portString); /**here*/

f.insert(1,new StringItem("Waiting for connection "+ip+" on port "+portString,""));/**here*/

sender = new Sender(dc);

while (true) {
Datagram dg = dc.newDatagram(100);
dc.receive(dg);

// Have we actually received something or
// is this just a timeout ?
if (dg.getLength() > 0) {
f.insert(1,new StringItem("Server : ",new String(dg.getData(), 0, dg.getLength()))); /**here*/
}
}
} catch (ConnectionNotFoundException cnfe) {
....
.....
..
public void commandAction(Command c, Displayable s) {
if ((c == sendCommand) && !parent.isPaused()) {
sender.send(null, tf.getString());
f.insert(1,new StringItem("Me(Client) : ",tf.getString()));/**here*/
tf.setString("");/**here*/
}

if (c == exitCommand) {
parent.destroyApp(true);
parent.notifyDestroyed();
}
}

public void stop() {
}

}

And the DatagramMIDlet class

import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;

public class DatagramMIDlet extends MIDlet implements CommandListener {

private static final int DEFAULT_PORT = 5555;
private String IP_ADDRESS;
private static final String DEFAULT_IP = "202.3.213.129";
private static final String SERVER = "Server";
private static final String CLIENT = "Client";
private static final String[] names = { SERVER, CLIENT };
private static Display display;
private Form f;
private ChoiceGroup cg;
private TextField portField;
private TextField ipField; /**here*/
private boolean isPaused;
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Command startCommand = new Command("Start", Command.ITEM, 1);

public DatagramMIDlet() {
display = Display.getDisplay(this);
f = new Form("Datagram Demo");
cg = new ChoiceGroup("Please select peer", Choice.EXCLUSIVE, names,null);
f.append(cg);
portField = new TextField("Port number:", String.valueOf(DEFAULT_PORT),6, TextField.NUMERIC);
ipField = new TextField("IP address:", DEFAULT_IP,20, TextField.ANY);/**here*/
f.append(ipField);/**here*/
f.append(portField);

....
........
......

public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == startCommand) {
String name = cg.getString(cg.getSelectedIndex());
int port = Integer.parseInt(portField.getString());
String ip = ipField.getString(); /**here*/

if (name.equals(SERVER)) {
Server server = new Server(this, port,"The Server");/**here*/
server.start();
} else {
Client client = new Client(this, port, ip);
client.start();
}
}
}
}

Saturday, December 27, 2008

Playing with Graphics

Now, i want to make an application that draw a line, and i have to matter with MIDlet image class, and MIDlet Graphics. So here it is.

...
public class DrawLine extends MIDlet implements CommandListener
{

Form screen;
Image line;
TextField input_length;
Graphics gr;

/**
* Called by the Application Management Software (AMS) when the MIDlet
* begins execution. The AMS is the software on a device that manages
* the downloading and life-cycle of MIDlets. When this constructor
* returns, the AMS places the MIDlet in the Paused state.
*/
public DrawLine()
{
screen = new Form("Draw.. Line...");
line = Image.createImage(screen.getWidth(),50);
gr = line.getGraphics();
input_length = new TextField("Input Length Here","",10,TextField.NUMERIC);
screen.append(input_length);
screen.append(line);
screen.addCommand(new Command("Draw", Command.OK, 0));
screen.addCommand(new Command("Exit", Command.EXIT, 0));
screen.setCommandListener(this);
}
...
..
public void startApp()
{
Display.getDisplay(this).setCurrent(screen);
}
..
..
public void commandAction(Command c, Displayable d)
{

if(c.getLabel().equals("Exit"))
{
notifyDestroyed();
}
else if(c.getLabel().equals("Draw"))
{
Graphics g = line.getGraphics();
int length = Integer.parseInt(input_length.getString());
screen.delete(1);
g.setColor(255,255,255);
g.drawLine(0,20,g.getClipWidth(),20); // delete previouse image with white color ^_^"
g.setColor(0,0,0);
g.drawLine(0,20,length,20);
input_length.setString("");
screen.append(line);
}

}
}

Compile, Deploy, just input the length to the text box, and then click draw, it should draw a line with your input length in pixels.
After succeed with that, i want to make improvements. I crated a new class called DrawRectangle. I just add a new input field (TextField) because it's a rectangle who have width and height.

import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;

/**
* Class DrawRectangle - a simple MIDlet application that create rectangle image with user input
*
* @author Keenan M
* @version 1.0 :P
*/

public class DrawRectangle extends MIDlet implements CommandListener
{

Form screen;
Image rectangle;
TextField input_width;
TextField input_height;
Graphics gr;

public DrawRectangle()
{
screen = new Form("Draw.. Rectangle...");
rectangle = Image.createImage(screen.getWidth(),screen.getHeight());
gr = rectangle.getGraphics();
input_width = new TextField("Input Length Here","",10,TextField.NUMERIC);
input_height = new TextField("Input Length Here","",10,TextField.NUMERIC);
screen.append(input_width);
screen.append(input_height);
screen.append(rectangle);
screen.addCommand(new Command("Draw", Command.OK, 0));
screen.addCommand(new Command("Exit", Command.EXIT, 0));
screen.setCommandListener(this);
}

public void startApp()
{
Display.getDisplay(this).setCurrent(screen);
}

public void pauseApp()
{
}

public void destroyApp(boolean unconditional)
{
}

public void commandAction(Command c, Displayable d)
{

if(c.getLabel().equals("Exit"))
{
notifyDestroyed();
}
else if(c.getLabel().equals("Draw"))
{
Graphics gr = rectangle.getGraphics();
int width = Integer.parseInt(input_width.getString());
int height = Integer.parseInt(input_height.getString());
screen.delete(2);
/** it's a clearing time */
gr.setColor(255,255,255);
gr.fillRect(1,1,screen.getWidth(),screen.getHeight());
/** end of clearing */
gr.setColor(0,0,0);
gr.drawRect(1,1,width,height);
input_width.setString("");
input_height.setString("");
screen.append(rectangle);
}
}
}

Compile, Deploy, it's work, that code make me draw a rectangle :D.

updated!
Hmm, I think I should rename my Application to Drawer. woke, it's done.
Now, i want to make an application that make a String Image. with method drawString() in the graphics class. there it is.

import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.*;

/**
* Class DrawString - Draw string image
*
* @author Keenan
* @version 1.0
*/
public class DrawString extends MIDlet implements CommandListener
{

Form screen;
Image st;
TextField input;
Graphics gr;

public DrawString()
{
screen = new Form("Draw.. String...");
st = Image.createImage(screen.getWidth(),15); // << string
gr = st.getGraphics();
input = new TextField("Input Here","",6+1+6+1+4,TextField.ANY);
screen.append(input);
screen.addCommand(new Command("Draw", Command.OK, 0));
screen.addCommand(new Command("Exit", Command.EXIT, 1));
screen.setCommandListener(this);
}

public void startApp()
{
Display.getDisplay(this).setCurrent(screen);
}

public void pauseApp()
{
}

public void destroyApp(boolean unconditional)
{
}

public void commandAction(Command c, Displayable d)
{
if(c.getLabel().equals("Exit"))
{
notifyDestroyed();
}
else if(c.getLabel().equals("Draw"))
{
Graphics g = st.getGraphics();
String v = input.getString();
//screen.delete(1); << so it's like log message
g.setColor(255,255,255);
g.fillRect(0,0,st.getWidth(),st.getHeight());
g.setColor(0,0,0);
g.drawString(v, 2,0,Graphics.LEFT|Graphics.TOP);
input.setString("");
screen.append(st);
}
}

}

Compilelalalala, Deploylalala, it works! :D

Making a Simple Calculator

I want to make a Calculator !


...
....
public class MyCalculator extends MIDlet implements CommandListener
{
...
....

After that, I preparing for the Item that i want to display in the screen
The item is :
3 TextField for inputing first value, second value, and the result.
1 ChoiceGroup for selecting the operator.
2 Command, one for exit, one for Calc(ulating) :D.
So..

..
...
private TextField fv = new TextField("First Value", "", 10, TextField.NUMERIC);
private TextField sv = new TextField("Second Value", "", 10, TextField.NUMERIC);
private TextField r = new TextField("Result", "", 50, TextField.ANY);
String cgOperator[] = {"Divide","Times","Add","Subtract"};
private ChoiceGroup operator = new ChoiceGroup("Operator",ChoiceGroup.EXCLUSIVE, cgOperator, null);
.....
.....

And of course, the commandAction() method..

...
..
public void commandAction(Command c, Displayable d) {
// If it's our exitCommand, destroy ourselves
if(c.getLabel().equals("Exit")) {
notifyDestroyed();
}else if(c.getLabel().equals("Calc")) {
int first_value = Integer.parseInt(fv.getString());
int second_value = Integer.parseInt(sv.getString());
double result = 0;
if(operator.isSelected(0))
{
result = first_value / second_value;
}else if(operator.isSelected(1))
{
result = first_value * second_value;
}else if(operator.isSelected(2))
{
result = first_value + second_value;
}else if(operator.isSelected(3))
{
result = first_value - second_value;

}
r.setString(""+result+""); // <<< (i can't parseDouble() it.. :D)
}
}
...
..

Compile it, Deploy it, and I get my MIDlet Calculator !!! yeah

Spam blog ?

aaah, my blog is marked by spam by the blogger
maybe that because i updated the blog by the existing post, not create a new blog
haha