お絵かきiアプリの作成
では、お絵かきするiアプリを作成しましょう。ここでは、SampleApp.javaに、SampleAppクラスとMainCanvasクラスを用意することにします。
import java.io.*;
import javax.microedition.io.Connector;
import com.nttdocomo.ui.*;
public class SampleIApp extends IApplication {
public void start() {
Display.setCurrent(new MainCanvas(this));
}
}
class MainCanvas extends Canvas {
IApplication iapp;
int[][] data;
int selx,sely,selc;
int[] c_arr;
MainCanvas(IApplication app){
super();
this.iapp = app;
selx = 0;
sely = 0;
selc = 4;
c_arr = new int[]{Graphics.getColorOfRGB(255,255,255),
Graphics.getColorOfRGB(255,0,0),
Graphics.getColorOfRGB(0,255,0),
Graphics.getColorOfRGB(0,0,255),
Graphics.getColorOfRGB(0,0,0)};
data = new int[30][30];
this.setSoftLabel(Frame.SOFT_KEY_1, "COLR");
this.setSoftLabel(Frame.SOFT_KEY_2, "QUIT");
load();
}
public void load(){
InputStream input = null;
try {
input = Connector.openInputStream("scratchpad:///0;pos=0");
for(int i = 0;i < 30;i++)
for(int j = 0;j < 30;j++)
data[i][j] = input.read();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void save(){
OutputStream output = null;
try {
output = Connector.openOutputStream("scratchpad:///0;pos=0");
for(int i = 0;i < 30;i++)
for(int j = 0;j < 30;j++)
output.write(data[i][j]);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void move(int dx,int dy){
selx += dx;
sely += dy;
selx = selx < 0 ? 0 : selx;
sely = sely < 0 ? 0 : sely;
selx = selx > 29 ? 29 : selx;
sely = sely > 29 ? 29 : sely;
this.repaint();
}
public void select(){
data[selx][sely] = selc;
repaint();
}
public void change(){
selc++;
selc = selc > 4 ? 0 : selc;
repaint();
}
public void end(){
save();
iapp.terminate();
}
public void paint(Graphics g) {
g.lock();
g.setColor(Graphics.getColorOfRGB(200, 200, 200));
g.fillRect(0, 0, 500, 500);
g.setColor(Graphics.getColorOfRGB(255, 255, 255));
g.fillRect(0, 0, 300, 300);
for(int i = 0;i < 30;i++)
for(int j = 0;j < 30;j++){
g.setColor(c_arr[data[i][j]]);
g.fillRect(i * 5, j * 5, 5, 5);
}
g.setColor(c_arr[selc]);
g.drawRect(selx * 5,sely * 5,5,5);
g.unlock(true);
}
public void processEvent(int type, int param) {
super.processEvent(type, param);
switch(type){
case Display.KEY_PRESSED_EVENT:
switch(param){
case Display.KEY_SOFT1:
change();
break;
case Display.KEY_SOFT2:
end();
break;
case Display.KEY_UP:
move(0,-1);
break;
case Display.KEY_DOWN:
move(0,1);
break;
case Display.KEY_RIGHT:
move(1,0);
break;
case Display.KEY_LEFT:
move(-1,0);
break;
case Display.KEY_SELECT:
select();
break;
}
}
}
}