Java 7에 포함되기로 했다가 취소된 함수형 프로그래밍(closure) 미리 맛보기

    관련 자료
        [1] http://javac.info/
        [2] http://stronglytypedblog.blogspot.com/2010/06/lambdas-in-java-preview-part-1-basics.html )
        [3] http://www.infoq.com/articles/lambdas-java-analysis
        [4] http://wiki.java.net/bin/view/JDK/ClosuresSyntaxInJava7
        [5] http://www.ibm.com/developerworks/java/library/j-jtp04247.html
        [6] http://www.java.net/pub/pq/242
        [7] http://www.baptiste-wicht.com/2010/05/oracle-pushes-a-first-version-of-closures/
        [8] http://www.davidflanagan.com/2010/05/closures-in-jav.html


1. FuctionalJava 홈페이지
   http://functionaljava.org/examples/

2. 다운로드
    http://functionaljava.org/download/


3. 예제

JDK 1.5 이상 용 예제 파일 (Java 7 용은 별도로 있음)

// 소스 파일: Fibs.java

package concurrent;

import static fj.Bottom.error;
import fj.Effect;
import fj.F;
import fj.P;
import fj.P2;
import fj.Unit;
import fj.data.List;
import fj.control.parallel.Actor;
import fj.control.parallel.Promise;
import fj.control.parallel.Strategy;
import static fj.data.List.range;
import static fj.function.Integers.add;
import static fj.control.parallel.Promise.join;
import static fj.control.parallel.Promise.promise;
import static fj.control.parallel.Actor.actor;

import java.text.MessageFormat;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Parallel Fibonacci numbers.
 * Based on a Haskell example by Don Stewart.
 * Author: Runar
 */
public class Fibs
  {private static final int CUTOFF = 35;

   public static void main(final String[] args)
     {if (args.length < 1)
         throw error("This program takes an argument: number_of_threads");

      final int threads = Integer.parseInt(args[0]);
      final ExecutorService pool = Executors.newFixedThreadPool(threads);
      final Strategy<Unit> su = Strategy.executorStrategy(pool);
      final Strategy<Promise<Integer>> spi = Strategy.executorStrategy(pool);

      // This actor performs output and detects the termination condition.
      final Actor<List<Integer>> out = actor(su, new Effect<List<Integer>>()
        {public void e(final List<Integer> fs)
          {for (final P2<Integer, Integer> p : fs.zipIndex())
               {System.out.println(MessageFormat.format("n={0} => {1}", p._2(), p._1()));}
           pool.shutdown();}});

      // A parallel recursive Fibonacci function
      final F<Integer, Promise<Integer>> fib = new F<Integer, Promise<Integer>>()
        {public Promise<Integer> f(final Integer n)
          {return n < CUTOFF ? promise(su, P.p(seqFib(n))) : f(n - 1).bind(f(n - 2), add);}};

      System.out.println("Calculating Fibonacci sequence in parallel...");
      join(su, spi.parMap(fib, range(0, 46)).map(Promise.<Integer>sequence(su))).to(out);}

  // The sequential version of the recursive Fibonacci function
  public static int seqFib(final int n)
    {return n < 2 ? n : seqFib(n - 1) + seqFib(n - 2);}}



4. 컴파일하기

    javac -d . -cp functionaljava.jar Fibs.java


5. 실행하기 (옵션 3은 쓰레드 개수)

    java -classpath .;functionaljava.jar concurrent.Fibs 3

실행 결과:
ibs 3
Calculating Fibonacci sequence in parallel...
n=0 => 0
n=1 => 1
n=2 => 1
n=3 => 2
n=4 => 3
n=5 => 5
n=6 => 8
n=7 => 13
n=8 => 21
n=9 => 34
n=10 => 55
n=11 => 89
n=12 => 144
n=13 => 233
n=14 => 377
n=15 => 610
n=16 => 987
n=17 => 1,597
n=18 => 2,584
n=19 => 4,181
n=20 => 6,765
n=21 => 10,946
n=22 => 17,711
n=23 => 28,657
n=24 => 46,368
n=25 => 75,025
n=26 => 121,393
n=27 => 196,418
n=28 => 317,811
n=29 => 514,229
n=30 => 832,040
n=31 => 1,346,269
n=32 => 2,178,309
n=33 => 3,524,578
n=34 => 5,702,887
n=35 => 9,227,465
n=36 => 14,930,352
n=37 => 24,157,817
n=38 => 39,088,169
n=39 => 63,245,986
n=40 => 102,334,155
n=41 => 165,580,141
n=42 => 267,914,296
n=43 => 433,494,437
n=44 => 701,408,733
n=45 => 1,134,903,170



Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
Posted by Scripter
,


[파일명:  TestStringFindInList.java]------------------------------------------------
import java.util.*;

public class TestStringFindInList {

    public static void main(String[] args) {
        String[] data = { "하나", "둘", "셋", "넷", "다섯", "여섯" };
        ArrayList<String> words = new ArrayList<String>();
        for (int i = 0; i < data.length; i++) {
            words.add(data[i]);
        }
        int where;

        System.out.print("vector: ");
        printArray(words);
        where = find(words, "셋");
        if (where > 0) {
            System.out.print("발견!  ");
            System.out.println("Next word of 셋 in list: " + words.get(where+1));
        }

        System.out.println("Sorting...");
        Collections.sort(words);

        System.out.print("vector: ");
        printArray(words);
        where = find(words, "셋");
        if (where > 0) {
            System.out.print("발견!  ");
            System.out.println("Next word of 셋 in list: " + words.get(where+1));
        }
    }

    static int find(ArrayList<String> arr, String s) {
     for (int i = 0; i < arr.size(); i++) {
      if (arr.get(i).indexOf(s) >= 0)
       return i;
     }
     return -1;
    }

    static void printArray(ArrayList<String> arr) {
        System.out.print("[");
        for (int i = 0; i < arr.size() - 1; i++) {
            System.out.print(arr.get(i) + ", ");
        }
        if ( arr.size() > 0)
            System.out.print(arr.get(arr.size() - 1));
        System.out.println("]");
    }
}
------------------------------------------------


컴파일> javac testStringFindInList.java

실행> java TestStringFindInList
list: [하나, 둘, 셋, 넷, 다섯, 여섯]
발견!  Next word of 셋 in list: 넷
Sorting...
list: [넷, 다섯, 둘, 셋, 여섯, 하나]
발견!  Next word of 셋 in list: 여섯


크리에이티브 커먼즈 라이선스
Creative Commons License

Posted by Scripter
,


[파일명:  TestStringFindInVector.java]------------------------------------------------
import java.util.*;

public class TestStringFindInVector {

    public static void main(String[] args) {
        String[] data = { "하나", "둘", "셋", "넷", "다섯", "여섯" };
        Vector<String> words = new Vector<String>();
        for (int i = 0; i < data.length; i++) {
            words.add(data[i]);
        }
        int where;

        System.out.print("vector: ");
        printArray(words);
        where = find(words, "셋");
        if (where > 0) {
            System.out.print("발견!  ");
            System.out.println("Next word of 셋 in vector: " + words.elementAt(where+1));
        }

        System.out.println("Sorting...");
        Collections.sort(words);

        System.out.print("vector: ");
        printArray(words);
        where = find(words, "셋");
        if (where > 0) {
            System.out.print("발견!  ");
            System.out.println("Next word of 셋 in vector: " + words.elementAt(where+1));
        }
    }

    static int find(Vector<String> arr, String s) {
     for (int i = 0; i < arr.size(); i++) {
      if (arr.elementAt(i).indexOf(s) >= 0)
       return i;
     }
     return -1;
    }

    static void printArray(Vector<String> arr) {
        System.out.print("[");
        for (int i = 0; i < arr.size() - 1; i++) {
            System.out.print(arr.elementAt(i) + ", ");
        }
        if ( arr.size() > 0)
            System.out.print(arr.elementAt(arr.size() - 1));
        System.out.println("]");
    }
}
------------------------------------------------


컴파일> javac TestStringFindInVector.java

실행> java TestStringFindInVector
vector: [하나, 둘, 셋, 넷, 다섯, 여섯]
발견!  Next word of 셋 in vector: 넷
Sorting...
vector: [넷, 다섯, 둘, 셋, 여섯, 하나]
발견!  Next word of 셋 in vector: 여섯


크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by Scripter
,


[파일명:  TestStringFindApp.java]------------------------------------------------
import java.util.*;

public class TestStringFindApp {

    public static void main(String[] args) {
        String[] words = { "하나", "둘", "셋", "넷", "다섯", "여섯" };
        int where;

        System.out.print("array: ");
        printArray(words);
        where = find(words, "셋");
        if (where > 0) {
            System.out.print("발견!  ");
            System.out.println("Next word of 셋 in array: " + words[where+1]);
        }

        System.out.println("Sorting...");
        Arrays.sort(words);

        System.out.print("array: ");
        printArray(words);
        where = find(words, "셋");
        if (where > 0) {
            System.out.print("발견!  ");
            System.out.println("Next word of 셋 in array: " + words[where+1]);
        }
    }

    static int find(String[] arr, String s) {
     for (int i = 0; i < arr.length; i++) {
      if (arr[i].indexOf(s) >= 0)
       return i;
     }
     return -1;
    }

    static void printArray(String[] arr) {
        System.out.print("[");
        for (int i = 0; i < arr.length - 1; i++) {
            System.out.print(arr[i] + ", ");
        }
        if ( arr.length > 0)
            System.out.print(arr[arr.length - 1]);
        System.out.println("]");
    }
}
------------------------------------------------


컴파일> javac testStringFindApp.java

실행> java TestStringFindApp
array: [하나, 둘, 셋, 넷, 다섯, 여섯]
발견!  Next word of 셋 in array: 넷
Sorting...
array: [넷, 다섯, 둘, 셋, 여섯, 하나]
발견!  Next word of 셋 in array: 여섯



크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,


[파일명:  TestSortApp.java]------------------------------------------------
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

class TestSortApp {
    public static void main(String[] args) {
        List<String> list = Arrays.asList(args);
        Collections.sort(list);
        System.out.println(list);
    }
}
------------------------------------------------


컴파일> javac TestSortApp.java

실행> java TestSortApp 하나 둘 셋 넷
[넷, 둘, 셋, 하나]


 

크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,


정의 (소수와 합성수)
    1보다 큰 양의 정수 n에 대하여
    (i) n = a * b 를 만족하고 1보다 큰 두 양의 정수 a와 b가 존재하면,
        n을 합성수(合成數, composite number)라고 한다. 참고로 이 경우,
        a, b 중에 적어도 하나는 sqrt(n) 보다 작거나 같다.
        합성수의 예로는 4, 6, 9, 24, 143 등이 있다.
    (ii) n = a * b 를 만족하고 1보다 큰 두 양의 정수 a와 b가 존재하지 않으면,
         즉 n을 두 양의 정수의 곱으로 표현하는 방법이 1*n과 n*1 두 가지 뿐이면,
         n을 소수(素數, prime number)라고 한다.  소수의 예로는 2, 3, 5, 7, 11 등이 있다.
         n이 소수인지 아닌지 확인하려면, 
         n을 2 보다 크거나 같고 sqrt(n) 보다 작거나 같은 모든 정수로 나누어 본다.
         이 경우 언제나 나누어 떨어지지  않으면 n은 소수이고,
         그렇지 않으면 n은 합성수이다.
    

우선 다음은 명령행 인자로 전달 받은 양의 정수 n을 2 이상이고 sqrt(n) 이하인 홀수들로 각각
나누어 보아 n이 합성수인지 아닌지 확인하는 Java 애플리케이션 소스 코드이다.
확인하는데 걸린 경과 시간도 알려준다.


/*
 * Filename: DivideEachApp.java
 *
 *  Purpose: Determine whether the given integer is a prime or not.
 *
 *  Compile: javac -d . DivideEachApp.java
 *  Execute: java DivideEachApp [integer]
 *
 *     Date: 2009/03/24
 *   Author: PH Kim   [ pkim ((AT)) scripts.pe.kr ]
 */

/*
  Execution Examples (with Java 1.6.0_12):

      Prompt> java DivideEachApp 1234567812343
      1234567812343 = 1 * 1234567812343
      1234567812343 is a prime
      Elapsed time: 0.25 sec

      Prompt> java DivideEachApp 9999994200000841
      9999994200000841 = 99999971 * 99999971
      9999994200000841 is a not prime
      Elapsed time: 21.047 sec

      Prompt> java DivideEachApp 18446744073709551617
      18446744073709551617 = 274177 * 67280421310721
      18446744073709551617 is a not prime
      Elapsed time: 0.078 sec

      Prompt> java DivideEachApp 10023859281455311421
      10023859281455311421 = 1308520867 * 7660450463
      10023859281455311421 is a not prime
      Elapsed time: 304.906 sec
*/

import java.math.*;
import java.util.*;

public class DivideEachApp {
    public static void main(String[] args) {
        final BigInteger ONE = new BigInteger("1");
        final BigInteger TWO = new BigInteger("2");
        BigInteger n, k, d, z;
        n = new BigInteger("10006099720301");
        if (args.length > 0) {
            n = new BigInteger(args[0]);
        }

        z = n.divide(TWO);    // z = n / 2
        if (n.equals(z.multiply(TWO))) {
            System.out.println(n + "n = 2 * " + z);
        }

        double time1 = new GregorianCalendar().getTime().getTime();

        d = new BigInteger("1");
        k = new BigInteger("3");
        while (k.multiply(k).compareTo(n) <= 0) {
            z = n.divide(k);    // z = n / k
            if ( n.equals(k.multiply(z)) ) {
                d = k;
                break;
            }
            k = k.add(TWO);
        }

        double time2 = new GregorianCalendar().getTime().getTime();

        System.out.println(n + " = " + d + " * " + n.divide(d));
        if (d.equals(ONE))
            System.out.println(n + " is a prime");
        else
            System.out.println(n + " is a not prime");

        System.out.println("Elapsed time: " + (time2 - time1)/1000.0 + " sec");
    }
}




이제 다음은 정수의 인수분해 능력이 뛰어난  Pollard의 rho 방법(일명 거북이와 토끼 알고리즘, tortoise-hair algorithm)을 구현한  Java 애플리케이션 소스 코드이다. 이 알고리즘은 소수에 대해서는 시간이 많이 걸리지만, 합성수에 대해서는 시간이 매우 적게 걸린다는 것이 특징이다.


/*
 * Filename: PollardRhoApp.java
 *
 *  Purpose: By using the pollard rho method,
 *           determine whether the given integer is a prime or not.
 *
 *      See: http://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm
 *           http://en.wikipedia.org/wiki/Floyd%27s_cycle-finding_algorithm#Tortoise_and_hare#
 *
 *  Execute: javac -d . PollardRhoApp.java
 *  Execute: java PollardRhoApp [integer]
 *
 *     Date: 2009/03/24
 *   Author: PH Kim   [ pkim ((AT)) scripts.pe.kr ]
 */

/*
  Execution Examples (with java 1.6.0_12):

      Prompt> java PollardRhoApp 1234567812343
      Try first the Pollard rho algorithm with c = 2
      d = 1234567812343, count = 466951
      Try second the Pollard rho algorithm with c = 3
      d = 1, count = 1111112
      Try third the Pollard rho algorithm with c = 1
      d = 1234567812343, count = 799441
      1234567812343 = 1234567812343 * 1
      Elapsed time: 17.735 sec

      Prompt> java PollardRhoApp 9999994200000841
      Try first the Pollard rho algorithm with c = 2
      d = 99999971, count = 3593
      9999994200000841 = 99999971 * 99999971
      Elapsed time: 0.062 sec

      Prompt> java PollardRhoApp 18446744073709551617
      Try first the Pollard rho algorithm with c = 2
      d = 274177, count = 1028
      18446744073709551617 = 274177 * 67280421310721
      Elapsed time: 0.032 sec

      Prompt> java PollardRhoApp 10023859281455311421
      Try first the Pollard rho algorithm with c = 2
      d = 1308520867, count = 20350
      10023859281455311421 = 1308520867 * 7660450463
      Elapsed time: 0.297 sec
*/

import java.math.*;
import java.util.*;

public class PollardRhoApp {
    public static BigInteger f(BigInteger x, BigInteger c, BigInteger n) {
        return x.multiply(x).add(c).mod(n);    // (x*x + c) % n
    }

    public static BigInteger g(BigInteger x, BigInteger c, BigInteger n) {
        return f(f(x, c, n), c, n);
    }

    public static BigInteger gcd(BigInteger x, BigInteger y) {
        BigInteger a, b, t;
        a = x.abs();
        b = y.abs();
        if (b.equals(BigInteger.ZERO)) {
            return a;
        }
        while (!b.equals(BigInteger.ZERO)) {
            t = a.mod(b);
            a = b;
            b = t;
        }
        return a;
    }

    public static BigInteger pollardRho(BigInteger n) {
        BigInteger c, x, y, d, count, savedX;
        final BigInteger ONE = new BigInteger("1");
        c = new BigInteger("2");
        x = new BigInteger("1");
        y = new BigInteger("1");
        d = new BigInteger("1");
        savedX = x;
        count = BigInteger.ZERO;
        System.out.println("Try first the Pollard rho algorithm with c = " + c);
        while (d.equals(ONE) && count.multiply(count).compareTo(n) <= 0) {
            x = f(x, c, n);
            if (x.equals(savedX)) {
             System.out.println("It is cyclic.  x = " + x);
             break;
            }
            y = g(y, c, n);
            d = gcd(x.subtract(y).abs(), n);
            count = count.add(ONE);
            // if (count % 5000 == 0) {
            //  println("  count = $count")
            // }
        }

        System.out.println("d = " + d + ", count = " + count);
        if (d.compareTo(ONE) > 0 && d.compareTo(n) < 0) {
            return d;
        }

        c = new BigInteger("3");
        x = new BigInteger("1");
        y = new BigInteger("1");
        d = new BigInteger("1");
        savedX = x;
        count = BigInteger.ZERO;
        System.out.println("Try second the Pollard rho algorithm with c = " + c);
        while (d.equals(ONE) && count.multiply(count).compareTo(n) <= 0) {
            x = f(x, c, n);
            if (x.equals(savedX)) {
             System.out.println("It is cyclic.  x = " + x);
             break;
            }
            y = g(y, c, n);
            d = gcd(x.subtract(y).abs(), n);
            count = count.add(ONE);
            // if (count % 5000 == 0) {
            //  println("  count = $count")
            // }
        }

        System.out.println("d = " + d + ", count = " + count);
        if (d.compareTo(ONE) > 0 && d.compareTo(n) < 0) {
            return d;
        }

        c = new BigInteger("1");
        x = new BigInteger("1");
        y = new BigInteger("1");
        d = new BigInteger("1");
        savedX = x;
        count = BigInteger.ZERO;
        System.out.println("Try third the Pollard rho algorithm with c = " + c);
        while (d.equals(ONE) && count.multiply(count).compareTo(n) <= 0) {
            x = f(x, c, n);
            if (x.equals(savedX)) {
             System.out.println("It is cyclic.  x = " + x);
             break;
            }
            y = g(y, c, n);
            d = gcd(x.subtract(y).abs(), n);
            count = count.add(ONE);
            // if (count % 5000 == 0) {
            //  println("  count = $count")
            // }
        }

        System.out.println("d = " + d + ", count = " + count);

        return d;
    }

    public static void main(String[] args) {
        BigInteger n, k, z;
        n = new BigInteger("9991");
        if (args.length > 0) {
            n = new BigInteger(args[0]);
        }

        double time1 = new GregorianCalendar().getTime().getTime();

        k = pollardRho(n);
        z = n.divide(k);
        System.out.println(n + " = " + k + " * " + z);

        double time2 = new GregorianCalendar().getTime().getTime();
        System.out.println("Elapsed time: " + (time2 - time1)/1000.0 + " sec");
    }
}


 

크리에이티브 커먼즈 라이선스
Creative Commons License
Posted by Scripter
,


초등학교 때 배우는 두 정수의 곱셈표를 만들어 주는 자바 애플리케이션 소스이다.

/**
 * Filename: MakeMultTableApp.java
 *
 *     Print a multiplication table.
 *
 *     Compile: javac -d . MakeMultTableApp.java
 *     Execute: java MakeMultTableApp 230 5100
 *
 * Date: 2009/03/06
 * Author: pkim (AT) scripts.pe.kr
 */

import java.io.*;
import java.util.*;

public class MakeMultTableApp {
    public static void printUsing() {
        System.out.println("Using: java MakeMultTableApp [number1] [number2]");
        System.out.println("Print a multiplication table for given two integers.");
    }

    public static void printMultTable(long x, long y) {
        long nx = (x >= 0L) ? x : - x;
        long ny = (y >= 0L) ? y : - y;
        int ntail1 = 0;
        int ntail2 = 0;
        while (nx % 10 == 0) {
            nx = nx / 10;
            ntail1++;
        }
        while (ny % 10 == 0) {
            ny = ny / 10;
            ntail2++;
        }
        long z = nx * ny;
        String strZ = "" + z;
        String strX = "" + nx;
        String strY = "" + ny;
        int n = strY.length();
        String zeros  = "0000000000000000000000000000000000000000";
        String whites = "                                        ";
        String bars   = "----------------------------------------";
        String line1, line2, line3, line4;
        String loffset = "       ";
        line4 = loffset + strZ;
        line1 = loffset + whites.substring(0, strZ.length() - strX.length()) + strX;
        line2 = "   x ) " +  whites.substring(0, strZ.length() - strY.length()) + strY;
        line3 = "     --" +  bars.substring(0, strZ.length());
        System.out.println(line1 + zeros.substring(0, ntail1));
        System.out.println(line2 + zeros.substring(0, ntail2));
        System.out.println(line3);
        if (strY.length() > 1) {
            int y1;
            String strT;
            for (int i = 0; i < strY.length(); i++) {
                y1 = Integer.parseInt(strY.substring(strY.length() - i - 1, strY.length() - i));
                if (y1 != 0) {
                    strT = "" + (nx * y1);
                    System.out.println(loffset + whites.substring(0, strZ.length() - strT.length() - i) + strT);
                }
            }
            System.out.println(line3);
        }
        System.out.println(line4 + zeros.substring(0, ntail1) + zeros.substring(0, ntail2));
    }

    public static void main(String[] args) {
        long x, y;
        if (args.length >= 2) {
            x = Long.parseLong(args[0]);
            y = Long.parseLong(args[1]);
            System.out.println("");
            printMultTable(x, y);
        }
        else {
            printUsing();
        }
    }
}



컴파일> javac -d . MakeMultTableApp.java

실행> java MakeMultTableApp 230 5100
결과>

          230
   x )   5100
     ------
         23
       115
     ------
       1173000

 

크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,


 

/*
 * HelloHangul.java
 *
 *    컴파일: javac -classpath .;iText-rtf-2.1.4.jar;iText-2.1.4.jar HelloHangul.java
 *      실행: java -cp .;iText-rtf-2.1.4.jar;iText-2.1.4.jar HelloHangul *
 */

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.rtf.RtfWriter2;

public class HelloHangul {
    public static void main(String[] args) {
        System.out.println("Hello, 한글! RTF 파일 생성됨");
        try {
            // 도큐먼트 생성
            Document document = new Document();
           
            // RtfWriter2 생성
            RtfWriter2.getInstance(document, new FileOutputStream("HelloHangul.rtf"));
           
            // 도큐먼트 열기
            document.open();
           
            // Step 4: Add content to the document.
            document.add(new Paragraph("Hello, 한글!"));
           
            // 도큐먼트 닫기
            document.close();
        } catch (FileNotFoundException fnfe) {
            // 파일을 생성 할 수 없을 때
            fnfe.printStackTrace();
        } catch (DocumentException de) {
            // DocumentExceptions arise if you add content to the document before opening or
            // after closing the document.
            // 도큐먼트를 열기 전이나 닫은 후의 예외상황 발생
            de.printStackTrace();
        }
    }
}



 

크리에이티브 커먼즈 라이선스
Creative Commons License

 

Posted by Scripter
,


컴파일> javac -d . HelloSwingApp.java
실행> java HelloSwingApp


/*
 * HelloSwingApp.java
 */

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

public class HelloSwingApp extends JFrame implements ActionListener {
 
   JButton button1;
   JLabel label1;

   public static void main(String[] args) {
      HelloSwingApp app = new HelloSwingApp();
      app.setTitle("Hello Win");
      app.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent we) {
              System.exit(0);
          }
      });
      app.setLocation(50, 50);
      app.setSize(200, 140);
      app.setVisible(true);
   }

   public HelloSwingApp() {
      Container pane1 = this.getContentPane();
      pane1.setLayout(null);
      button1 = new JButton("클릭하세요!");
      button1.addActionListener(this);
      button1.setBounds(40, 70, 120, 30);
      label1 = new JLabel("");
      label1.setBounds(30, 20, 120, 20);
      pane1.setBackground(new Color(0xFF, 0xFF, 0xEE));
      pane1.add(label1);
      pane1.add(button1);
   }

   private JDialog dialog1;
   private JPanel panDiag;

   public void actionPerformed(ActionEvent e) {
      Object src = e.getSource();
      if (src instanceof JButton) {
          if ((JButton) src == button1) {
              dialog1 = new JDialog(this, "메시지");
              dialog1.setSize(180, 120);
              dialog1.setLocation(300, 200);
              dialog1.addWindowListener(new WindowAdapter() {
                  public void windowClosing(WindowEvent we) {
                      dialog1.dispose();
                  }
              });
         
              panDiag = new JPanel() {
                  public void paint(Graphics g) {
                      g.drawString( "안녕하세요?", 30, 30 );
                  }
              };

              dialog1.add(panDiag);
              dialog1.setVisible(true);
              label1.setText("Hello, world!");
          }
      }
   }
}






Creative Commons License 
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다
Posted by Scripter
,



컴파일> javac -d . HelloWinApp.java
실행> java HelloWinApp

/*
 * HelloWinApp.java
 */

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

public class HelloWinApp extends Frame implements ActionListener {

   Button button1;
   Label label1;

   public static void main(String[] args) {
      HelloWinApp app = new HelloWinApp();
      app.setTitle("Hello Win");
      app.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent we) {
            System.exit(0);
          }
      });
      app.setLocation(50, 50);
      app.setSize(200, 140);
      app.setVisible(true);
    }
 
    public HelloWinApp() {
      setLayout(null);
      button1 = new Button("클릭하세요!");
      button1.addActionListener(this);
      button1.setBounds(40, 100, 120, 30);
      label1 = new Label("");
      label1.setBounds(30, 60, 120, 20);
      setBackground(new Color(0xFF, 0xFF, 0xEE));
      add(label1);
      add(button1);
   }

   private Dialog dialog1;
   private Panel panDiag;

   public void actionPerformed(ActionEvent e) {
      Object src = e.getSource();
      if (src instanceof Button) {
            if ((Button) src == button1) {
                dialog1 = new Dialog(this, "메시지");
                dialog1.setSize(180, 120);
                dialog1.setLocation(300, 200);
                dialog1.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent we) {
                        dialog1.dispose();
                    }
                });
         
                panDiag = new Panel() {
                    public void paint(Graphics g) {
                      g.drawString( "안녕하세요?", 30, 30 );
                    }
                };

                dialog1.add(panDiag);
                dialog1.setVisible(true);
                label1.setText("Hello, world!");
            }
      }
   }
}





Creative Commons License 
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다

Posted by Scripter
,