ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • JAVA-SWT 프로그래밍 기초
    개발노하우 2007. 6. 9. 02:50
     
    JAVA-SWT 프로그래밍
    Posted on 2004/8/26
    Topic: GUI 응용
    article_SWT_Study위키 홈으로
    1 소개
    1.1 SWT에 대해서
    2 SWT 프로그래밍 화경 구축 및 맛보기
    2.1 환경 구축
    2.2 Hello World를 통해서 익히는 Eclipse+SWT 개발
    2.2.1 프로젝트 생성
    2.2.2 코드 생성
    2.2.3 실행 시키기
    3 SWT 프로그래밍 일반
    3.1 SWT 애플리케이션의 기본 구조
    3.2 SWT 애플리케이션 제작
    3.3 SWT 패키지들
    3.4 다이얼로그
    3.5 Widgets
    3.5.1 위젯 이벤트
    3.5.2 자주사용하는 위젯
    3.5.3 버튼
    3.5.4 slider, scale, progressBar 위젯
    3.5.5 텍스트 위젯
    3.5.6 List 위젯
    3.5.7 Sash 위젯
    3.6 Composite 위젯
    3.6.1 Table 위젯

    1 소개 #

    SmartDic프로젝트를 진행하기 위해서 javaGUI라이브러리인 SWT를 필요로 한다. 아직까지 SWT를 다루어 본적이 없으므로 프로젝트의 원할한 진행을 위해서 SWT에 대한 스터디를 수행하기로 했다.

    예제들은 Eclipse를 이용해서 작성하고 테스트하도록 하겠다. Eclipse의 사용방법은 SWT 스터디 위키를 참고하기 바란다.

    1.1 SWT에 대해서 #


    SWT #

    java에서 GUI를 지원하기 위한 도구로 sun에서 개발한 Swing이 널리 사용되고 있었는데, IBM에서 통합개발 플랫폼인 Eclipse를 개발하면서 Swing 대신 자체적으로 개발한 GUI라이브러리를 제작한다. 이게 SWT 이다.

    • Swing : ?J2SE를 위한 GUI 툴킷
    • SWT : IBM의 공개 프로젝트인 Eclipse 플랫폼의 제작을 위해 별도로 개발된 라이브러리
    SWT는 Standard Widget Toolkit의 줄임말로 각 운영체제자체에서 제공되는 위젯 툴킷을 통합한 그래픽 라이브러리다. 이는 각 타겟 플렛폼에 꽤나 의존적이 될 수도 있음을 의미하지만, OS독립적인 API를 제공함으로써 이 문제를 해결하고 있다. 이들 API는 목표가 되는 운영체제 시스템의 GUI코드를 wrapper함으로써 개발자 입장에서는 운영체제에 신경쓰지 않고 동일한 코드를 유지할 수 있게 된다.

    덧붙여 설명하자면, Swing은 모든 위젯이 운영체제와 별개를 사용하는데(자바의 모토가 One make All use 아니던가) 그렇기때문에 Swing의 GUI는 웬지 눈에 낯설고 어색해 보이는 면이 있어왔다. 그러나 SWT는 가능한한 사용할 수있는 모든 Native Widget은 사용하고, 그러하지 않는 부분만 자바의 자체 위젯을 사용한다. 때문에 최대한 그 OS의 Native GUI와 비슷한 모습을 보여주는것이다.(Native에서 제공하지 않는 자체 위젯까지 포함하므로 때론 더 이쁠수도 있겠다. 물론 반대인 경우도 있겠지만).

    그럼 자바가 시스템에 독립적이지 않은게 아닌가? 하고 반문할지 모르지만 위에 설명된 바와같이 공통적인 API를 사용하므로서 (Abstract Layer라고 볼 수 도 있겠다) OS가 다르다고 해서 소스코드의 변경을 필요로 하지 않는것이다. (VM차원에서 Native Widget를 해당 API로 랩핑해주므로)

    다음은 현재 java에서 사용중인 GUI라이브러리에 대한 비교다.
    Component SWT Swing AWT
    Button X X X
    Advanced Button X X
    Label X X X
    List X X X
    Progress Bar X X
    Sash X X
    Scale X X
    Sash X X
    Slider X X
    Text Area X X X
    Advanced Text Area X X
    Tree X X
    Menu X X
    Tab Folder X X X
    Toolbar X X
    Spinner X X
    Tabler X X X
    Advanced Table X X


    2 SWT 프로그래밍 화경 구축 및 맛보기 #

    2.1 환경 구축 #

    우선은 개발환경을 구축해야 한다. 기본 개발환경은 Linux, ?JDK1.4기반이며 스터디를 위해서 Eclipse를 설치하기로 했다. 아무래도 SWT가 Eclipse의 일부로 개발된 측면이 있기 때문에 자연스러운 학습을 위해서 Eclipse가 필요하다고 판단되었기 때문이다.

    Eclipse는 http://www.eclipse.org에서 최신버전 3.0 (04/7/27일 현재)받을 수 있다. 설치는 압축푸는 걸로 끝이다. 이클립스와 함께 SWT개발과 관련된 라이브러리도 받아야 한다. 역시 위 사이트에서 받을 수 있다. SWT라이브러리를 받은다음 이클립스를 설치한 곳에 적당한 디렉토리를 만들어서 압축을 풀도록 하자. 필자의 경우 이클립스 설치디렉토리는 /usr/eclipse에 SWT는 /usr/eclipse/jar에 풀었다.

    다음은 이클립스를 통한 개발 모습이다.


    2.2 Hello World를 통해서 익히는 Eclipse+SWT 개발 #

    자바플렛폼에서의 개발이 그리 익숙치 않은 관계로 우선 SWT버젼의 Hello world출력 애플리케이션을 만들어 보기로 했다.

    2.2.1 프로젝트 생성 #
    이클립스가 실행되었다면, 새로운 File > New > Project 를 이용해서 새로운 프로젝트를 생성해야 한다. 그러면 아래와 같은 Project 생성 Wizard가 뜨게 된다.


    여기에서 java > java project 를 선택하고 Next 버튼을 클릭하도록 한다. 이제 프로젝트의 이름을 선택해 주어야 하는데, ?HelloWorld로 하자. 그다음 Finish 버튼을 누른다. 그럼 아래의 그림과 같이 ?HelloWorld 프로젝트가 생성된걸 확인할 수 있다.


    2.2.2 코드 생성 #
    프로젝트도 만들어지고 했으니 이제 코드를 생성해 보기로 하자. ?HelloWorld 프로젝트 이름을 마우스로 클릭한후 오른쪽 버튼을 클릭하면 팝업메뉴가 뜨는데 여기에서 New > Class를 선택하도록 한다. 그러면 Java Class 생성화면이 나오는데 Name에 ?HelloWorld를 넣고 Finish버튼을 클릭해서 새로운 클래스를 만들어 내도록 한다.

    그러면 아래와 같이 ?HelloWorld.java 에디터 화면이 생성된걸 확인할 수 있다.


    이제 코드를 완성하도록 하자. 다음은 ?HelloWorld출력을 위한 코드다.
    import org.eclipse.swt.widgets.*;
    import org.eclipse.swt.*;
        
    
    public class HelloWorld{
      public static void main(String[] args) {
          Display display = new Display();
          Shell shell = new Shell(display);
          Label label = new Label(shell, SWT.NONE);
        label.setText("Hello World!");
        
        shell.pack();
        label.pack();
          shell.open();
          while(!shell.isDisposed())
              if(!display.readAndDispatch())
                  display.sleep();
              
          display.dispose();
          label.dispose();
      }
    }
    

    그데 몇몇라인을 보면 빨간색 밑줄이 그어져 있는 것을 볼 수 있을 것이다. 이는 코드에 문제가 있다는 건데, 우리가 swt관련 패키지를 지원할 수 있도록 포함시키지 않았기 때문에 발생하는 에러다. C로 말하자면 -l"라이브러리" 를 하여 라이브러리를 링킹하지 않은것과 비슷하다고 볼 수 있겠다.

    이문제의 해결을 위해서는 프로젝트에 swt와 관련된 JAR파일을 추가시켜줘야 한다. 추가시키는 방법은 : 프로젝트 이름을 선택하고 마우스 왼쪽 버튼 클릭후 Properties를 클릭하도록 한다. 여기에서 java Build Path > Libraries를 선택하도록 한다. 그다음 Add External Jars를 클릭해서 SWT관련 JAR파일을 추가시켜주면 된다.


    2.2.3 실행 시키기 #
    이제 실행시키는 일만 남았다. 마찬가지로 우선 ?HelloWorld 프로젝트를 선택한다음 Run > Run 을 선택하도록 하자.

    그러면 다음과 Run환경 설정창이 뜬다. 이 화면을 통해서 우리는 각종 실행 인자와 환경변수와 같은 실행환경을 설정할 수 있다. C코드로 부터 실행파일을 만들때 가장 마지막으로 하는 일이 필요한 오브젝트나 라이브러리를 링크하는 작업이 있다. 마찬가지로 java환경에서도 이러한 작업이 필요로 한다. 우리가 만든 Hello World프로그램의 경우 SWT패키지를 사용하고 있으므로 SWT라이브러리를 사용하라고 알려줄 필요가 있다.

    이것은 다음과 같이 VM arguments 에 SWT라이브러리의 경로를 명시해줌으로써 알려줄 수 있다. 경로는 자신의 eclipse 설치 디렉토리에 따라 달라질 수 있다.


    swt관련 라이브러리의 경로는 리눅스를 기준으로 ./eclipse/plugins/org.eclipse.swt.gtk_3.0.0/os/linux/x86이다. 참고하기 바란다.

    이제 Run 버튼을 클릭해서 실행하도록 하자. 다음과 같은 실행결과물을 확인할 수 있을 것이다.


    3 SWT 프로그래밍 일반 #

    3.1 SWT 애플리케이션의 기본 구조 #

    SWT 애플리케이션은 블럭구조를 가지며 Display, Shell, Widget의 기본 블럭들로 이루어진다. Dispalys는 이벤트 loop를 관리하고 UI 쓰레드와 다른 쓰레드들간의 통신을 제어한다. Shell은 OS의 윈도우 메니저에 의해서 생성되는 윈도우 창을 관리한다. 모든 SWT 애플리케이션은 적어도 하나의 Dispaly와 하나 혹은 그 이상의 Shell 인스턴스를 필요로 한다.

    http://www.developer.com/img/articles/2004/03/25/figure_01.gif

    위 그림은 SWT 애플리케이션의 대략적인 구성을 서로 다른 관점을 통해서 보여주고 있다. 첫번째 다이아 그램은 UI 객체의 상속관계를 나타내고 있다. 두번째 다이아 그램은 UI 객체의 컨태이너 구조체를 보여주고 있다. 세번째 다이아 그램은 만들어진 UI를 보여준다.

    만약 애플리케이션이 다중 쓰레드를 이용한다면 각각의 쓰레드는 자신의 Display 인스턴스를 만들게 된다. 프로그래머는 Display.getCurrent()메서드를 이용해서 최근 활성화된 Dispaly의 인스턴스를 가져올 수 있다.

    Shell은 운영체제에서 윈도우를 나타내기 위해서 사용된다. shell은 maximized, normail, minimized 형태를 가질수 있다. shell 두가지 타입이 있다. 하나는 top-level shell로 자식을 생성하며 Display의 메인 윈도우가 된다. 다른 하나는 dialog shell로 다른 shell과 독립된다.

    shell의 타입은 쉘의 생성자에 의해서 넘겨지는 style bit 값에 의존적이다. 기본적으로 쉘은 ?DialogShell 타입이 된다. 이는 아무런 인자 없이 만들경우 ?DialogShell이 만들어진다는 뜻이다.

    몇몇 위젯의 특성(properties)는 반드시 생성시간에 설정되어야 한다. 이러한 위젯 특성을 style bits라고 부른다. Style bits는 SWT 클래스에 상수로 정의되어 있다. 예를들자면 Button button = new Button(shell, <styleBits>)형식으로 사용할 수 있다. sytle bits는 OR연산자 |를 이용할 수 있다. 만약 테두리가 있는 입력버튼을 만들기를 원한다면 SWT.PUSH | SWT.BORDER 해주면 된다.

    3.2 SWT 애플리케이션 제작 #

    SWT 애플리 케이션은 다음과 같은 순서로 만들어 진다.
    • Display 생성
    • 하나 이상의 shell 생성
    • shell의 레이아웃 설정
    • shell에 포함될 위젯 생성
    • shell windows을 연다.
    • event dispatching loop 작성
    • display의 배치
    다음은 SWT 애플리케이션의 일반적인 구성이다.
    import org.eclipse.swt.layout.RowLayout;
    import org.eclipse.swt.widgets.Display;
    import org.eclipse.swt.widgets.Shell;
    
    public class SliderExample
    {
        public static void main(String args[])
        {
            Display display = new Display();     // 1
            Shell shell = new Shell(display);    // 2
            shell.setLayout( new RowLayout());   // 3
            // -------------------------------
            // 여기에 적당한 코드를 넣는다. 
            // -------------------------------
            shell.pack();
            shell.open();                        // 4
            while( !shell.isDisposed())          // 5
            {
                if(!display.readAndDispatch()) 
                display.sleep();
            }
            display.dispose();                   // 6 
        }
    }
    

    위 예제는 실제 코드가 없기 때문에 비어있는 윈도우를 생성한다. 이를테면 SWT애플리케이션 제작을 위한 템플릿 코드정도로 생각하면 된다.

    1. 모든 SWT애플리케이션은 Dispaly와
    2. 하나 이상의 Shell을 필요로 한다. shell은 객체의 조합이다.
    3. 만약 layout을 잡지 않는다면, 추가된 위젯은 보이지 않게 된다.
    4. 만들어진 shell을 연다.
    5. 이벤트 핸들링 루프를 만들고 GUI 이벤트를 읽는다.
    6. 사용되지 않는 display를 버린다.

    3.3 SWT 패키지들 #

    SWT는 여러개의 패키지로 구성되어 있다. 이들 패키지에 대한 자세한 내용은 Eclipse API 문서에 정의되어 있다. 여기에서는 중요한 패키지들을 간단하게 설명하도록 하겠다.

    • org.eclipse.swt : SWT 클래스에 의해서 사용되는 상수와 예외값들이 정의되어 있다. SWT패키지는 SWT, ?SWTException, ?SWTError 3개의 클래스로 구성되어 있다. SWT는 keyboard, error, color, layout, text sylte, button등과 같은 가장 자주 사용되는 라이브러리들을 포함하고 있다.
    • org.eclipse.swt.widgets : 핵심 SWT 위젯 컴포넌트들과 위젯을 지원하기 위한 인터페이스와 클래스들을 포함하고 있다.
    • org.eclipse.swt.events: SWT 컴포넌트들에 의해 사용되는 이벤트 타입과, 리스너, 이벤트들을 정의하고 있다. 이 패키지는 Listener interfaces, Adapter class, Event class를 포함하고 있다.
    • org.eclipse.swt.dnd : SWT 위제에서 drag-and-drop을 지원하기 위한 클래스를 포함한다.
    • org.eclipse.swt.layout : SWT위젯의 자동크기변화와 위치지정과 관련된 클래스를 포함한다.
    • org.eclipse.swt.print : 출력을 위한 클래스 포함
    • org.eclipse.swt.graphics : 점, 선, 면, 색, 커서, 폰트, Graphics context등 이미지와 관련된 클래스를 제공한다.

    3.4 다이얼로그 #

    다이얼로그는 운영체제의 윈도우 환경에서 지원하는 것을 사용한다. 예를들어 리눅스라면 GTK에서 지원하는 다이얼로그를 사용하게 된다. SWT의 다이얼로그는 Dialog 클래스로 부터 파생된다. dialog는 위젯이 아니지만 위젯을 포함할 수 있다.

    http://www.developer.com/img/articles/2004/03/25/figure_02.gif

    어떤 다이얼로그들은 properties 를 조정할 수 있다. 다이얼로그는 아래와 같이 사용할 수 있다.
    MessageBox messageBox = 
    new MessageBox(shell, SWT.OK|SWT.CANCEL);
    if (messageBox.open() == SWT.OK)
    {
        System.out.println("Ok is pressed.");
    }
    
    각 다이얼로그는 open()메서드를 이용해서 다른 타입을 리턴받을 수 있다. 예를 들어서 ?MessageBox dialog는 open()메서드로 부터 int 값을 리턴받는다. 그러므로 각각의 다이얼로그 마다 리턴되는 타입에 맞도록 처리를 해주어야 한다.

    ?ColorDialog는 색선택 창을 보여주는데, RGB 객체를 리턴한다.

    ?DirectoryDialog는 디렉토리 선택을 위한 창을 보여주는데, open()메서드를 사용할 경우 선택된 디렉토리의 이름(문자열)을 리턴한다.

    Font dialog는 시스템에서 제공하는 모든폰트에 대한 목록을 제공하고 선택할 수 있도록 한다. ?FontData 객체가 리턴된다.

    ?FileDialog는 파일선택 창을 띄운다. 여기에 더해서 확장자 필터, 경로 필터, 파일이름 필터등을 적용할 수 있다. 다이얼로그는 다음과 같은 타입을 가지고 있다.

    SWT.OPEN Open 버튼을 보여준다. 파일을 열고자 할때 사용한다.
    SWT.SAVE Save 버튼을 보여준다. 파일을 저장할때 사용한다.

    ?PrintDialog는 프린트와 관련된 여러가지 조작을 할 수 있는 창을 보여준다. open()메서드를 호출했을 경우 ?PrintData 객체를 리턴한다.

    ?MessageBox 다이얼로그는 사용자와 상호작용하기 위해서 사용할 수 있다. 다이얼로그는 목적에 따라서 여러가지 타입을 가질 수 있는데, 아래와 같이 | 연산을 통해서 다양한 타입을 만들어 낼 수 있다.
    MessageBox messageBox = new MessageBox(shell,
                SWT.OK|
                SWT.CANCEL|
                SWT.ICON_WARNING);
                messageBox.setMessage("www.korayguclu.de");
                messageBox.open();
    
    이렇게 해서 만들어진 다이얼로그는 다음과 같이 보일 것이다. 아래 그림은 리눅스에서 실행시킨 경우다. http://www.joinc.co.kr/albums/album01/akl.png ?MessageBox에서 사용할 수 있느 아이콘은 아래에 정리해 두었으니 참고하기 바란다. || SWT.ICON_ERROR || http://www.developer.com/img/articles/2004/03/25/image_01.gif ||
    SWT.ICON_INFORMATION http://www.developer.com/img/articles/2004/03/25/image_02.gif
    SWT.ICON_QUESTION http://www.developer.com/img/articles/2004/03/25/image_03.gif
    SWT.ICON_WARNING http://www.developer.com/img/articles/2004/03/25/image_04.gif
    SWT.ICON_WORKING http://www.developer.com/img/articles/2004/03/25/image_02.gif

    3.5 Widgets #

    위젯은 윈도우를 구성하는 공통 GUI객체다. 버튼, 체크박스, 팝업메뉴, 슬라이드바, 스핀박스, 텍스트 입력창등이 여기에 포함된다.

    SWT GUI 객체는 widget과 Control 클래스로 부터 파생된다. 위젯 객체는 모든 공통 GUI클래스를 위한 기본 클래스와 메서드를 정의하고 있다. Control 클래스는 모든 windowed GUI 클래스의 기본 클래스로 윈도우와 다이얼로그의 display와 관련된 제어를 맡는다.

    다음은 위젯의 계층구조를 나타낸 그림이다.

    http://www.developer.com/img/articles/2004/03/25/figure_04.gif

    3.5.1 위젯 이벤트 #
    3.5.2 자주사용하는 위젯 #
    http://www.developer.com/img/articles/2004/03/25/figure_05.gif

    모든 Control 클래스는 border를 가질 수 있다. border는 SWT.BORDER 상수를 이용해서 추가 시킬 수 있다.

    3.5.3 버튼 #
    버튼은 다양한 스타일을 가지고 있으며 bit값에 의해서 설정할 수 있다. 아래의 테이블은 버튼과 그 스타일을 정리한 테이블이다.

    상수 사용예 설명
    SWT.ARROW http://www.developer.com/img/articles/2004/03/25/image_05.gif popup메뉴등을 위해서 사용한다.
    SWT.CHECK http://www.developer.com/img/articles/2004/03/25/image_06.gif 체크박스
    SWT.PUSH http://www.developer.com/img/articles/2004/03/25/image_07.gif 푸쉬버튼
    SWT.RADIO http://www.developer.com/img/articles/2004/03/25/image_08.gif 라디오 버튼
    SWT.TOGGLE http://www.developer.com/img/articles/2004/03/25/image_06.gif 푸쉬버튼과 비슷하지만 버튼을 누르면 이전의 누름버튼은 원상태로 된다.

    3.5.4 slider, scale, progressBar 위젯 #
    scale는 연속된 범위내에서 특정한 값을 선택하기 위해서 사용하는 위젯이다. 범위는 Scale 클래스의 setMinimum()과 setMaximum()메서드를 이용해서 정할 수 있다. 선택된 값은 getSelection()메서드를 이용하면 된다. scale는 한번에 하나의 값만을 가져올 수 있다.

    http://www.developer.com/img/articles/2004/03/25/figure_06.gif

    생성자를 통해서 넘기는 인자를 통하여 다른 모양의 scale와 slider위젯을 생성할 수 있다. slider와 scale를 위해서 사용되는 상수는 아래와 같다.

    SWT.HORIZONTAL 수평으로 배치
    SWT.VERTICAL 수직으로 배치

    옵션으로 SWT.BORDER 상수를 이용해서 scale주변에 테두리를 만들어 줄수 있다.
     final Slider slider =
       new Slider(shell,SWT.VERTICAL);
     slider.setMinimum(0);
     slider.setMaximum(100);
     slider.setIncrement(5);
     slider.setPageIncrement(10);
     slider.setSelection(25);
     slider.addSelectionListener(
      new SelectionAdapter()
      {
        public void widgetSelected(SelectionEvent e)
        {
          System.out.println("Selection:"+
                              slider.getSelection());
        }
      }
     );
    

    ?ProgressBar 위젯은 Slider, Scale 위젯과 비슷하다. 그러나 선택이 불가능하다. 이것은 어떤 작업의 진척정도를 나타내기 위해서 사용한다. SWT.SMOOTH와 SWT.INTERMINATE 상수를 이용해서 ?ProgressBar 위젯을 변경할 수 있다.

    3.5.5 텍스트 위젯 #
    Text 위젯은 텍스트 편집창을 만들기 위해서 사용한다. 필요에 따라서는 하나의 편집창에서 서로 다른 폰트와 색을 동시에 출력하는 기능을 가진 ?StypleText 위젯을 사용할 수도 있다.. 이 위젯을 사용하면 전경색, 배경색과 폰트를 문자단위로 지정해 줄 수 있다.

    http://www.developer.com/img/articles/2004/03/25/figure_07.gif

    다음은 text 편집창을 만드는 예제 코드다.
    import org.eclipse.swt.layout.RowLayout;
    import org.eclipse.swt.widgets.Display;
    import org.eclipse.swt.widgets.Shell;
    import org.eclipse.swt.widgets.MessageBox;
    import org.eclipse.swt.widgets.Slider;
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.widgets.Text;
    
    public class SliderExample {
         public static void main(String args[])
          {
         Display display = new Display();
         Shell shell = new Shell(display);
         shell.setLayout( new RowLayout());
         Text text =
            new Text(shell, SWT.MULTI|SWT.WRAP);
         text.setText("Hello world!!");
         
         shell.pack();
         shell.open();
         while( !shell.isDisposed())
            {
              if(!display.readAndDispatch()) 
              display.sleep();
            }
         display.dispose();
          }
    }
    

    3.5.6 List 위젯 #
    List widget은 목록중에서 하나의 원소를 선택할 수 있는 인터페이스르 제공한다. 만약에 요소들중 하나를 선택하게 되면 이벤트 리스너에게 신호를 보내게 된다(QT의 슬롯,시그널 개념과 비슷하다.). SWT.SINGLE와 SWT.MULTI를 이용해서 단일 혹은 다중 선택이 가능하다. 리스트 위젯은 기본적으로 스크롤이 가능한 위젯임으로 SWT.H_SCROLL과 SWT.V_SCROLL 상수를 이용할 수 있다.

    http://www.developer.com/img/articles/2004/03/25/figure_08.gif

     final List list = new List(shell,SWT.MULTI);
     for (int i = 1; i < 11; i++) 
     {
       list.add(i+".)www.korayguclu.de");
     }
     list.addSelectionListener(
       new SelectionAdapter()
       {
         public void widgetSelected(SelectionEvent e)
         {
           List list = (List) e.getSource();
           String[] str = list.getSelection();
           for (int i = 0; i < str.length; i++)
           {
             System.out.println("Selection: "+str[i]);
           }
         }
      }
     );
    

    3.5.7 Sash 위젯 #
    Sash 위젯은 여러개의 위젯이 포함되었을 때, 서로의 영역을 변경할 수 있도록 만들어 준다. 마우스를 Sash 경계에 가져가면 좌우 화살표 혹은 상하 화살표로 바뀌면서 영역의 크기를 조정할 수 있도록 만들어준다.

    http://www.developer.com/img/articles/2004/03/25/figure_09.gif

    Button button = new Button(shell,SWT.PUSH);
    button.setText("Button0");
    
    Sash sash = new Sash(shell, SWT.VERTICAL);
    
    Button button1 = new Button(shell,SWT.PUSH);
    button1.setText("Button1");
    

    3.6 Composite 위젯 #

    Composite 위젯은 다른 위젯들을 포함해서 그룹화하고 배열시키기 위한 일종의 Container 위젯이다. 또한 위젯 뿐만 아니라 Composite위젯 클래스 자체를 포함시킬 수도 있다. SWT의 Composite는 Swing의 그것다는 달리 add 메서드를 제공하지 않는다. 대신 생성자를 통해서 필요한 위젯을 배치시켜줘야만 한다.

    그리고 아래 그림에서 처럼 Shell 자체를 포함시킬 수도 있다.

    http://www.developer.com/img/articles/2004/03/25/figure_10.gif

    Composite 위젯은 스크롤 가능한 위젯으로 상수 SWT.H_SCROLL 과 SWT.V_SCROLL을 이용해서 스크롤을 추가시킬 수도 있다.

    3.6.1 Table 위젯 #
    테이블 위젯은 문자열이나 이미지를 출력하기 위한 위젯이다.
    덧글쓰기 | 엮인글 쓰기 이 포스트를.. 이 포스트 담기 -->
    이클립스에서 새로운 프로젝트 생성하기 | Eclipse 2005/05/13 18:20
    http://blog.naver.com/huskies/12817716

    java.net과 이클립스를 이용한 오픈

    소스 자바 어플리케이션 개발

    1부. 이클립스에서 새로운 프로젝트 생성하기


    Martin Pllu
    martinpllu-AT-dev.java.net

    소개


    이 튜토리얼 시리즈는 java.net에서 호스팅 되어 있는 오픈소스 자바 어플리케이션을 이클립스를 사용하여 개발하는 방법을 설명한다. 이 글은 자바에 대한 지식은 있지만 이클립스는 다뤄보지 않는 개발자들을 대상으로 한다.


    문의사항 또는 피드백이 있다면 튜토리얼의 포럼을 이용하기 바란다.


    이클립스에서 새로운 프로젝트를 어떻게 만드는지 볼 것이다. 이미 만들어진 프로젝트에 참여할 예정인 경우와 같이 새로운 프로젝트 생성이 불필요한 경우에도 이클립스의 주요 컨셉들을 이해하기 위해 이글을 읽어보기를 권장한다.

    다음번 튜토리얼의 제목은 다음과 같다. :
    • 이클립스와 CVS를 이용한 팀단위 개발(2 부)
    • 이클립스에서 Ant와 JUnit를 함께 사용하여 빌드 및 테스팅 자동화하기
    튜토리얼을 시작하기전에 이클립스와 Java.net의 몇가지 중요한 특징들을 살펴보자.

    이클립스의 주요기능


    이클립스는 자바개발을 위한 강력하고 풍부한 기능을 제공하는 통합개발환경(IDE)이다. 보다 자세한 정보에 대한 것은 아래의 링크(이클리스 온라인 도움말)를 통하여 확인해볼 수 있다.
    IDE를 사용해본적이 없거나 마지막으로 써 본 것이 몇 년 전이라면 이클립스를 주목해보는것이 좋을 것이다. 여러분은 이클립스의 편의성과 진보된 기능에 놀랄 것이다. 저자가 Emacs에서 이클립스로 개발툴을 전환한지 몇년이 되었는데 이전의 개발보다 높은 생산성을 보여주었다. 리팩토링 자동화 지원은 정말 멋진 기능이다.

    이클립스는 Windows, Linux, Max OS X, Solaris, AIX 그리고 HP-UX에서 실행할 수 있다. 자바로 작성되었지만 SWT라고 불리는 그래픽 툴킷을 사용했다. SWT는 운영체제가 제공하는 GUI를 활용하여 매우 멋진 look & feel을 제공한다.


    이클립스는 복잡한 플러그인 아키텍처 를 가지고 있는 범용적인 어플리케이션 플랫폼이며, 이클립스의 자바 IDE는 플러그인의 한 종류이다. 이클립스를 활용하여 고유의 플러그인들을 개발하거나 웹브라우저나 금전 관리 프로그램 등의 "rich client" 어플리케이션을 개발할 수 있다. 이클립스 플랫폼 플러그인 개발 가이드를 보면 보다 많은 정보를 얻을 수 있을 것이다.

    이클립스는 독립적인 이클립스 재단에 의해 개발된 무료 오픈 소스 소프트웨어이다. 이 재단에는 IBM Rational, Borland, Red Hat, and SuSE 등과 같은 산업내의 주요 회사들이 참여하고 있다. 태생적으로 오픈소스인지라 오픈소스 개발에 이상적이다. 일례로 CVS 클라이언트 GUI를 내장하고 있어(2 부에서 다룬다) java.net과 같은 CVS 호스팅 사이트에서 개발하기가 용이하다.

    이클립스의 문서는 훌륭하다. 웹사이트온라인 도움말을 보기바란다.

    오픈소스와 상용를 막론하고 별도의 이클립스 플러그인을 개발하는 커뮤니티 활동도 활발하다. 아래 두 링크를 통해 훌륭한 플러그인들은 찾을 수 있을 것이다. 이클립스 사용자들은 공식 이클립스 배포판과 플러그인 개발 커뮤니티로 부터 정기적으로 새로운 기능을 제공받는다.

    java.net의 주요기능


    java.net은 성공적인 자바 온라인 커뮤니티로 뉴스, 아티클, 포럼, 위키, 그리고 다양한 오픈소스 프로젝트를 위한 호스팅과 같은 기능을 제공해준다. 2003년 Sun Microsystems에 의해서 오픈소스 자바 개발을 지원하기 위해서 생겨났지만, java.net은 이클립스 재단과 마찬가지로 완전히 독립적인 단체이다. java.net에 있는 몇몇 커뮤니티들은 다양한 기술과 관심사들을 가지고 있다. 예를들어 Java Tools, Java Enterprise, Jini, Java Linux와 같은 것이 있다.
    Javapedia국제 교육과 학습과 같은 몇몇 커뮤니티들은 지식을 공유하여 자바를 배우는 좋은 곳들이다. 이들 sourceforge와 같은 다른 개발 호스팅 웹사이트에서 나와 java.net로 옮겨온 커뮤니티들이다.

    새로운 프로젝트를 만드는것이 쉽다 . 프로젝트는 만드는데 필용한 것은 오직 좋은 아이디어와 프로젝트 요청 폼뿐이다. 여러분은 java.net에 호스팅 되거나 어딘가 다른곳에 호스트되어있지만 java.net과 연결된 프로젝트들의 온라인 프로젝트 디렉토리 를 검색할 수 있다. 새로운 프로젝트를 시작하기 전에 기존의 프로젝트들을 확인하여 이미 존재하는 프로젝트를 또 생성하지 않도록 해야한다. 만약 여러분의 아이디어가 익숙한 기존 프로젝트의 질을 높이는 것이라면 최종물은 유사한 프로젝트가 되기도 한다. 기존 프로젝트에 참여하고자 하는 경우는 프로젝트의 웹사이트에 적혀있는 소유주에게 이야기하면 된다.

    java.net은 CVS를 사용하여 소스코드에 대한 제어를 한다. 만약 여러분이 CVS를 사용해본적이 없다고 하더라고 걱정할 것은 없다. 2 부에서 여러분에게 단계별 가이드를 제공해주겠다. CVS에 들어있는 내용물들을 웹상에서 확인할 수 있고, CVS안의 코드나 문서의 연결이 수월해진다. 이 링크를 통해 확인해보라.

    이슈 트래커, 공지 게시판, 토론포럼 그리고 메일링리스트 등등 java.net 이 제공하는 몇몇 유용한 기능들은 여러분이 팀의 일부로 작업할 때에 도움을 준다. 프로젝트 소유주들은 프로젝트의 멤버들과 역할에 대한 관리가 쉽고, 프로젝트의 멤버라면 CVS가 체크인 되거나 새로운 포럼을 생성되는 경우에 이메일을 통해서 프로젝트의 변경이 생길때 마다 변경사항을 확인할 수 있다. RSS 피드 또한 가능하여 여러분의 프로젝트를 다른사람들이 확인할 수 있게된다. 프로젝트의 웹페이지는 설정하기 매우 쉽다(단지 HTML만 체크하면 된다) 사이트 전체 검색과 개별 프로젝트내에서의 검색을 지원하는 좋은 검색 엔진 또한 제공된다.




    튜토리얼 1부 - 이클립스에서 새로운 프로젝트 설정하기


    이번 튜토리얼에서는 이클립스를 사용하여 새로운 자바 프로젝트는 생성하고 설정하는 방법에 대하여 다루겠다. java.net에서의 작업은 다음 튜토리얼에서 다루겠다.

    선행사항


    • 이클립스 3.0이나 그 이후의 버전을 다운로드한다. (본 튜토리얼 번역본은 3.1을 기준으로 한다)
    • 자바 1.3 또는 그 이후 버전이 필요하다. 만약 적절한 자바 버전이 설치되어 있지 않다면 http://java.sun.com 에서 다운로드 하여 설치한다.

    이클립스의 다운로드나 시작에 문제가 있다면이클립스 FAQ를 참고하길 바란다.

    이클립스 시작하기


    튜토리얼의 예제로 사용하기 위해 javatools-demo라는 프로젝트를 사용한다.
    먼저 이클립스를 실행시키고 여러분의 작업공간(workspace)의 경로를 설정한다.
    작업공간은 이클립스에서 사용할 여러분의 소스코드가 저장되는 폴더를 의미한다.


    "Use this as the default..." 옵션을 선택하면 항상 같은 작업공간에서 이클립스가 실행된다. 나중에 여러 개의 작업공간 중에서 선택하여 이클립스를 실행하기를 원할 수 있으므로 지금은 이 옵션을 선택하지 않기를 권장한다.

    이클립스가 시작되면 환영페이지를 볼 수 있다:



    도움말 구하기


    이클립스의 도움말은 언제든지 Help->Help Contents에서 볼 수 있다. 이 도움말은 eclipse.org 웹사이트와 동일한 내용이다.
    (역자주 : Eclipse의 도움말은 자체적인 웹서버를 통해서 서비스되기 때문에 로딩 시에 시간일 걸릴수 있다.)

    프로젝트 생성하기


    환영페이지를 닫는다. Navigator패널에서 오른쪽 마우스 버튼을 클릭하고 New->Project를 선택한다.





    "Java Project"를 선택하고 "Next"를 클릭한 후, 나타나는 다음과 같은 창에 여러분의 프로젝트 이름을 적는다:



    "Finish"를 클릭한다. 자바 퍼스펙티(Java perspective)로 변경할 것인지 묻는 프롬프트 창이 뜨게 된다면 "Yes"를 선택한다.

    퍼스펙티브(Perspectives)

    이클립스는 서로 다른 유형의 작업을 위해서 다양한 퍼스펙티브를 제공한다. 사용 가능한 모든 퍼스펙티브를 보고 싶다면 Window->Open Perspective->Other...를 선택하면 된다.



    지금 우리가 위치한 "Java" 퍼스펙티브는 자바 어플리케이션을 개발하는데 유용한 편집기, 뷰(views)와 메뉴 아이템들을 제공해준다. 자바 프로젝트를 생성하기 전의 "Resource" 퍼스펙티브는 윈도우 익스플로러 스타일의 파일 탐색기와 같은 기본적인 도구들을 제공한다.

    빠르게 퍼스펙티브를 변경하고 싶다면 이클립스창의 오른쪽 상단의 버튼을 이용하면 된다.




    프로젝트는 앞서 선택한 작업공간에 저장된 디렉토리일 뿐이다. 파일시스템에서 직접 확인해 보자.

    JRE 변경


    자바 퍼스펙티브의 Package Explorer 패널에 새로 만들어진 프로젝트에서 오른쪽 클릭을 하고, Properties를 선택한다. Properties 대화창의 왼쪽 패널에서 Java Build Path를 선택하면 프로젝트 클래스패스를 조작할 수 있다.

     

    Libraries 탭을 통해 확인해보면, 현재는 오직 JRE 시스템 라이브러리만 등록된 것을 알 수 있을 것이다. 기본 설정의 JRE 시스템 라이브러리는 이클립스를 실행하는데 쓰이는 JRE를 의미한다. 필자의 경우는 자바 5.0 JRE가 설치되어서 사용되고 있다. 여러분이 어떤 버전의 자바를 설치했느냐에 따라 다른 JRE를 보게 될 수 있다

    여러분이 다른 JRE를 쓰고자 할 수도 있다. 예를 들어 기본 설정은 자바 5.0 이지만, 여러분의 프로젝트가 보다 많은 사람들에게 쓰일 수 있게 하기 위해서 자바 1.4 혹은 1.3 버전과 호환되기를 원할 수 있다.


    기본적인 JRE에 만족한다면 다음 섹션으로 넘어가도 무방하다.


    먼저 여러분의 컴퓨터에 알맞은 JDK 또는 JRE가 설치되어 있어야 한다. 그렇지 않다면 http://java.sun.com 에서 다운로드하여 설치해야 한다.

    "Add Library"를 클릭한다:




    "Next"를 클릭하고 "Installed JREs..."를 클릭한다.



    "Add"를 클릭한다.

    다음 대화창에서 여러분이 사용할 JRE 나 JDK를 찾은 후 이름을 입력한다. 여러분이 새로 추가하는 JRE에 여러분이 부여하는 이름이다.

     

    "OK"를 클릭하고 새로운 JRE를 선택한다.

     

    "OK"를 클릭하고 "Finish"를 클릭한다. 여러분의 프로젝트는 새로운 JRE로 컴파일하게 될 것이다.

     

    소스 폴더 생성하기


    Properties 대화창에서 "Source" 탭을 선택한다.



    이클립스의 프로젝트는 자바 소스 파일을 포함하는 하나 이상의 소스 폴더를 가질 수 있다. 최초에는 프로젝트 디렉토리 자체가 유일한 소스 폴더가 된다.

    여러개의 소스 폴더를 사용하는 것은 다른 종류의 코드들을 분리하는데 좋은 방법이다. 이러한 방법을 활용하면 작업이 더 수월해지고, 나중에 다루게 되는 Ant 빌드 스크립트를 간결하게 할 수 있다.

    "Add Folder"를 클릭하고 "src"라고 쓴다.



    프롬프트창에서 "Yes"를 클릭한다.



    "Add Folder..."를 다시 클릭하고 "Create New Folder..."를 클릭한다. 이번엔 폴더를 "test" 라고 명명한다. "OK"를 연속해서 클릭한다.

    여러분은 이제 두 개의 소스 폴더를 확인할 수 있다.



    "Order and Export" 탭을 클릭하면 프로젝트의 자바 코드를 컴파일할 때 사용하는 클래스패스 전체를 볼 수 있다. 아직 우리는 소스 코드를 작성하지는 않았다.

    이제 클래스패스에는 JRE와 함께 두 개의 소스 폴더가 포함되어 있다.

    .

    클래스 저장 폴더(Output folder)

    여러분이 프로젝트 디렉토리가 아닌 별도의 소스 폴더를 사용하게 되면 컴파일러는 생성된 클래스 파일을 "output folder"라고 부르는 별도의 폴더에 저장한다. 위의 대화창에서 볼 수 있듯이 클래스 저장 폴더는 프로젝트 아래에 있는 bin 디렉토리로 설정된다. 특별한 이유가 없는 경우는 이러한 설정을 변경하지 않는 것이 좋다.

    기본적으로 여러분은 bin 디렉토리나 클래스 파일을 Package Navigator에서 볼 수 없게 된다. Navigator로 뷰를 전환하면 프로젝트의 모든 파일과 디렉토리를 걸러지지 않은 채로 보게된다.

    외부에서 만든 JAR 파일 가져오기


    여러분의 어플리케이션이 외부에서 제작한 라이브러리를 사용하는 경우에는 JAR 파일 형태로 프로젝트에 포함시키고, 프로젝트의 클래스패스에 추가할 수 있다.

    예제 어플리케이션이 날짜를 처리할 필요가 있어서 잘 만들어진 Joda Time API를 사용하기로 했다고 가정해보자.

    먼저 실행 파일 형태의 라이브러리를 다운로드 하고, 압축을 해제한다. 그리고, 여러분의 프로젝트에 새로운 폴더를 생성한다.





    새로운 폴더 생성을 위한 창이 뜨면, 폴더를 lib 라고 이름 짓는다. 새로 만든 폴더에서 오른쪽 마우스 클릭을 하고, "Import..."를 선택한다.




    대화창이 뜨면, "File System"을 선택하고 "Next"를 클릭한다. 라이브러리의 압축을 풀어 둔 디렉토리를 찾아서 JAR 파일을 선택한다.

    "Browse" 버튼을 선택하고 정확하게 JAR 파일이 위치한 디렉토리를 찾아야 한다. 그렇지 않은 경우에는 JAR 파일을 포함하고 있는 디렉토리 이외에 원치 않는 폴더까지 가져올 수 있음을 유의하자.



    "Finish"를 클릭한다. 정상적으로 수행했다면 다음과 같은 결과를 얻는다.



    이제 JAR 파일을 프로젝트 클래스패스에 추가해보자. 프로젝트에서 오른쪽 마우스를 클릭하고 "Properties" 를 선택한다. "Java Build Path"의 "Libraries"탭으로 이동한다.



    "Add JARs..."를 선택하고 새로 가져온 JAR를 선택한 뒤 "OK"를 클릭한다.



    소스 코드 가져오기

     
    Eclipse로 가져올 기존의 소스 코드가 없다면 이번 섹션은 넘어가도 무방하다.


    여러분의 프로젝트에서 마우스 오른쪽 버튼을 클릭하고 "Import"를 선택하면 코드를 가져올 수 있다.
       


    여러분의 코드가 ZIP이나 JAR형태의 파일이라면 "Zip file"을 선택한다. 그 외의 경우는 "File System"을 선택한다. 나머지 진행에 관한 부분은 별도의 설명이 필요없을 것이다.

    클래스 생성하기


    여러분이 새로운 자바 코드를 생성하기를 원한다면, "src" 소스폴더에서 마우스 오른쪽 버튼을 클릭한 후 "New->Class"를 선택한다.



    클래스가 위치할 패키지의 이름을 적는다.


    도메인 이름을 거꾸로 적는것이 일반적인 패키지 이름을 적는 규칙이라고 하더라도, net.java 를 프로젝트의 접두어로 사용하지 않겠다. 그 이유는 링크 시킨 위키에서 잘 설명되어 있다.



    org.jtdemo라고 하겠다..

    더 이상의 설명을 필요하지 않을 것이다. 자유롭게 테스트 해보자



    에디터 윈도우에서 여러분이 방금 만들어 낸 클래스를 볼 수 있다.




    뷰와 에디터

    이클립스에서는 에디터가 구별된다. 위에 보이는 자바 에디터와 같이 에디터는 직접 수정할 수 있는 내용(content)를 보여주는 창이다. 에디터에서 수정한 변경사항은 여러분이 저장하기 전까지는 아무런 영향을 미치지 않는다. 에디터의 타이틀바를 드래깅하여 다양한 형태로 겹치게 하거나 격자로 놓을 수 있다. 열려진 모든 에디터들의 목록을 보고 싶다면 Ctrl-E를 누르면 된다.

    뷰는 내용(content)을 보다 추상화 된 형태로 보여주는 창이다. 예를들어 Package Explorer, Problems, Outline 뷰와 같은 것들이 뷰라고 할 수 있다. 뷰에서의 변경사항은 즉시 반영된다. 뷰의 타이틀 바를 드래그하여 다양한 형태로 고정시킬 수 있고, 겹치게 하거나 격자형태로 위치시킬 수 있다. 새로운 뷰를 열고 싶다면 Window->Show View->Other...를 선택하면 된다.

    해당 뷰나 에디터를 최대화시키고 싶다면 타이틀바를 더블클릭하거나 Ctrl-M을 누르면 된다.


    이제 여러분이 코드를 작성할 준비가 되었다.

    이클립스에는 자바 개발에 필요한 유용한 기능이 있지만, 아직 여기서 그 기능들을 설명하지는 않는다. 어떤 것들이 가능한지 알아보기 위해서는 자바 개발 도구 팁과 기법이클립스 기본 팁과 기법을 직접 보고, 직접 조작해볼 수 있다.

    preference 공유하기


    대부분의 이클립스의 기능들은 preference를 통해 다양한 방식으로 설정이 가능하다. 여러분의 preferences를 다른 사람들과 공유하고자 할 수 있다. 가령, 동일한 코딩 스타일을 규칙으로 삼고 싶다고 가정하자. 또한 여러개의 작업공간을 가지고 있고 그 작업공간들에서 모두 같은 preference를 사용하고 싶다고 가정해 보자.

    Preference 대화창(Window->Preferences)에서 Export 버튼을 사용하여 여러분의 preference를 내보낼 수 있다. 이렇게 하면 XML 형식으로 여러분의 Preferences를 내보게 된다. 내보내진 Preferences는 Import 버튼을 사용하여 가져올 수 있다.

    다수의 프로젝트들와 Order and Export 탭


    필요에 따라 여러개의 자바 프로젝트들을 생성하고, 다른 프로젝트의 내용을 서로 사용할 수도 있다. "other"라는 이름의 새로운 자바 프로젝트를 만들고, 빌드 경로를 보자. (마우스 오른쪽 클릭후, Properties, 자바 빌드 패스(Java Build Path)). "Add..." 버튼을 누르고 기존 프로젝트 항목을 체크하여 빌드할 때 사용할 수 있도록 한다.



    기존 프로젝트의 빌드 패스를 보자. "Order and Export" 탭에 프로젝트의 클래스패스의 모든 항목들이 포함되어 있다. 이들 항목 들 중에서 체크가 되어진 것은 노출(Exported)된 것인데,이들 항목은 이 프로젝트에 의존적인 모든 프로젝트의 클래스패스에 자동으로 추가된다. 예를들어 우리가 joda-time-098.jar 항목을 체크하였다면 자동으로 "other" 프로젝트의 클래스패스에 추가된다.



    어떤 항목이든 선택하여 클래스패스에서의 순서를 "Up", "Down" 버튼을 사용하여 변경할 수 있다.

    java.net 어플리케이션들을 위한 단일 프로젝트 사용하기

    만일 여러분이 java.net에 호스팅 하고자 하는 어플리케이션을 생성하려고 한다면 하나의 프로젝트를 이용하라. 그렇게 하는 것이 CVS로 작업하는데 더 용이하다.

    만일 어플리케이션 코드의 다른 부분을 별도로 관리하기를 원한다면 소스 폴더를 활용하라. 외부의 이클립스 프로젝트를 사용하기를 원하는 경우, 예를 들어 java.net에 위치한 또 다른 이클립스 기반 프로젝트를 사용하려고 한다면, 앞서 설명한 프로젝트 의존성을 활용하는 것보다는 외부의 프로젝트를 JAR 파일로 압축해서 사용하라.

    플러그인의 설치


    이클립스에는 새로운 플러그인을 찾아 설치하기 위한 그래픽 유저 인터페이스가 있다. Help->Software Updates->Fild and install 메뉴 항목을 통해서 접근할 수 있다. 그러나, 아래 설명하는 방법과 같이 수작업으로 직접 설치하는 것이 더 편리하다.

    먼저 여러분이 설치하길 원하는 플러인을 다운로드 받는다. http://eclipse-plugins.2y.net/eclipse/index.jsp 사이트와 http://www.eclipseplugincentral.com/ 사이트에 있는 온라인 색인을 통해 좀 더 쉽게 찾을 수 있다.

    필요하다면 zip이나 tar형태로 압축된 플러그인의 압축을 푼다. "plugin.xml" 파일이 있는 디렉토리 찾아서 디렉토리를 Eclipse가 설치되어 있는 디렉토리(예를들어 C:\eclipse\eclipse-SDK-3.0.1-win32\eclipse\plugins.) 아래의 "plugins" 디렉토리로 복사한다. 이클립스를 다시 시작하면 플러그인을 사용할 수 있는 상태가 된다. (종종 플러그인은 사용자가 직접 사용을 하게 되는 경우에 새로운 뷰나 에디터, 퍼스펙티브를 제공한다.)

    만약 플러그인이 로드되었는지 의심스럽다면 Help->About Eclipse Platform을 선택하고 "Plug-in Details"를 선택해보면 된다.



    이렇게 하면 로드된 모든 플러그인을 볼 수 있다.



    요약


    이클립스가 무엇인지 그리고 오픈소스개발을 위하여 프로젝트를 어떻게 설정하는지 익혔기를 바란다. 2부에서는 java.net의 CVS 저장소와 함께 이클립스에 통합된 CVS를 사용하는 방법을 살펴본다.

    저자와 역자


    Martin Pllu: Edinburgh에 있는 Standard Life Assurance사의 메세징 & Java 기반 팀의 멤버이다. java.net에 호스트 되어있는 leafcutter and tracetest같은 오픈소스 어플리케이션의 개발자이기도 하다.


    역자 : 안영회, 최한수
    덧글 1개 | 엮인글 쓰기 이 포스트를.. 이 포스트 담기 -->
    Swing and SWT: A Tale of Two Java GUI Libraries | Eclipse 2005/05/13 16:17
    http://blog.naver.com/huskies/12813058

    Swing and SWT: A Tale of Two Java GUI Libraries
    By Mauro Marinilli

    Go to page: 1  2  Next  

    In this article, we will talk about Java J2SE graphical user interface (GUI) libraries. We will adopt a programmer's viewpoint in our discussion. We assume the reader is familiar with the basics of the Swing library and wants to explore the SWT technology.

    We will discuss two Java GUI libraries:

    • Swing—The reference GUI toolkit for J2SE.
    • SWT—This library has been developed by IBM as a part of the Eclipse platform.

    Eclipse is an open-source, IBM-sponsored, fully extensible IDE, built using Java and SWT. SWT originated as Eclipse's GUI library, but it can be used outside it as a an alternative GUI library to both Sun's AWT and Swing.

    In the following section, we will introduce the basics of SWT. We will assume the reader is familiar with Swing. Finally, we compare SWT and Swing.

    SWT

    SWT (Standard Widget Toolkit) is a graphics library and a widget toolkit integrated with the native window system (especially with Windows but Linux and Solaris are supported as well). Despite the tight integration with the native target platform, SWT is an OS-independent API. SWT can be seen as a thin wrapper over the native code GUI of the host operating system.

    At a higher level of abstraction, also a part of the Eclipse platform, lies JFace. This is a GUI library, implemented using SWT, that simplifies common GUI programming tasks. JFace is independent of the given window system, in both its API and implementation, and is designed to work with SWT, without hiding it. For brevity, we will discuss only SWT here.

    Introduction

    The design strategy of SWT was focused on building a simple, essential library that would produce GUI applications closely coupled to the native environment. SWT delegates to native widgets for common components (such as labels, lists, tables, and so on) as AWT does, while emulating in Java more sophisticated components (for example, toolbars are emulated when running on Motif) similarly to Swing's strategy.

    SWT has been designed to be as inexpensive as possible. This means (among the other things) that it is native-oriented. Anyway, it differs from AWT in a number of details. SWT provides different Java implementations for each platform, and each of these implementations calls natively (through the Java Native Interface, JNI) the underlying native implementation. The old AWT is different in that all platform-dependent details are hidden in C (native) code and the Java implementation is the same for all the platforms.

    Resources

    An important difference from normal Java programming is the way OS-dependent objects are managed in SWT. Swing emulates a large part of such objects (such as widgets, for instance) in Java, leaving the disposal job to the JRE garbage collector. This saves a lot of complexity for the programmer but this lack of control can lead to some unexpected issues, especially with cross-platform development.

    SWT designers chose a different approach, obliging the developer to explicitly dispose of OS-dependent objects in the application code. SWT has been designed with efficiency in mind, so handling explicitly OS resources becomes an occasion to promote efficient programming and not just a necessity. Resource disposal is needed to free the OS resources used by the SWT application. Such OS resources need to be explicitly de-allocated by invoking the dispose method.

    In practice, disposing of objects is a delicate business and it can lead to unpredictable results whenever another object tries to access an already disposed item.

    The Basic Structure of an SWT Program

    As already said, an SWT program relies upon the native platform resources (wrapped by the Display class, as we will see later on) both in terms of allocated resources (such as colors, images, and so on) and as regards the event mechanism. As regards event handling, in SWT there is only one thread that is allowed to handle native user interface events.

    We now see the basic structure of an SWT program. This will help us understand SWT's basic architecture.

    There are two basic classes used in any SWT application, the Display and Shell classes. Instances of the Display class are responsible for managing the connections between SWT and the underlying operating system, enforcing the SWT models (for colors or images, for example). The Shell class instead represents windows managed by the platform-dependent desktop manager.

    Typically, an SWT program will first create a local resources manager (an instance of the Display class) and attach all the needed widgets to one or more Shell objects. Listing 1 shows this typical mechanism.

    Listing 1: A snippet of code showing the use of the Display and Shell classes.

    00:     Display display = new Display();
    01:     Shell shell = new Shell(display);
    02:     //GUI code here
    03:     shell.open();
    04:     while (!shell.isDisposed()) {
    05:       if (!display.readAndDispatch())
    06:         display.sleep();
    07:     }
    08:     display.dispose();
    09:   }
    10: }
    

    To fully understand the code in Listing 1, one should understand the readAndDispatch method of the Display class. Such a method reads an event from the operating system's event queue, dispatching it appropriately. It returns true if there is additional work to do, or false if the caller can sleep until another event is placed on the event queue.

    The loop at lines 4-9 in Listing 1 is typical of SWT applications. It takes care of forwarding all underlying platform events to the SWT application until the shell is disposed and the program can exit the event loop.

    Basic Controls

    Some of the basic components (or controls, as they are called in SWT) are the following:

    • Button. This component is the well-known button component used in toolbars, forms, and so forth.
    • ComboBox. This widget is the well-known combo box component.
    • Label. This component represents a (non-selectable) object that displays a string or an image.
    • List. This widget represents a basic list component.
    • ProgressBar. It shows a progress indicator.
    • Sash. It is the Swing equivalent of a JSplitPane. It is a widget that can be dragged to resize two areas in a GUI.
    • Scale. This component implements an editable GUI item representing a range of continuous numeric values.
    • Slider. This component represents an editable object that stands for a range of discrete, numeric values.
    • Table. This component represents a basic table.
    • Text. This component represents a basic text area.
    • Tree. This component represents a basic tree widget.
    • StyledText. This component represents a text area with styled fonts and other advanced attributes.

    Go to page: 1  2  Next  

    덧글쓰기 | 엮인글 쓰기 이 포스트를.. 이 포스트 담기 -->
    A First Look at Eclipse Plug-In Programming | Eclipse 2005/05/13 16:13
    http://blog.naver.com/huskies/12812922

    A First Look at Eclipse Plug-In Programming
    By Koray Guclu

    Go to page: 1  2  3  4  5  Next  

    "First they ignore you, then they laugh at you, then they fight you, then you win."—Mahatma Gandhi (1869-1948)

    1. Introduction

    1.1. What is Eclipse?

    The Java platform is extensively used on server and enterprise applications. Java is even used on systems that require high performance. Despite its extensive use on server platforms, it has not been used too much on desktop applications. The main reason is the look & feel of the Java applications. Most end-users find Java look & feel differently then the one what they are accustomed to. After the introduction of Swing, there were many new things that a programmer can control and use.

    On the other hand, platform-dependent integration was still missing. It was still hard to use MSOffice tools with Swing.

    Eclipse solves the problems that exist in the current Swing library. The SWT library provides a platform-dependent look & feel. In addition to that, Eclipse provides a plug-in based framework that can be used as a base platform for desktop applications.

    1.1.2. Who is behind Eclipse?

    IBM has started to develop a project called Eclipse. IBM invested 40 K dollars before giving it away to the open source community. The first release of Eclipse V 1.0 wass announced in November 2001. Eclipse is supported by many other organizations such as Borland Software Corp., Merant Internation Ltd., Oracle, Rational Software Corp., Red Hat Inc., SuSe Inc., and TogetherSoft Corp.

    1.1.3. What makes Eclipse unique?

    Eclipse is a set of frameworks that brings Java applications to the desktop. In contrast to many other open source projects, Eclipse is supported by many big companies.

    SWT (The Standard Widget Toolkit) library delivers native widget functionality for the Eclipse platform in an operating system-independent manner. The SWT library can be used to provide native look and feel to the end-users. End-users don't know whether the application is a Java application or a native application.

    The Eclipse platform delivers plug-in–based architecture. Everything except a small bootstrap code is written as a plug-in in Eclipse. The Eclipse platform architecture includes all the GUI design patterns. For example, it provides plug-in versioning, a help system, and so forth. It can also be used as general purpose IDE architecture. Eclipse Java IDE is based on generic plug-in architecture, which makes it easy to support other languages as well.

    Through its predefined infrastructure, different vendor plug-ins can communicate with each other easily.

    1.2. Where to start?

    Eclipse has its own GUI library (SWT) that provides a native look and feel for Eclipse. Eclipse code is written in Java that calls the SWT library through JNI. Eclipse does not ship with a JVM. To use Eclipse, a JVM must exist on the target platform. Otherwise, you will get the following error message.

    Figure 1. Error message shown when there is no JVM installed.

    To develop under Java, it is better to download and install a JDK.

    Eclipse can be found on the Eclipse download Web site at no charge. I would suggest you download the latest release build (Build name: 2.1.2) of the "Eclipse SDK" from the main Eclipse download site.

    Eclipse workbench uses the native SWT library. Therefore, appropriate target platform download should be selected for the download. The SWT library supports the following platforms:

    Table 1. SWT Platforms
    Operating System Windowing Sub-system
    Windows 98/ME/2000/XP/CE Win32
    Linux Motif
    Linux GTK
    Solaris Motif
    MacOS Carbon
    QNX Photon
    AIX Motif
    HP-UX Motif

    After downloading and unzipping the Eclipse zip file it should be started by running the Eclipse executable file found under the top-level installation directory.

    Changing the workspace location
    You can specify different workspace locations by using eclipse.exe -data <location> as a command line parameter of the Eclipse executable.

    The default location of the workspace is the root installation directory of the Eclipse installation. If you want to run different instances of Eclipse for different projects or purposes, you can do the following:

    1. Create an Eclipse shortcut.
    2. Give a proper name to the shortcut.
    3. Right-click on the shortcut and open the Properties window.
    4. Set the "Start in:" parameter of the shortcut to a new location. Eclipse will use this location as the workspace.

    1.3. Projects under eclipse.org

    There are different projects developed under eclipse.org. The picture below shows these projects.

    Figure 2. The Eclipse.org project structure

    Eclipse project provides industry-standard, commercial-quality integrated tools. The Eclipse project consists of three sub projects. These are:

    • Platform (core—plug-in based architecture)
    • JDT (Java Development Tools)
    • PDE (Plug-in Development Environment)

    Eclipse JDT is very good tool at no cost. It provides much functionality, such as syntax highlight, code refactoring, debugger, team environment, and scrapbook.

    PDE provides the tools to write plug-ins. PDE makes it easy to write a plug-in within a plug-in environment. You can write a plug-in easily. PDE runs your plug-in within another Eclipse instance. It also allows you to select the plug-in to be included in your application.

    Eclipse tools project provides a central place for tool builder for the Eclipse platform.

    Eclipse technology project provides new channels for open source developers, researchers, academics, and educators to participate in the on-going evolution of Eclipse.

    "Eclipse officials said that the new organization will work and look a lot like the Apache Foundation and that members will have to commit to provide a commercial product that supports Eclipse within 12 months of joining."

    Go to page: 1  2  3  4  5  Next  

    Next article: SWT Programming with Eclipse

    덧글쓰기 | 엮인글 쓰기 이 포스트를.. 이 포스트 담기 -->
    SWT Programming with Eclipse | Eclipse 2005/05/13 16:10
    http://blog.naver.com/huskies/12812788

    SWT Programming with Eclipse
    By Koray Guclu

    Go to page: 1  2  3  4  5  6  Next  

    "The best way to predict the future is to invent it."—Alan Kay

    1. Why SWT?

    SWT is a cross platform GUI developed by IBM. Why has IBM created another GUI? Why have not they used existing Java GUI frameworks? To answer those questions, we need to go back to the early days of Java.

    Sun has created a cross platform GUI framework AWT (Abstract Windowing Toolkit). The AWT framework uses native widgets but it was suffering from a LCD problem. The LCD problem causes loss of major platform features. In other words, if platform A has widgets 1–40 and platform B has widgets 20–25, the cross-platform AWT framework only offers the intersection of these two sets.

    To solve this problem, Sun has created a new framework that uses emulated widgets instead of native widgets. This approach solved the LCD problem and provided a rich set of widgets but it has created other problems. For instance, Swing applications no longer look like native applications. Although they're the latest improvements in the JVM, Swing applications suffer performance problems that do not exist in their native counterparts. Moreover, Swing applications consume too much memory, which is not suitable for small devices such as PDAs and Mobile Phones.

    IBM has decided that neither of the approaches fulfill their requirements. Consequently, IBM has created a new GUI library, called SWT,which solves the problems seen with the AWT and the Swing frameworks. The SWT framework accesses native widgets through JNI. If a widget is not available on the host platform, SWT emulates the unavailable widget.

    2. Building Blocks of an SWT Application

    Display, Shell, and Widgets are basic building blocks of an SWT application. Displays are responsible from managing event loops and controlling communication between the UI thread and other threads. Shell is the window in an application managed by the OS window manager. Every SWT application requires at least one Display and one or more Shell instances.

    Figure 1. An SWT application from different perspectives.

    Figure 1 shows an SWT application from different perspectives. The first diagram is the simplified inheritance diagram of the UI objects. The second diagram is the containment structure of the UI objects. The third diagram is the created UI.

    If an application uses multiple threads, each thread uses its own instance of a Display object. You can get the current active instance of a Display object by using the static Display.getCurent() method.

    A Shell represents a window in a particular operating system. A shell can be maximized, normal, or minimized. There are two types of shells. The first one is the top-level shell that is created as a child, main window of the Display. The second one is a dialog shell that depends on the other shells.

    The type of a Shell depends on style bits passed to the Shell's constructor. The default value of a Shell is DialogShell. That is to say, if nothing is given to the parameter, it is by default a DialogShell. If a Display object is given to the parameter, it is a top-level shell.

    Some widget properties must be set at creation time. Those widget properties are called style bits. Style bits are defined as constants in SWT class, for example, Button button = new Button( shell, <styleBits> ). It is possible to use more then one style bit by using the OR operation |. For instance, to use a bordered push button, you need to use SWT.PUSH | SWT.BORDER as style bit parameters.

    3. Environment Set-Up

    Developing an SWT application is different from developing a Swing application. To begin with an SWT application development, you need add SWT libraries to your classpath and set necessary environment variables accordingly.

    The first library that you need is the swt.jar file that is under the ECLIPSE_HOME\eclipse\plugins\org.eclipse.swt.win32_2.1.0\ws\win32 directory. Depending on the version of the Eclipse that you are using, you might need to use a different directory. The swt.jar file must be added to your classpath to make this go to Project->Properies->JavaBuildPath->Libraries->Add Variable -> Eclipse Home ->Extend and select the swt.jar library under the director abovey and then click on OK.

    Afterwards, you will be able to compile an SWT application but, because of a runtime exception shown below, it won't be able to run because the swt.jar library uses native libraries. You need to set the java.library.path environment variable to use native libraries in Java.

    Console output
    java.lang.UnsatisfiedLinkError: no swt-win32-2133 in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1403)
    at java.lang.Runtime.loadLibrary0(Runtime.java:788)
    at java.lang.System.loadLibrary(System.java:832)
    ...
    at org.eclipse.swt.widgets.Display.<init>(Display.java:287)
    at Main.main(Main.java:25)
    Exception in thread "main"

    To set the java.library.path variable, go to Run-> Run...-> Java Applicaton-> New ->Arguments -> VM Arguments. Thereafter, if neccesary, modify the path below and paste it to the VM Arguments field.
    -Djava.library.path=c:\eclipse\plugins\org.eclipse.swt.win32_2.1.0\os\win32\x86

    Loading native libraries
    If you need to load any native library that your application uses, you can use the Runtime.getPlatform.loadLibrary("libraryname") method.

    Finishing these steps will enable you to run an SWT application within your eclipse environment.

    4. Your First SWT Application

    Creating a typical SWT application requires the following steps:

    • Create a Display
    • Create one or more Shells
    • Set a Layout manager of the Shell
    • Create widgets inside the Shells
    • Open the Shell window
    • Write an event dispatching loop
    • Dispose display

    You can use the following code template to quickly run the code snippets in this article. You can copy and paste the code to the area, as shown in Source 1.

    Source 1. SWT application template
    import org.eclipse.swt.layout.RowLayout;
    import org.eclipse.swt.widgets.Display;
    import org.eclipse.swt.widgets.Shell;
    
    public class SliderExample
    {
      public static void main(String args[])
      {
     Display display = new Display();
     Shell shell = new Shell(display);
     shell.setLayout( new RowLayout());
        // ------------------------
        // Your code comes to here.
        // ------------------------
        shell.pack();
     shell.open();
     while( !shell.isDisposed())
        {
          if(!display.readAndDispatch()) 
          display.sleep();
        }
     display.dispose();
      }
    }
    

    This example displays an empty window. You can add your widgets to the template above. Every SWT application requires a Display and one or more Shells. The Shell is a composite object; it can contain other composite objects. If the layout of the shell is not set, added widgets to the Shell won't be visible. The Shell window must be opened to be displayed. The event handling loop reads and dispatches GUI events. If there is no event handling loop, the application window cannot be shown, even if the Shell window is opened by the open() method. Afterwards, you should dispose of the Display, when the Shell is discarded.

    Importing required libraries
    You can use the Source->Organize Imports menu or Ctrl+Shift+O to import the required libraries automatically.

    Go to page: 1  2  3  4  5  6  Next  

    Previous article: A First Look at Eclipse Plug-In Programming
    Next article: Constructing SWT Layouts

    출처 : Tong - Developer님의 ▒ Java통

Designed by Tistory.