자바 awt , event 를 이용하여
JAVA 로 그림그리기 예제를 해보겠습니다.


오늘은 그림그리기를 해서
자바에 조금더 알아 보겠습니다.


액션이 있는 예제이기 때문에 조금더

재미있게 따라 해보실 수 있을거라 생각됩니다.


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

class GraphicsEx1 extends Frame {
 public static void main(String[] args) {
   new GraphicsEx1("GraphicsEx1");
 }
 
 public void paint(Graphics g){
   g.setFont(new  Font("Serif" , Font.PLAIN , 15));
   g.drawString("Graphics 를 이용해서 그림을 그립니다." , 10, 50);
   g.drawOval(50,100, 50 , 50);
   g.setColor(Color.blue);
   g.fillOval(100, 100,50, 50);
   g.setColor(Color.red);
   g.drawLine(100,100, 150,150);
   g.fillRoundRect(200, 100, 120 , 80 , 30 , 30);
   g.setColor(Color.orange);
   g.fillPolygon(new int[]{ 50, 100, 150, 200} ,
       new int[] { 250, 200 , 200, 250}, 4);
   g.setColor(Color.cyan);
   g.fillArc(250 , 200 ,100 ,100 ,0 ,120);
 }
 public GraphicsEx1(String title){
  super(title);
  addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we){
      System.exit(0);
    }
  });
  setBounds(100,100, 400,300);
  setVisible(true);

}
}


안드로이드 개발하다보면 랜덤값을 사용할 일이 많은데요
랜덤 숫자 하나 가저 오는건 쉽지만 중복된 숫자없이
값을 출력 한다는건 어려울 수가 있습니다.
아래 소스를 이용 하시면 빠른 속도로 값을 가저올 수 있습니다.

public int[] RnadomCount(int count){
        int[] nResult = new int[count];
        int[] list = { 0 ,1 ,2,3,4,5,6,7,8,9 };
        
        int idx;
        int nRand = count;

        for (int i = 0; i < count; i++){
            idx =  (int)(Math.random()* nRand);
            nResult[i] = list[idx];
            list[idx] = list[--nRand];
        }
        
        return nResult;
    }


자바 연습 네번째!!
자바 awt , event , io 를 이용하여
메뉴만들기 도전 해보겠습니다.


자바에서 아주 기본적인 예제로 보시면

되겠습니다.


메뉴는 어디에서든 필요한 필수 입니다.

천천히 따라해보세요 ^^


import java.awt.*;
import java.awt.event.*;
import java.io.*;


class TextEditor extends Frame {
 String fileName;
 TextArea content;
 MenuBar mb;
 Menu mfile;
 MenuItem minew , miopen , misaveas , miexit ;

 TextEditor(String title){
   super(title);
   content = new TextArea();
   add(content);

   mb = new MenuBar();
   mfile = new Menu("파일");
   minew = new MenuItem("New");
   miopen = new MenuItem("open");
   misaveas = new MenuItem("save As");
   miexit = new MenuItem("Exit");
   
   mfile.add(mfile);
   mfile.add(minew);
   mfile.add(miopen);
   mfile.add(misaveas);
   mfile.add(miexit);

   mb.add(mfile);  
   setMenuBar(mb);  // 프레임에 menubar 를 포함시긴다
   
   // 메뉴에 이벤트 핸들러를 등록한다
  MyHandler handler = new MyHandler();
  minew.addActionListener(handler);
  miopen.addActionListener(handler);
  misaveas.addActionListener(handler);
  miexit.addActionListener(handler);

  setSize(300, 200);
  setVisible(true);

 }

 // 선택된 파일의 내용을 읽어서  TextArea에 보여주는 메서드
 void fileOpen(String fileName){
   FileReader fr;
   BufferedReader br;
   StringWriter sw;

   try{
     fr = new FileReader(fileName);
     br = new BufferedReader(fr);
     sw = new StringWriter();

     int ch = 0;
     while((ch=br.read()) != -1) {
      sw.write(ch);
     }
     br.close();
     content.setText(sw.toString());
   }catch (IOException e){
    e.printStackTrace();
   }
 }

 void saveAs(String fileName){
   FileWriter fw;
   BufferedWriter bw;
   
   try{
    fw = new FileWriter(fileName);
    bw = new BufferedWriter(fw);
    bw.write(content.getText());
    bw.close();
   } catch (IOException ie){
    ie.printStackTrace();
   }
 }
 public static void main(String args[]){
   TextEditor main = new TextEditor("Text Editor");
 }

 //메뉴를 클릭했을 때 메뉴별 처리코드

 class MyHandler implements ActionListener {
   public void actionPerformed(ActionEvent e){
    String command = e.getActionCommand();

   if(command.equals("New")){
    content.setText("ff");
   }else if (command.equals("open")){
    FileDialog fileOpen =
     new FileDialog(TextEditor.this , "파일열기");
    fileOpen.setVisible(true);
    fileName = fileOpen.getDirectory() + fileOpen.getFile();
    System.out.println(fileName);
    fileOpen(fileName);
   } else if (command.equals("save As")){
     FileDialog fileSave =
      new FileDialog(TextEditor.this , "파일저장" , FileDialog.SAVE);
     fileSave.setVisible(true);
     fileName = fileSave.getDirectory() + fileSave.getFile();
     System.out.println(fileName);
     //현재 TextArea 의 내용을 선택된 저장한다.
     saveAs(fileName);
   } else if (command.equals("Exit")) {
    System.exit(0);
   }
   }
 }}


[ 자바 연습 ]


자바 연습 세번째 awt event 를
이용한 채팅창을 만들어 봅시다.


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

class  TextComponentEventTes extends Frame  {
 
  TextField tf;
  TextArea ta;
 
 TextComponentEventTes(String title){
  super(title);
 
   tf = new TextField();
   ta = new TextArea();
   add(ta, "Center");
   add(tf, "South");

   tf.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
     ta.append(tf.getText() + "\n");
     tf.setText("");
     tf.requestFocus();
    }
  });

  ta.setEditable(false);
  setSize(300, 200);
  setVisible(true);
  tf.requestFocus();
 
  addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent evt){
     setVisible(false);
     dispose();
     System.exit(0);
    }
  });


 }
 public static void main(String args[]){
   TextComponentEventTes mainWin =
     new TextComponentEventTes("TextComponentEventTest");

 

 }
}


[자바 예제]


자바 연습 두번째 빙고판을 만들어 봅시다.

역시나 게임을 만들면서 결과를 보며
배우는게 가장 좋은 방법이고

자바를 접하는데 가장 좋습니다. ^^


천천히 따라 결과까지 보시기 바래요~


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


class MyGame1 extends Frame {
  Button apple , q,w,e,r,t,y,u,i,o,p,a,s,d,b,g,h,j,k,l,z,x,c,v,n;
 
 MyGame1(String title){
  super(title);
  apple = new Button("사과");
  q = new Button("나무");w = new Button("축구");e = new Button("농구");r = new Button("야구");
  i = new Button("배");u = new Button("나니");y = new Button("발렌시아");t = new Button("루니");
  o = new Button("참외");p = new Button("긱스");a = new Button("드록바");s = new Button("박지성");
 
  j = new Button("에브라");k = new Button("메시");l = new Button("치차리토");z = new Button("베르마토프");
  h = new Button("게임");g = new Button("호날두");
  b = new Button("퍼디난드");
  d = new Button("토레스");x = new Button("제코");c = new Button("이청용");
  n = new Button("램파드");v = new Button("제라드");
 
  apple.addActionListener(new EventHandler());
  q.addActionListener(new EventHandler());
  w.addActionListener(new EventHandler());
  e.addActionListener(new EventHandler());
  r.addActionListener(new EventHandler());
  t.addActionListener(new EventHandler());
  y.addActionListener(new EventHandler());
  u.addActionListener(new EventHandler());
  i.addActionListener(new EventHandler());
  o.addActionListener(new EventHandler());
  p.addActionListener(new EventHandler());
  a.addActionListener(new EventHandler());
  s.addActionListener(new EventHandler());
  d.addActionListener(new EventHandler());
    g.addActionListener(new EventHandler());
    b.addActionListener(new EventHandler());
  h.addActionListener(new EventHandler());
  j.addActionListener(new EventHandler());
  k.addActionListener(new EventHandler());
  l.addActionListener(new EventHandler());
  z.addActionListener(new EventHandler());
  x.addActionListener(new EventHandler());
  c.addActionListener(new EventHandler());
  v.addActionListener(new EventHandler());
  n.addActionListener(new EventHandler());

  setLayout(new GridLayout(5,5));
  setSize(300,300);
  setVisible(true);
   
  add(q);add(w);add(e);add(r);add(t);add(y);add(u);add(i);add(o);add(p);add(a);add(s);add(d);add(b);add(g);add(h);add(j);
  add(k);add(l);add(z);add(apple);add(x);add(c);add(v);add(n);

 }
 
 class EventHandler implements ActionListener{
  public void actionPerformed(ActionEvent e){
     Button cb= (Button)e.getSource();
     String cc = cb.getLabel();
     System.out.println(cc);
     
   cb.setBackground(Color.red);
   
  }
 }


 public static void main(String[] args) {
  new MyGame1("MyGame");

   }
}



[자바 예제]
이번 자바 연습 소스는 랜덤값을
맞추는 게임을 올려봅니다.


자바을 처음 접하시는 분들은
아래와 같은 간단한 게임을 만들면서

재미를 붙여 보시는 것도 좋습니다. ^^

결과값 까지 꼭 보시길 바래요 ~

class  Excercise41 {
 public static void main(String[] args)  {
  int answer = (int)(Math.random()*100)+1;
  int input = 0;
  int count =0;
  java.util.Scanner s = new java.util.Scanner(System.in);
  do  {
   count++;
   System.out.println("1과 100상의 값을 입력하세요 :");
   input = s.nextInt();
   if(answer > input) {
   System.out.println("더 큰 수를 입력하세요.");
   } else if(answer < input) {
   System.out.println("더 작은 수를 입력하세요.");
   } else {
   System.out.println("맞췄습니다.");
   System.out.println("시도횟수는 "+count+"번입니다.");
   break; // do-while문을 벗어난다
   }
  }  while (true);
 }
}

==================카운트 만들기


1. while 구문으로 만들은것

 

class  FlowEx19
{
 public static void main(String[] args)
 {
  int i = 10;
  while(i >= 0){
   System.out.println(i);
   for (int j =0; j <1000000000 ;j++ )   {
    ;
   }
   i--;
  }
  System.out.println("완료");
 }
}


2. for문으로 만들기


class Cho {
 public static void main(String[] args)  {
  for (int i = 10 ; i >=0 ; i-- ) {
   System.out.println(i);
   for (int j = 0; j < 1000000000 ; j++ ) {
    ;
   }
  } 
  }
}


======================로또  for문으로 출력해보기

문장1

class For {
 public static void main(String[] args)  {
  int temp = 0;
  int a[] = new int[45];
  int k = 0;
  for (int i = 0; i < 45 ; i++ ) {
   a[i] = i + 1;
  }
  
  for (int y = 0; y < 100 ; y++ ) {
   k = (int)(Math.random()*45);
   temp = a[0];
   a[0] = a[k];
   a[k] = temp;
   
  }
  for (int i =0; i <= 6 ; i++ ){
    System.out.print(a[i]+" ");
  }
 }
}


문장2

class Tee {
 public static void main(String[] args)  {
  int a = 0;
  for (int i = 0; i < 6 ; i++){
   a = (int)(Math.random()*45)+1;
    System.out.print(a + "\t" );
  }
 }
}


================시작과 끝 시간 currentTimeMillis 이용하여출력하여라

 

class Tee {
 public static void main(String[] args)  {
  long cc = System.currentTimeMillis();
  int a = 0;
  for (int i = 0; i < 6 ; i++){
   a = (int)(Math.random()*45)+1;
    System.out.print(a + "\t" );
  }
  long ccq = System.currentTimeMillis();
  System.out.println("시작" + cc);
  System.out.println("끝" + ccq);
  System.out.println("걸린시간" + " " +(ccq - cc));
 }
}


===========if 문성적표만들기

 

class If {
 public static void main(String [] args){
  int a = 100;
  String b ="";
  if (a >= 100){
     b = "A";
   if (a >= 95){
    b += "+";
   }
  } else {
   b ="B";
  }
  System.out.println(b);
}
}

+ Recent posts