2008년 6월 30일 월요일

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

Java heap space관련
java -Xms[Min memory] -Xmx[max Memory] 클래스명 커멘드 라인에서 입력하세요.
java -Xms512m -Xmx1024m TestClass 이런식으로 입력 하시면 됩니다.

java Button Test

자바 gui질문입니다


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class ButtonPanel extends JPanel
implements ActionListener

//Button 생성
{ public ButtonPanel()
{ yellowButton = new JButton("Yellow");
blueButton = new JButton("Blue");
redButton = new JButton("Red");

add(yellowButton);
add(blueButton);
add(redButton);

yellowButton.addActionListener(this);
blueButton.addActionListener(this);
redButton.addActionListener(this);
}
//Event 처리
public void actionPerformed(ActionEvent evt)
{ Object source = evt.getSource();
Color color = getBackground();
if (source == yellowButton) color = Color.yellow;
else if (source == blueButton) color = Color.blue;
else if (source == redButton) color = Color.red;
setBackground(color);
repaint();
}

private JButton yellowButton;
private JButton blueButton;
private JButton redButton;
}


class ButtonFrame extends JFrame
{ public ButtonFrame()
{ setTitle("ButtonTest");
setSize(300, 200);
addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
} );

Container contentPane = getContentPane();
contentPane.add(new ButtonPanel());
}


//} 이 부분 삭제 여기서 에러 납니다.
//public class ButtonTest
//{


public static void main(String[] args)
{ JFrame frame = new ButtonFrame();
frame.show();
}
}


//뭘 원하시는 건지 잘 모르겠습니다. 정확히 말해주시면 좋겠는데.
//쪽지 한번 주세요

java Double Buffering

JAVA어플리케이션 그래픽

// Double Buffering 이미지를 메모리(버퍼 또는 가상화면)에 먼저
// 그리고 화면에 나중에 그리는 기법입니다.
// 화면은 캡쳐한거라 좀 이상해 보이지만 직접 실행하면 부드럽게 이동합니다.
import java.applet.Applet;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.util.Date;

public class Applet1 extends Applet implements Runnable {

Thread runner;
Image img; //버퍼 또는 가상화면
Graphics gc;
int px=10;

boolean stop = false;

public void start() {
img = createImage(300 , 300);
gc = img.getGraphics();

runner = new Thread(this);
runner.start();
}

public void stop() {
if(runner != null) {
stop = true;
runner = null;
}
}

public void run() {
while(!stop) {
px++;
if(px>300) px=10;

//게임의 배경이라고 생각하시면 됩니다. 지우기
gc.setColor(Color.WHITE);
gc.fillRect(0, 0, 300, 300);
// 게임의 비행기라고 생각하시면 됩니다. 그리기
gc.setColor(Color.black);
gc.drawRect(px, 10, 30, 30);

repaint();
try {
Thread.sleep(10); //지연 또는 화면을 갱신
} catch(Exception ex) {
System.out.println("Exception:" + ex.toString());
}
}
}

public void update(Graphics g) {
paint(g);
}

public void paint(Graphics g) {
g.drawImage(img, 10, 50, this); // 버퍼 이미지를 화면에 그리기.
}
}

2. drawOval에서 그려지는 모든 점의 좌표 구하는 방법 혹은 drawOval의 함수 내부
원이나 타원의 그려지는 모든 점의 좌표 구하는 법은 Math.sin() Math.cos() 명령을 이용하면 구할 수 있습니다. 연구해 보세요
.

count Digits

숫자자릿수세기



import java.util.StringTokenizer;


//import Program Files.java.util.*;


public class cal


{


public static void main(String[] args)


{


int i;

i=countDigits(500);

System.out.print(i);


}



private static int countDigits(int i) {


// TODO Auto-generated method stub


int count=0;


while(i>0){


i = i/10; //10 으로 0 이 될때까지 계속 나누면 됩니다.


count ++;


}// 이부분 연구해보세요.


return count;


}


}

2008년 6월 29일 일요일

자바스크립트 팝업창


이상 없이 잘 돌아가는 것 같은데 뭐가 문제인가요?

질문자 :
리눅스 페도라 core6에서 저 팝업창이 안뜨니깐 문제인 겁니다. 관심 감사합니다.^^
나:
아~~ 네 그렇군요 ^^.

ㅋㅋ

2008년 6월 28일 토요일

Android 3D tetris

Monolith Android

Monolith Android is a 3D tetris like game for the android mobile phone platform. The code is based on the SDK samples of the Android SDK. The intent is to create a fun to play game, and familiarize with the rich API of the android platform. The game uses openGL ES to render the graphics. As well as the classic tetris-like gameplay, the game provides additional game modes, "Monolith" and "Puzzle" (coming soon!). The Monolith name derives from the fact that the matrix that the game is played in, looks a bit like a monolith from the film "2001 a Space Odyssey".

Here’s the code

처음 이 프로그램 실행해 보고 신기하고 재미있어 나도 tetris하나 만들어 봤는데…. ᄏ OHA에서 1 2 3 4 등급에서 2등급 (Overall: In the 25th to 50th percentile of all submitted applications)주더라고요. 나중에 정리되면 한번 올릴게요 ^^;

java StringTokenizer

자바 디버깅좀 해주세요 ㅠㅠ

import java.util.StringTokenizer;

//import Program Files.java.util.*;

public class cal

{

//ArrayList arr=new ArrayList();

String result=new String();

public void splitter(String target,String token)

{

StringTokenizer st = new StringTokenizer(target,token);

String[] operand=new String[st.countTokens()];

int i;

for(i=0;st.hasMoreElements();i++)//수정부분

//while(st.hasMoreElement)//nextElement를 하고 남은 element가 있는지 검사

{

operand[i]=(String)st.nextToken();//수정부분

//자료를 뽑아 오기 위해서는 hasMoreElements와 nextToken() 메소드를 적절히 사용해야 합니다.

}

//System.out.println("결과는"+operator(operand));

operator(operand);

}

public void operator(String[] operand)

{

int[] in=new int[operand.length];

int i=0;

for(i =0;i<operand.length;i++)

{

in[i] = Integer.parseInt(operand[i]);

}

int result=0;

for(i=0;i<in.length-1 ;i++)// 수정부분

//님이 걸린 에러는 in[i+1]!=0 이부분에서 배열의 첨자가 최대+1 되기 때문에 발생했습니다.

{

result=in[i]+in[i+1];

}

System.out.println("결과는"+result);

//return result;

}

public static void main(String[] args)

{

cal c = new cal();

c.splitter("123+456","+");

}

}


//그리고 이클립스의 debug mode 를 사용해보세요..

2008년 6월 27일 금요일

JAVA File (파일생성) ,임시파일

JAVA File (파일생성) 이 안됩니다.



import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

import java.util.StringTokenizer;

public class JAVA_File {

public static void main(String[] args){

try{

// 파일을 읽어 옵니다.

File myFile = new File("C:/data.txt");

FileReader fileReader = new FileReader(myFile);

BufferedReader reader = new BufferedReader(fileReader);

// 파일을 만들고 저장 합니다.

//임시파일을 임시
//(C:\Documents and Settings\Administrator\Local Settings\Temp)
//
디렉토리에 만들고.. data2XXXXX.txt형태로 파일 생성
// XXXXX는 createTempFile 명령이 자동으로 생성합니다.

File imsiFile = File.createTempFile("data2",".txt");

// imsiFile.deleteOnExit();

FileWriter fw = new FileWriter(imsiFile);

BufferedWriter bw = new BufferedWriter(fw);

// 타이틀을 생성합니다.

String line1 = "=========================================================";

String line2 = " 계좌번호 고객명 비밀번호 계좌상태";

String line3 = "=========================================================";

// 타이틀을 파일에 저장 합니다.

bw.write(line1);bw.newLine();

bw.write(line2);bw.newLine();

bw.write(line3);bw.newLine();// 이부분 수정했습니다.

// 타이틀을 콘솔에 출력 합니다.

System.out.println(line1);

System.out.println(line2);

System.out.println(line3);

// 토큰화 객체

StringTokenizer stk = null;

String line = null;

while((line = reader.readLine()) != null) {

stk = new StringTokenizer(line, ";");

while(stk.hasMoreTokens()){

String result = stk.nextToken();

// 파일을 생성한다.

bw.write(result+" \t ");

// 콘솔화면에 출력한다.

System.out.print(result+" \t ");

}

bw.newLine();

bw.flush();

System.out.println("");

}

bw.close();

reader.close();

}catch(Exception ex){

ex.printStackTrace();

}

}

}

Open Handset Alliance 란?

Google 주도로 개발된 오픈 소스인 모바일을 위한 플랫폼「Android」Google 및 Android를 지지하는 각국의 휴대 캐리어·단말 메이커·반도체 메이커·소프트웨어 기업 등 현시점에서 34사로 구성된 단체.

차이나 모바일, NTT 도코모, KDDI, T-Mobile, Sprint Nextel 등 네트워크 오퍼레이터 7사. 인텔이나 NVIDIA, Qualcomm, TI 등 반도체 메이커 9사. HTC, LG, 모토로라, Samsung의 휴대 핸드 세트 메이커 4사. Google, eBay (Skype를 보유), NMS Communications 등 소프트웨어 10사. Wind River나 Aplix 등 코마샤라이제이션 기업 4사. 반대로 포함되지 않은 것은 노키아·마이크로소프트·Palm·애플이라고 하는 플랫폼 기업. 캐리어에서는 미국의 AT&T나 Verizon, 소프트뱅크 모바일 등.....

2008년 6월 26일 목요일

android 3gp Video/Music player sample

Notes

You can specify a directory path or a remote URL in the edit box
You can specify just an mp3 file to play music only
Choose any 3gp file from
http://daily3gp.com/ to view videos
The 4 buttons are for play, pause, reset and stop
When you specify a http or https url, we save the url contents to hard disk first and then play it
All the leg work was done by dahui. Many thanks!!
The icons are from here
MediaPlayer does not yet support any remote url’s or MPEG4 video AFAICT


Here’s the code

안드로이드 처음 시작할 때 열심히 연구한 code인데 지금 보니 재미있네요….

android 폰 출시 지연…"연내 힘들수도"

"사공이 많으면 배가 산으로 간다." 나의 생각은 Open Handset Alliance 이들이 사공같다..
Too many cooks spoil the broth.

2008년 6월 24일 화요일

To make by calendar array in Java

자바로 달력 배열로 만들기 질문입니다.


//주석 필요하시면 쪽지 주세요.

import java.util.*;

import java.text.*;

class Calendar_IN

{

public static void main(String[] args)

{

String start_date = "2008-06-25";

String end_date = "2009-06-24";

String[] inner_date = null;

Calendar cs = Calendar.getInstance();

Calendar ce = Calendar.getInstance();

SimpleDateFormat sdf = new SimpleDateFormat();

sdf.applyPattern("yyyy-MM-dd");

cs=getDate(start_date);

ce=getDate(end_date);

int count=1;

while(cs.before(ce))

{

count++;

cs.add(Calendar.DATE, 1);

}

cs=getDate(start_date);

inner_date = new String[count];

for(int i=0;i<count;i++){

inner_date[i]=(sdf.format(cs.getTime()));

cs.add(Calendar.DATE, 1);

}

for(int i=0;i<count;i++){

System.out.println(inner_date[i]);

}

}

private static Calendar getDate(String date) {

// TODO Auto-generated method stub

Calendar ret=Calendar.getInstance();;

ret.setTime(new Date(Integer.valueOf(date.substring(0, 4))-1900,

Integer.valueOf(date.substring(5, 7))-1,

Integer.valueOf(date.substring(8, 10))));

return ret;

}

}

java test

class Gesanggi{

void bb(int i,int j){

System.out.println(i+"*"+j+"="+(i*j));// 수정부분 " 삭제

}

}


public class Gesanggi1{

public static void main(String args[]){

int x,y;

Gesanggi f1=new Gesanggi();

x=Integer.parseInt(args[0]);

y=Integer.parseInt(args[1]);

f1.bb(x,y);

}

}

Number comparison out of the table ,JavaScript

테이블 안 숫자 비교


<script language="JavaScript">


<!--


function aaa() {


var nodeTr = document.getElementById("tb").childNodes[0];


var nodeTr2 = document.getElementById("tb2").childNodes[0];


var comp = 0;//추가부분


for (var i=0; i < nodeTr.childNodes.length; i++) {


for(var ii=0; ii < nodeTr.childNodes[i].childNodes.length; ii++) {


if(nodeTr.childNodes[i].childNodes[ii].childNodes[0].nodeValue == nodeTr2.childNodes[i].childNodes[ii].childNodes[0].nodeValue) {


comp++;//추가


}


}


}



if(comp == 9){alert('똑같다!!');}//추가및 이동


else{


alert('다르다!!');


return;


}




}


//-->


</script>



<input type="button" value="비교" onClick="aaa()">




<table id="tb" border="1" width="200">


<tr>


<td>2</td>


<td>3</td>


<td>5</td>


<tr>


<td>6</td>


<td>7</td>


<td>8</td>


<tr>


<td>4</td>


<td>3</td>


<td>6</td>


</tr>


</table>





<table id="tb2" border="1" width="200">


<tr>


<td>2</td>


<td>3</td>


<td>2</td>


<tr>


<td>6</td>


<td>7</td>


<td>8</td>


<tr>


<td>4</td>


<td>3</td>


<td>6</td>


</tr>


</table>

google android More haste, less speed

"올 하반기 안드로이드 플랫폼을 탑재한 휴대폰을 선보이겠다는 구글의 행보에 차질이 생긴 정황이 포착됐다. 일부에선 내년으로 넘어갈 수 있다는 얘기까지 나오고 있다."

이 가사를 읽고 급할수록 돌아가라 는 말을 하고 싶은데 영어가 안되네! ᄒᄒᄒ

Haste makes waste.


2008년 6월 23일 월요일

java 에 관련된 바둑 프로그램 소스 ( ramolra )


질문 자체가 뭘 원하시는지 잘 몰라서 대충 눈치로 .....

import java.io.*;
enum Area {Center, West, North, East, South}
//enum은 성격이 같은 상수를 정의하고 표현할 때 사용합니다.
//Center 는 0 South 는 4의 값을 의미합니다.

public class Coord2Area {
public static void main(String[] args) throws IOException{
Area areaXY = Area.Center;//areaXY를 0으로 초기화한다는 것이고요.

int level, pos;
char [] col = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T'};
//BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
//String nstr = br.readLine();
//int X = Integer.parseInt(nstr);
//String mstr = br.readLine();
//int Y = Integer.parseInt(mstr);
int X, Y;
for (X=0; X<=18; X++){ for (Y=0; Y<=18; Y++) { Boolean ws=false, nr=false, es=false, st=false; level= 0; pos=0; if (Y>=X && Y<=19-X) { areaXY = Area.West; level = 9 - X; pos = Y-X;} else if (Y>=X+1 && Y>=20-X) { areaXY = Area.North;
level = Y-9;
pos = X+Y-18; }
else if (Y>=21-X && Y<=X) {areaXY = Area.East; level = X-9; pos = X-Y;} else if (Y<=X-1 && Y<=20-X) { areaXY = Area.South; level = 9 - Y; pos = 18-Y-X;} else { areaXY = Area.Center; level = 0; pos = 0; } //System.out.print("X=" + X + ", Y=" + Y +"====> ");
//System.out.println("Area:" + areaXY.ordinal() + " level: "+ level +
// " pos: "+pos);


System.out.print(areaXY.ordinal() + ", ");
//areaXY.ordinal()은 방향의 상수 값을 얻고 그걸 System.out.print로 출력
//areaXY.ordinal() 방향의 상수값란 0,1,2,3,4
//프로그램상 " Center, West, North, East, South" 이걸로 표현됨.
}
System.out.println();
}
}
}

JavaScript 입력한값을 찾아 checkbox 체크



<HTML>
<HEAD>
<TITLE> AndroidHandFeel </TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- (자바스크립트) 입력한값을 찾아 체크박스 체크
window.onload = function() {
var 색 = prompt("색상을 입력하세요.", "");
if (document.getElementById(색) && document.getElementById(색).type == "checkbox") //색의 체크박스 판단
{
document.getElementById(색).checked = true; //체크박스 체크
}
else{alert("색상이 존재하지 않습니다.");}}

//-->
</SCRIPT>
</HEAD>
<BODY>
<p>


<input type="checkbox" name="orange">orange
<input type="checkbox" name="black">black
<input type="checkbox" name="blue">blue
<input type="checkbox" name="red">red
</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
</BODY>
</HTML>

Lotto Test


설명이 필요하시면 쪽지 주시고요 ^^.

import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;


public class LottoTest extends JFrame
{
JButton b1,b2,b3,b4,b5,b6,b7;
Panel p1,p2;
Label l;

public static void main(String arg[])

{
LottoTest lt = new LottoTest();
lt.display();
}

LottoTest()

{

b1=new JButton(" ");
b2=new JButton(" ");
b3=new JButton(" ");
b4=new JButton(" ");
b5=new JButton(" ");
b6=new JButton(" ");
p1=new Panel(new FlowLayout(50,50,50));
b7=new JButton(" ok ");

b7.addActionListener(new MyEventHandler());//추가하세요.

p2=new Panel(new FlowLayout(50,50,50));
l=new Label("0438115 김성진");
p1.add(b7);
p2.add(l);
addWindowListener(new WindowH());

}

class WindowH extends WindowAdapter

{
public void windowClosing(WindowEvent we)

{
System.exit(0);
}
};


class MyEventHandler implements ActionListener {

public void actionPerformed(ActionEvent e){

Getlotto();

}

}//추가 부분

public void display()

{

setLayout(new FlowLayout());
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
add(p2);
add(p1);
setSize(400,300);

//pack();

setVisible(true);

}

public void Getlotto() {

// TODO Auto-generated method stub

int num[] = new int[6];

for (int i = 0; i < 6; i++) {

Random ran = new Random();

num[i] = ran.nextInt(45) + 1;

for (int j = 0; j < i; j++) {

if (num[i] == num[j]) {

num[i] = ran.nextInt(46) + 1;

i = i - 1;

break;

}

}

}

for (int i = 0; i < 6; i++) {

switch (i) {

case 0:

b1.setLabel(String.valueOf(num[i]));

break;

case 1:

b2.setLabel(String.valueOf(num[i]));

break;

case 2:

b3.setLabel(String.valueOf(num[i]));

break;

case 3:

b4.setLabel(String.valueOf(num[i]));

break;

case 4:

b5.setLabel(String.valueOf(num[i]));

break;

case 5:

b6.setLabel(String.valueOf(num[i]));

}

}// 추가 부분


}
}



2008년 6월 22일 일요일

Exeption in thread "main" java.lang.NullPointerException


import java.awt.*;

import java.awt.event.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;

import javax.swing.*;

class UpdateInfo extends JFrame
{
private JPanel pmain, pupper, pcenter, pbottom;
private JLabel lname, lemail, lplace;
private JTextField tfname, tfemail, tfplace;
private JButton bInput, bReset, bClose;

public UpdateInfo()
{
setTitle("Update Infomation");
Container c = getContentPane();
pmain = new JPanel();
pupper = new JPanel();// 추가하세요.
lname = new JLabel("성 명");
tfname = new JTextField(5);
lemail = new JLabel("이메일");
tfemail = new JTextField(15);
pcenter = new JPanel();
lplace = new JLabel("주 소");
tfplace = new JTextField(25);
pbottom = new JPanel();
bInput = new JButton("입 력");
bReset = new JButton("새로고침");
bClose = new JButton("닫 기");
bClose.setToolTipText("종료하기");
bClose.setCursor(new Cursor(Cursor.HAND_CURSOR));
bClose.addMouseListener(new TryClose());

pupper.add(lname);
pupper.add(tfname);
pupper.add(lemail);
pupper.add(tfemail);
pcenter.add(lplace);
pcenter.add(tfplace);
pbottom.add(bInput);
pbottom.add(bReset);
pbottom.add(bClose);
pmain.add("North", pupper);
pmain.add("Center", pcenter);
pmain.add("South", pbottom);
add(pmain);

bReset.addActionListener(new ButtonHandler());
bInput.addActionListener(new ButtonHandler());
setResizable(false);
setSize(400,150);
setVisible(true);
setDefaultLookAndFeelDecorated(true);
}

public class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String string = "";
if(e.getSource() == bReset)
{
tfname.setText("");
tfemail.setText("");
tfplace.setText("");
}
else if(e.getSource() == bInput)
{
string = String.format("성명 : "+ tfname.getText() + "E-mail : " + tfemail.getText() + "\n주소 : " + tfplace.getText(),e.getActionCommand());

JOptionPane.showMessageDialog(null, string);
}
}
}

public class TryClose extends MouseAdapter
{
public void mousePressed(MouseEvent ev)
{
dispose();
// new TestLogin(); // 지금은 필요 없음
}
}

public static void main(String[] args)
{
UpdateInfo ui = new UpdateInfo();
}
}

swing jTextPane.select() 메서드 관련


import javax.swing.JFrame;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.Rectangle;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;


public class SelectTest extends JFrame {

private JPanel jContentPane = null;
private JButton jButton = null;
private JScrollPane jScrollPane = null;
private JTextPane jTextPane = null;

public SelectTest() {
super();
initialize();

}

private void initialize() {
this.setSize(new Dimension(387, 282));
this.setContentPane(getJContentPane());
this.setTitle("SelectTest");
}

private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(null);
jContentPane.add(getJButton(), null);
jContentPane.add(getJScrollPane(), null);
}
return jContentPane;
}

private JButton getJButton() {
if (jButton == null) {
jButton = new JButton();
jButton.setBounds(new Rectangle(131, 15, 113, 30));
jButton.setText("select");
jButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
try {
jTextPane.grabFocus();//이부분 추가하세요 ^^!
//문제의 select() 메서드....
jTextPane.select(0,10);



//버튼을 클릭했을때의 텍스트팬의 선택된구역의 좌표
System.out.println(jTextPane.getSelectionStart()+""+jTextPane.getSelectionEnd());



}catch(Exception ee) {}

}
});
}
return jButton;
}

private JScrollPane getJScrollPane() {
if (jScrollPane == null) {
jScrollPane = new JScrollPane();
jScrollPane.setBounds(new Rectangle(43, 74, 300, 155));
jScrollPane.setViewportView(getJTextPane());
}
return jScrollPane;
}

private JTextPane getJTextPane() {
if (jTextPane == null) {
jTextPane = new JTextPane();
}
return jTextPane;
}

public static void main(String[] args) {
SelectTest ss = new SelectTest();
ss.setVisible(true);

}


}

2008년 6월 20일 금요일

Java 이벤트처리, 스레드



지식in에 올릴려고 했는데 이미 결정해서 올릴 때가 없어 여기에 올립니다.
ㅋ 참조 하세요. everick9 님 답변은 Frame에 띄우는 방법이고 저의 방법은 애플릿창에서 실행되는 거니 참조해서 좋은 프로그램 만드세요... ㅎ

대신 주석은 없어요. Canvas 는 상속 받을 필요는 없는데 님의 소스를 수정한거라...


import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Updown extends Applet implements ActionListener
{
private Image 그림;
public int pos=100;
private int flag = 0;
private Button 준비;
private Button 시작;
private Shark 상어;
private boolean startB = false;

public void init(){
add(준비 = new Button("준비"));
add(시작 = new Button("시작"));
그림 = getImage(getDocumentBase(),"flag.gif");
}
public void paint(Graphics g){
if(startB) g.drawImage(그림, 20, pos,this);
}

public void start(){
준비.addActionListener(this);
시작.addActionListener(this);
}

public void actionPerformed(ActionEvent e){
if(e.getSource() == 준비){
상어 = new Shark(this);
준비.setEnabled(false);
this.validate();
startB=true;
repaint();
}
else if(e.getSource() == 시작){
시작.setEnabled(false);
Thread 실행 = new Thread(상어);
실행.start();
this.validate();
}
}

}

class Shark extends Canvas implements Runnable
{
private Updown sh;
private int flag = 0;

public Shark(Updown m){
sh = m;
}
public void run(){
do{
if(flag == 0){
sh.repaint();
sh.pos += 10;
if(sh.pos > 500) flag = 1;
try{
Thread.sleep(50);
}
catch(Exception e){}
}
else if(flag == 1){
sh.repaint();
sh.pos -= 10;
if(sh.pos < 100) flag = 0;
try{
Thread.sleep(50);
}
catch(Exception e){}

}
}while(flag<2);
}
}

2008년 6월 19일 목요일

5. Android 개발도구 Eclipse 의 다운로드

Eclipse는 자바 개발자들에게는 더할 나위 없는 근사한 통합개발도구 입니다.
한마디로 여기서 프로그램 만든다는 거죠.
http://www.eclipse.org/downloads/ 로부터 다운로드하세요.

그리고 적당한 곳에 압축을 풀어주세요.
저의 경우는 그냥 c:\ 에 풀었는데 잘 돌아 갑니다.

2008년 6월 18일 수요일

4. Android Emulator의 실행

Android Emulator를 실행해 보겠습니다.
Android Emulator는 Android가 가동하는 휴대 단말의 에뮬레이터입니다.
일단 커멘드 prompt를 실행해 주세요. 그리고 emulator.exe -data C:\android-sdk_m5-rc15_windows\tools\u1.img 또는 emulator 를 입력합니다.

emulator.exe -data C:\android-sdk_m5-rc15_windows\tools\u1.img 다음에 설명하겠습니다.


다음과 같이 Android Emulator가 실행된 화면이 나오면 브라우저나 Google Maps 등도 실행해보세요.

2008년 6월 17일 화요일

자바에서 시스템 명령어 사용하여 Mysql 덤프 하는 방법

일단 실행해보세요 . 만약 화면에 null이라고 나오면 빨강 부분 path를 정확히 하세요..

예)c:\mysql\bin\mysqldump

cmd를 사용해서 실행하는 명령들은 스트림을 만들어서 입력 출력해야합니다.메모장이나 그림판 기타 프로그램은 실행되지만 dos모드명령들은 cmd의 스트림을 통해 실행해야 돌아갑니다.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class SampleInvoke2
{
public static void main(String arg[])
{
try
{
Runtimer=Runtime.getRuntime();
String[] cmd={"cmd.exe" , "/c" , "mysqldump -u root -p123456 userlist > c:/userlist.sql"};
Process P=r.exec(cmd);
BufferedReader br=new BufferedReader(new InputStreamReader(P.getInputStream()));
String str=br.readLine();
System.out.println(str);
while(str!=null)
{
System.out.println(str);
str=br.readLine();
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
System.exit(0);
}
}
}

2008년 6월 15일 일요일

자바에서 버튼 드래그& 드롭과 관련


너무 허접하게 만들어서 공개하기가 창피해서 공개 안했는데...
찾는 분들 쪽지 때문에 공개합니다.
아 그리고 각 색 부분이 패널입니다..



/****************************************************************/
/* test */
/* */
/****************************************************************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* Summary description for test
*
*/
public class test extends JFrame
{
// Variables declaration
private JPanel contentPane;
//-----
private JButton jButton1;
private JPanel jPanel1;
//-----
private JPanel jPanel2;
//-----
// End of variables declaration

int x = 10;
int y = 10;
int s_x = 10;
int s_y = 10;
int width = 80;
int height = 20;
public test()
{
super();
initializeComponent();
//
// TODO: Add any constructor code after initializeComponent call
//

this.setVisible(true);
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always regenerated
* by the Windows Form Designer. Otherwise, retrieving design might not work properly.
* Tip: If you must revise this method, please backup this GUI file for JFrameBuilder
* to retrieve your design properly in future, before revising this method.
*/
private void initializeComponent()
{
contentPane = (JPanel)this.getContentPane();
//-----
jButton1 = new JButton();
jPanel1 = new JPanel();
//-----
jPanel2 = new JPanel();
//-----

//
// contentPane
//
contentPane.setLayout(null);
addComponent(contentPane, jPanel1, 4,7,353,100);
addComponent(contentPane, jPanel2, 6,116,352,100);
//
// jButton1
//
jButton1.setText("jButton1");
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
jButton1_actionPerformed(e);
}



});
//
// jPanel1
//

jButton1.addMouseMotionListener(new MouseMotionAdapter() {


public void mouseDown( MouseEvent ev, int x,int y){
System.out.println(x);


}


public void mouseDragged(MouseEvent ev) {
int tem_x = ev.getX()-(width/2); // 이벤트 발생 좌표값중 x값 추출
int tem_y = ev.getY()-(height/2); // 이벤트 발생 좌표값중 y값 추출..


System.out.println(ev.getX());


// 마우스 포인터가 버튼 영역 안 여부 판단 후 버튼 위치 재지정...

x= x+tem_x;
y= y+tem_y;
jButton1.setBounds(x, y, width, height);
if(y>90){
addComponent(jPanel2, jButton1, x,200,73,25);
}


}
});



jPanel1.setLayout(null);
jPanel1.setBackground(new Color(204, 204, 255));
addComponent(jPanel1, jButton1, 5,7,73,25);
//
// jPanel2
//
jPanel2.setLayout(null);
jPanel2.setBackground(new Color(153, 153, 255));
//
// test
//
this.setTitle("test - extends JFrame");
this.setLocation(new Point(0, 0));
this.setSize(new Dimension(371, 259));


}

/** Add Component Without a Layout Manager (Absolute Positioning) */
private void addComponent(Container container,Component c,int x,int y,int width,int height)
{
c.setBounds(x,y,width,height);
container.add(c);
}

//
// TODO: Add any appropriate code in the following Event Handling Methods
//
private void jButton1_actionPerformed(ActionEvent e)
{
System.out.println("\njButton1_actionPerformed(ActionEvent e) called.");
// TODO: Add any handling code here

}

//
// TODO: Add any method code to meet your needs in the following area
//


//============================= Testing ================================//
//= =//
//= The following main method is just for testing this class you built.=//
//= After testing,you may simply delete it. =//
//======================================================================//
public static void main(String[] args)
{
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception ex)
{
System.out.println("Failed loading L&F: ");
System.out.println(ex);
}
new test();
}
//= End of Testing =


}

2008년 6월 13일 금요일

Android & notepad

Android & notepad

Notepad 로 블로그 홍보 UCC 한번 만들어 봤습니다.

2008년 6월 11일 수요일

Android 3D

오늘 캠코더 파일 정리하다 옛날에 녹화한 재미있는 파일을 발견했어요.
ㅋㅋ 지금은 너무 오래되어서 어디서 다운 받았는지 기억이 나지 않네요.

While I was rearranging the Camcorder files, I came to find a interesting file recorded long before.
Long time has passed by so I don't remember where I got it down from

2008년 6월 9일 월요일

Google I/O


안전벨트 인가? ㅋㅋㅋ
이상태에서 사고나면 즉사입니다.
벨트를 꼭 잠그세요.ㅎㅎㅎㅎㅎ
If an accident happens, it is instant death. Please shut a belt by all means.

2008년 6월 7일 토요일

Android GTalk Client

GTalkDataMessageSender

Video

public class GTalkDataMessageSender extends Activity {
private static final String LOG_TAG = "GTalkServiceSample";
IGTalkSession mGTalkSession = null;
EditText mUsernameField;
Button mSendButton;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.gtalk_data_message_sender);
mUsernameField = (EditText)findViewById(R.id.username);
mUsernameField.setOnClickListener(mOnClickListener);
mUsernameField.requestFocus();
mSendButton = (Button)findViewById(R.id.send);
mSendButton.setOnClickListener(mOnClickListener);
mSendButton.setEnabled(false);
bindGTalkService();
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(mConnection);
}
private void bindGTalkService() {
bindService((new Intent()).setComponent(
com.google.android.gtalkservice.GTalkServiceConstants.GTALK_SERVICE_COMPONENT),
mConnection, 0);
}
private boolean isValidUsername(String username) {
if (TextUtils.isEmpty(username)) {
return false;
}
if (username.indexOf('@') == -1) {
return false;
}
return true;
}
private Intent getIntentToSend() {

// intent만들고 메시지를 대입.
//I make intent and input a message

Intent intent = new Intent(GTalkDataMessageReceiver.ACTION);
intent.putExtra("poke", "Hi, I am Sam.");
intent.putExtra("question", "would you like to eat green eggs and ham?");
return intent;
}
private void showMessage(CharSequence msg) {
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the GTalkService has been
// established, giving us the service object we can use to
// interact with the service. We are communicating with our
// service through an IDL interface, so get a client-side
// representation of that from the raw service object.
IGTalkService GTalkService = IGTalkService.Stub.asInterface(service);
try {
mGTalkSession = GTalkService.getDefaultSession();
if (mGTalkSession == null) {
// this should not happen.
showMessage(getText(R.string.gtalk_session_not_found));
return;
}
} catch (DeadObjectException ex) {
Log.e(LOG_TAG, "caught " + ex);
showMessage(getText(R.string.found_stale_gtalk_service));
}
mSendButton.setEnabled(true);
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mGTalkSession = null;
mSendButton.setEnabled(false);
}
};
private View.OnClickListener mOnClickListener = new View.OnClickListener() {
public void onClick(View v) {
if (v == mUsernameField) {
mSendButton.requestFocus();
} else {
// use GTalkService to send data message to someone
String username = mUsernameField.getText().toString();
if (!isValidUsername(username)) {
showMessage(getText(R.string.invalid_username));
return;
}
if (mGTalkSession == null) {
showMessage(getText(R.string.gtalk_service_not_connected));
return;
}
try {

//모든 게 중요하지만 특히 이 한 줄의 코드가
//이 프로그램의 핵심이다.
//따라서 이 부분을 이해한다면
//이 프로그램을 이해한다고 볼 수 있다.
//Everything is important, but a code of this one line is the core of this program particularly.

mGTalkSession.sendDataMessage(username, getIntentToSend());

} catch (DeadObjectException ex) {
Log.e(LOG_TAG, "caught " + ex);
showMessage(getText(R.string.found_stale_gtalk_service));
mGTalkSession = null;
bindGTalkService();
}
}
}
};
}

2008년 6월 6일 금요일

Anatomy of an Android Application



어플리케이션 구성요소


Activity , Intent, Service, Content Provider

Anatomy of an Android Application

Android will be 100% open source, says Google

Google IO: Android will be 100% open source, says Google
Google은 땅파먹고 사나?

2008년 6월 5일 목요일

3. PATH의 설정

어플리케이션의 작성에 필요한 각 프로그램은 Android SDK를 인스톨 한 디렉토리안의 tools디렉토리안에 포함되어 있습니다.
따라서 C:\android-sdk_m5-rc15_windows/tools의 패스를 시스템에 추가해야합니다.
Windows에서는, 내 컴퓨터를 오른쪽 클릭하고, Properties를 선택합니다. Advanced 탭아래에서, Environment Variables 버튼을 누릅니다. 그리고, 위저드로 System Variables아래의 Path로 더블 클릭한 다음 Path에C:\android-sdk_m5-rc15_windows 패스를 추가합니다.

C:\android-sdk_m5-rc15_windows는 압축푼 디렉토리 이름입니다.


참고) Path를 추가 안해도 잘 돌아갑니다. 저는 Path설정 안하고 지금 사용중입니다.



What is Android?

Android 는, mobile devices를 위한 operating system, 미들웨어, 및 주요한 어플리케이션을 포함한 소프트웨어·스택입니다. Android SDK는, Android 플랫폼에서 Java 프로그램 언어를 사용하는 것으로 어플리케이션을 개발하기 시작하기 위해서 필요한 툴과 API를 제공합니다.

Android is a software stack for mobile devices that includes an operating system, middleware and key applications. This early look at the Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.

이런 나는 전화기를 판매하는 줄 알았는데 google 전화기나 팔지 뭘 os까지 만들고.ㅋ
구글폰 좋~찮아.

2008년 6월 3일 화요일

java.lang.NullPointerException

gtalk 프로그램 작성시 다음과 같은 Exception error 발생하면

GTalk Settings 화면에서 ADD Account 하시면 에러는 사라집니다.


2008년 6월 2일 월요일

Android Developer Challenge

구글 안드로이드 개발대회에 한국인 본선진출
아~~싸~ 축하드립니다. 파이팅 ~~~
나도 열심히 연구해야지 ...

2. 인스톨, SDK install

다운로드한 파일은 압축파일이기 때문에, 압축을 임의의 장소에 풀어 주세요. 저는 C: \ 에 압축을 풀었습니다. 아무곳에 압축을 풀어도 잘 돌아갑니다. ( 붉은선을 참조하세요)
그리고 license.txt 에는 SDK 이용에 관한 라이센스가 기재되어 있기 때문에 잘 읽어 보세요.
설마 안 읽어봤다고 감옥에 가겠어요.


2008년 6월 1일 일요일

구글폰의 실체

구글폰의 실체는 휴대폰 단말기가 아니라 운영체제와 서비스로 드러났다.
이게 무슨말인가?
너무 황당무개하기가 극에 다달았다 .
-


Sidewinder


World


FishMusic


LaughingBaby