레이블이 inheritence인 게시물을 표시합니다. 모든 게시물 표시
레이블이 inheritence인 게시물을 표시합니다. 모든 게시물 표시

2013년 8월 8일 목요일

[오라클자바커뮤니티,자바교육]자바의 자료형

JAVA자료형에 대해 계속 보도록 하겠습니다. 


오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷 실무전문 강의)  



1. 정수 자료형 (byte,short,int,long)

자바에서 제공하는 정수 자료형은 byte, short, int, long 4가지가 있습니다.(1,2,4,8 바이트 순)

C언어의 unsigned는 지원하지 않습니다.

short, byte에 연산을 하면 무조건 int형이 됩니다. 아래의 예를 보죠...

short a=0, b=0;

short c = a + b;

만약 위의 코드 부분이 컴파일 되다면 다음과 같은 오류가 날것 입니다.

---------- javac ----------
test.java:10: possible loss of precision
found : int
required: short
short c = a + b;
^
1 error


int형이 아닌 long형으로 데이터를 다루기 위해선 숫자 끝에 소문자 l이나 대문자 L을 표시한다.

Int : 12 (10진수), 012 (8진수), 0x12 (16진수)

Long : 12L, 12l



2. 부동소수 자료형 (float ,double)

자바에서 제공하는 부동소수 자료형은 float와 double이 있습니다.
부동소수 자료형 뒤에 아무것도 붙이지 않거나 ‘d’ 또는 ‘D’ 가 붙으면 기본적으로 double 형이 되며 ‘f’, ‘F’를 붙이면 float 자료형이 됩니다.

유효 10진 자리수
float : 6자리, double : 15자리

2진수로 표현하므로 표현 오차 발생하며 보다 정확한 표현을 하려면 BigDecimal 이용하세요~

리터럴

float --> 1e1f, 2.F, .3f, 6.02E+23f, 1.4039846e-45f ~ 3.40282347e+38f
double --> 1e1, 2.D, .3, 6.02E+23d, 4.94065645841246544e-324 ~ 1.79769313486231570e+308



[예제]

// FloatPointTest.java

class FloatingPointTest
{
public static void main( String[] args )
{
System.out.println( 1.2345678901234567890123456789 ); // 1.2345678901234567
System.out.println( 2e3 ); // 2000.0
System.out.println( 0.1 + 1.6 ); // 1.7000000000000002
System.out.println( 3.0 / 0.0 ); // Infinity
System.out.println( 0.0 / 0.0 ); // NaN
}
}



3. 진리 자료형 (boolean)

boolean Literal : true, false

boolean 형은 다른 데이터형과 연산이 불가하며 boolean형은 boolean 형과 연산이 가능 합니다.

[예제]

public class BooleanTest {
public static void main(String[] args) {
boolean b1 = true; boolean b2 = !b1;
System.out.println("b1 : " + b1);
System.out.println("!b1 : " + b2);
System.out.println(b1 & b2);
System.out.println(b1 | b2);
System.out.println(b1 == b2);
System.out.println(" 6 < 7 : " + (6 < 7));
}
}

[결과]

b1 : true
!b1 : false
false
true
false
6 < 7 : true

4. 문자 자료형 (char)

자바는 유니코드를 지원하는데 JDK1.4부터는 Unicode 2.0까지 지원합니다.

한 문자를 표현할 때는 '와 ' 사이에 단 한 글자만이 올 수 있습니다.

자바에서 문자를 표현하는 방법은 두가지가 있는데 첫번째 방법은 있는 그대로 쓰는 것이며 두번째 방법은 유니코드로 표현하는 방법이다. 예)char c = ‘A’, char c = ‘\u0041’

[예]

class CharTest {
public static void main(String[] args) {
char c1 = 'A'; char c2 = '\u0041';
char c3 = '가'; char c4 = '\uac00';
System.out.println("c1:"+c1+",c2:"+c2);
System.out.println(c1 == c2);
System.out.println("c3:"+c3+",c4:"+c4);
System.out.println(c3 == c4);
}
}

[결과]

c1:A,c2:A
true
c3:가,c4:가
true

[오라클자바커뮤니티]java awt Window,Frame,Font,Color

-------------------------

java.awt.Window

-------------------------


오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷 실무전문 강의)  






경계바, 타이틀바, 메뉴바가 없는 컴포넌트, 거의 직접 사용되지 않습니다.

그다지 유용하지 않으며 확장하여 사용하거나, ToolTip, PopUp메뉴와 같은 특수한 용도로 사용 합니다.

Window및 그 하위컴포넌트는 다른 컴포넌트에 포함되지않는 최상위 Component

Window및 Dialog 컴포넌트는 부모 컴포넌트로 Frame 컴포넌트를 지정해야만 그 객체를 생성할 수 있습니다.

Window객체를 사용해서 팝업 메뉴를 구현할 수 있으며 창의 기본 배치 관리자는 BorderLayout

WindowOpened나 WindowClosed와 같은 창 이벤트를 생성할 수 있습니다.



생성자 : Window(Frame owner), Window(Window owner), Window(Window owner, GraphicConfiguration gc)

메소드

addNotify() : Window의 피어(peer)를 작성.

addWindowListener(WindowListener) : 지정된 Window 수신기(listener)를 추가하여 Window으로부터 Window 이벤트를 수신.

dispose() :Window에 사용한 자원을 해제 할 때 사용

getFocusOwner() : Window가 활성화된 경우에만 Focus가 있는 창의 하위 컴포넌트를 Return

getOwner() : Window의 Owner를 Return

getOwnedWindows() : 현재 Window를 소유하고 있는 Window 배열을 Return

isShowing() : Windwo가 화면에 나타나 있는지 여부를 점검 합니다.

pack() : Window의 하위 컴포넌트를 환경설정된 크기로 배치 합니다. (최적크기)

processEvent(AWTEvent) : window에 대한 이벤트를 처리 합니다.

processWindowEvent(WindowEvent) : Window에서 발생하는 Window 이벤트를 등록된 WindowListener 객체로 보내 처리 합니다.

removeWindowListener(WindowListener) : Window Event Listener를 제거

show() : Window를 표시하고 앞으로 가져 옵니다.

toBack() : Window를 뒤로 보냅니다.

toFront() : Window를 앞으로 가져 옵니다.





------------------------

java.awt.Frame

--------------------

메소드

Frame() : 초기에는 보이지 않는 Frame의 새로운 인스턴스를 구성

Frame(String) : 지정된 제목으로 초기에는 보이지 않는 새로운 Frame 객체를 구성

getTitle() : 프레임의 제목을 가져옴

setTitle(String) : 프레임의 제목을 Set

isResizable() : 프레임 크기를 재조정할 수 있는지를 표시

getIconImage() : 프레임의 아이콘 이미지를 가져 옵니다.

setIconImage(Image) : 프레임이 아이콘으로 될 때 이미지가 표시되도록 설정

getMenuBar() : 프레임의 메뉴 막대를 가져 옵니다.

setMenuBar(MenuBar) : 지정된 메뉴 막대로 프레임의 Menu component를 설정 합니다.


remove(MenuComponent) : 프레임에서 지정된 Menu Component를 제거





-----------------------

java.awt.Color

-----------------------

java.awt.Object --> java.awt.Color

Paint Interface 구현한 글래스, RGB형식을 사용하여 색을 캡슐화 --> (0,0,0) 검정, (255,255,255) 흰색

색의비교 equals(), Color객체의 getRGB()를 이용


생성자

Color(float, float, float) : 지정된 빨강, 초록, 파랑 값을 사용하여 색상을 만들며, 각 값의 범위는 0.0-1.0

Color(float, float, float, float) : 지정된 빨강, 초록, 파랑 값을 사용하여 색상을 만들며, 불투명도 추가(0.0~1.0)

Color(int) : 지정된 RGB 값으로 색을 만든다. 빨강 컴포넌트는 16-23 비트 인수, 초록 컴포넌트는 8-15 비트 인수, 파랑 컴포넌트는 0-7 비트 인수.

Color(int, int) : ,RGB색상, 불투명도를 정수(0~255)로 나타냄

Color(int, int, int) : 지정된 빨강, 초록, 파랑 컴포넌트로 색을 만듬. (0~255)

Color(int, int, int, int) : 지정된 빨강, 초록, 파랑 컴포넌트로 색을 만듬, 마지막 인자는 불투명도를 나타내는 값(0~255)

Color(ColorSpace, float[], float) : 지정된 ColorSpace, color components float배열,불투명도를 이용해 색을 만듬.



메소드

brighter() : 색을 더 밝게

darker() : 색을 더 어둡게

equals(Object) : 다른 객체가 이 색과 같은지를 결정. 색의 비교시 사용

getBlue() : 색의 파랑 컴포넌트를 가져옴. (0~255)

getColor(String) : 시스템 특성에서 색을 찾는다. String은 시스템 특성

getColor(String, Color) : 시스템 특성에서 색을 찻는다. 지정된 특성이 없거나 정수로 분석될 수 없으면, 두 번째 인수가 지정한 색상이 대신 리턴 됩니다.

getColor(String, int) : 시스템 특성에서 색을 찾습니다. 지정된 특성이 없거나 정수로 분석될 수 없으면, 정수값(int)이 대신 사용되고 색으로 변환

getGreen() : 색의 초록 컴포넌트를 가져온다. (0~255)

getRed() : 색의 빨강 컴포넌트를 가져온다. (0~255)

getRGB() : 기본 RGB ColorModel에 있는 색을 표시하는 RGB 값을 가져옵니다. 리턴되는 정수의 24-31 비트는 0xff를, 16-23 비트는 빨강 값을, 8-15 비트는 초록 값을, 0-7 비트는 파랑 값을 나타 냅니다.




--------------------------------

java.awt.Font - 사용방법

----------------------------

버튼을 생성한 후에 버튼의 라벨을 TimesRoman 형 폰트에 진한 글씨로 크기를 20으로 하고자 할 경우 다음과 같이 설정할 수 있습니다.

Button btn = new Button("확인"); Font font = new Font("TimesRoman", Font.BOLD, 20); btn.setFont(font);

그래픽 컨텍스트에 그려지는?글자에 폰트를 지정하는 방법은 다음과 같습니다.

public void paint(Graphics g) {

Font f = new Font("TimesRoman", Font.BOLD, 20);

g.setFont(f);

g.drawString("Hello, World!", 10, 10);

}


자바 폰트 이름 X 윈도우 폰트 이름 윈도우즈 폰트 이름

Helvetica adobe-hevetica Arial

TimesRoman adobe-times Times New Roman

Courier adobe-courier Courier New

Dialog b&h-lucida MS Sans Serif

DialogInput b&h-lucidatypewriter MS Sans Serif

ZapfDingbats itc-zapfdingbats WingDings

default misc-fixed Arial



[예제] // 폰트 패밀리, 논리폰트명 출력

import java.awt.*;
class FontSample {
static Font font1 = new Font("TimesRoman", Font.ITALIC, 45);
static Font font2 = new Font("Helvetica", Font.BOLD, 12);
static Font font3 = new Font("Verdana", Font.PLAIN, 16);
public static void main(String args[]) {
System.out.println("family name of font1 : " + font1.getFamily());
System.out.println("family name of font2 : " + font2.getFamily());
System.out.println("family name of font3 : " + font3.getFamily());
System.out.println("name of font1 : " + font1.getName());
System.out.println("name of font2 : " + font2.getName());
System.out.println("name of font3 : " + font3.getName());
System.out.println("style of font1 : " + font1.getStyle());
System.out.println("style of font2 : " + font2.getStyle());
System.out.println("style of font3 : " + font3.getStyle());
System.out.println("size of font1 : " + font1.getSize());
System.out.println("size of font2 : " + font2.getSize());
System.out.println("size of font3 : " + font3.getSize());
} }



[예제] // 논리 Font명 및 시스템속성

import java.awt.*;
import java.util.*;
public class SysInfo {
public static void main(String[] args) {
Toolkit thekit = Toolkit.getDefaultToolkit();
System.out.println("\n Screen Resolution : " + thekit.getScreenResolution() + "dots per inch");
Dimension screenDim = thekit.getScreenSize();
System.out.println("Screen Size : " + screenDim.width + " by "+screenDim.height + " pixels");
GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontnames = e.getAvailableFontFamilyNames();
System.out.println("\n----- fonts available on this flatform ----");
for(int i=0; i<fontnames.length; i++) { System.out.println(fontnames[i]); }
//System Properties
System.out.println("---- System Properties...... ----");
Properties p = System.getProperties();
p.list(System.out);
}
}



[예제] // CharaterIterator/StringIterator

import java.text.*;

class CharacterIteratorSample
{ public static void main(String[] args) {
//begin index:1, end index=4-1, current:1
CharacterIterator iter= new StringCharacterIterator("abcde", 1, 4, 1);
System.out.println("CharacterIterator iter --> "+iter);
iterateBackward( iter );
}

public static void iterateBackward(CharacterIterator iter) {
for (char ch = iter.last(); ch != CharacterIterator.DONE; ch = iter.previous())
System.out.print(ch);
}
}

[오라클교육,자바교육,오라클자바커뮤니티]JAVA AWT 배치관리자(Layout Manager)

-----------------------------
배치관리자(Layout Manager)
-----------------------------

오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷 실무전문 강의)  



Component가 컨테이너에 배열되는 방식을 결정 합니다.
모든 컨테이너는 기본 Layout Manager를 가집니다.
Container는 다른 Component를 포함할 수 있는 최소의 클래스이고 java.awt.container 클래스를 상속해야 합니다.
Container를 상속하지 않은 일반 Component에는 Layout Manager가 등록될 수 없습니다.
Frame, Window, Panel등은 Layout Manager를 설정할 수 있으며 이렇게 설정된 Layout Manager는 화면의 크기가 바뀌거나, Component가 추가 되거나 제거 되었을 경우에 호출 됩니다.(이경우 즉시 다시 배치하지 않으며 Layout을 다시 그릴 필요가 있다는것을 표시한 후 validate함수가 호출되거나 화면이 다시 그려지는 경우에 다시 배치 작업을 수행 합니다. 따라서 Layout Manager를 설치후 즉시 효과를 볼려면 validate를 호출해야 합니다. Invalidate 함수는 특정 Component가 화면에 다시 배치해야 된다고 표시하는 것 입니다.
Layout Manager를 이용하는 경우에 수동으로 Component를 배치하는것이 소용 없습니다. 화면에 표시 될때 Layout Manager가 다시 위치, 크기등을 결정하기 때문 입니다. 수동으로 Layout을 설정하는 경우엔 위치, 크기등을 정해 주어야 하며 그렇지 않은 경우엔 초기 위치, 쿠기등이 정해지지 않으며 보통 화면에 나타나지 않습니다.
Layout Manager를 이용할 경우 크기지정이 유효한 경우는 Window, Frame등과 같은 최상위 Container 입니다.

수동으로 Component 배치하기
주로 소량의 정보를 보이거나 간단한 사용자 입력을 받는 Container에 사용 됩니다.
컨테이너에 설정해야 하는것들…
- 컨테이너의 크기를 고정 시킵니다.(Frame의 경우 setResizable)
- 컨테이너의 Layout Manager를 null로 한다. setLatout을 이용하며 Frame, Panel과 같은 기본 Layout Manager를 가지기 때문에 반드시 이과정을 수행해야 합니다.
- 컨테이너의 크기를 지정 합니다. (자식 컴포넌트의 크기, 위치를 수동으로 주는 경우 상의 컨테이너의 크기도 수동으로 지정해야 합니다. setSize, setBounds 등이용)

[예제]
import java.awt.*;
public class LayoutNull {
public static void main(String[] args) {
Button btn1, btn2, btn3;
Frame myWindow = new Frame("Null Layout");
myWindow.setResizable(false);
myWindow.setLayout(null);
myWindow.setSize(300, 300);
btn1 = new Button("버튼1"); btn1.setBounds(40,50,50,20);
btn2 = new Button("버튼2"); btn2.setBounds(100,50,50,20);
btn3 = new Button("버튼3"); btn3.setBounds(160,50,50,20);
myWindow.add(btn1); myWindow.add(btn2); myWindow.add(btn3);
myWindow.setVisible(true);
}
}

[결과]


인터페이스 java.awt.LayoutManager
컨테이너를 배치하는 클래스의 인터페이스를 정의 합니다.
addLayoutComponent(String, Component) : 지정된 이름을 가진 지정된 컴포넌트를 배치에 추가
layoutContainer(Container) : 지정된 패널에 컨테이너를 배치
minimumLayoutSize(Container) : 지정된 상위 컨테이너에서 컴포넌트를 받은 지정된 패널의 최소 크기를 계산
preferredLayoutSize(Container) : 지정된 상위 컨테이너에서 컴포넌트를 받은 지정된 패널의 환경설정된 크기를 계산
removeLayoutComponent(Component) : 배치에서 지정된 컴포넌트를 제거
LayoutManager2를 구현하는 java.awt의 클래스 - BorderLayout, CardLayout, GridBagLayout, GridLayout, FlowLayout

인터페이스 java.awt.LayoutManager2
LayoutManager2 인터페이스는 LayoutManager 인터페이스를 확장하여 배치에 컴포넌트를 추가하는 방식 및 위치를 지정하는 제약 조건 객체에 따라 배치를 명시적으로 처리 합니다.
addLayoutComponent(Component, Object) : 지정된 제약 조건 객체를 사용하여 지정된 컴포넌트를 배치에 추가 합니다.
getLayoutAlignmentX(Container) : x 축 정렬을 리턴 합니다.
getLayoutAlignmentY(Container) : y 축 정렬을 리턴 합니다.
invalidateLayout(Container) : 배치 관리 프로그램이 버려야 할 정보를 캐시에 넣은 경우 그 사실을 나타내고 배치를 무효화 합니다.
maximumLayoutSize(Container) : 컴포넌트의 최대 크기를 리턴 합니다.
LayoutManager2를 구현하는 java.awt의 클래스 - BorderLayout, CardLayout, GridBagLayout

FlowLayout
컴포넌트를 컨테이너에 연속된 행으로 위치 시킨다. 각 행에 많은 컴포넌트를 채우고 행이 다차면 다음으로 넘어간다. 주로 버튼등을 배열하기 위한 것
컴포넘트의 기본 위치는 행의 한가운데 입니다.
다음과 같은 행의 기본위치를 지정할수 있는 상수가 있습니다.
FlowLayout.LEFT, FlowLayout.RIGHT, FlowLayout.CENTER,
[예제]
import java.awt.*;
class FlowLayoutTest extends Frame {
public FlowLayoutTest() {
setLayout(new FlowLayout());
add(new Button("Button1"));
add(new Button("Button2"));
add(new MyButton("새로운 버튼"));
Panel p = new Panel();
p.add(new Button("Panel Button1"));
p.add(new Button("Panel Button2"));
add(p);
}
public static void main(String[] args) {
Frame f1 = new FlowLayoutTest();
f1.setTitle("Flow Layout Test : default");
f1.setBounds(0, 0, 200, 300);
f1.setVisible(true);
Frame f2 = new FlowLayoutTest();
//((FlowLayout)f2.getLayout()).setAlignment(FlowLayout.LEFT);
FlowLayout flow = new FlowLayout(FlowLayout.LEFT);
flow.setVgap(50);
f2.setLayout(flow);
f2.setTitle("Flow Layout Test : left");
f2.setBounds(200, 0, 200, 300);
f2.setVisible(true);
}
}
class MyButton extends Button {
public MyButton(String text) {
super(text);
}
public Dimension getPreferredSize() {
return new Dimension(super.getPreferredSize().width+30, super.getPreferredSize().height+30);
}
}

GridLayout
각 격자끼리의 width, height는 동일 합니다.
GridLay() : 행이 하나인 GridLayout을 만듭니다.
GridLayout(int row, int col) : 주어진 행과 열의 GridLayout을 만듭니다.
GridLayout(int row, int col, int hgap, int vgap)

[예제]
import java.awt.*;
class GridLayoutTest extends Frame {
public GridLayoutTest(String t, LayoutManager m, int x, int y) {
setTitle("GridLAyout Test " + t);
setLayout(m);
add(new Button("Button1"));
add(new Button("Button2"));
add(new Button("Button3"));
add(new Button("Button4"));
add(new Button("Button5"));
add(new Button("Button6"));
add(new Button("Button7"));
setBounds(x, y, 300, 300);
setVisible(true);
}
public static void main(String[] args) {
new GridLayoutTest("디폴트", new GridLayout(), 0, 0);
new GridLayoutTest("2, 0", new GridLayout(2, 0), 300, 0);
new GridLayoutTest("0, 2", new GridLayout(0, 2), 0, 300);
new GridLayoutTest("3, 3", new GridLayout(3, 3), 300, 300);
}
}

GridBagLayout
Layout Manager중에서 가장 복잡하며, 보통 하나의 GridBagLayout을 사용하여 모든 종류의 폼을 구성할 수 있습니다.
융통성있는 배치 관리 프로그램으로 동일 크기의 컴포넌트를 요구하지 않으면서 컴포넌트를 수직 및 수평으로 정렬 합니다.
각 컴포넌트가 하나 이상의 셀을 차지하는 표시 영역이라 부르는 셀의 사각형 격자를 동적으로 유지 관리 합니다.
GridBagLayout으로 관리하는 각 컴포넌트는 표시 영역에서 컴포넌트 배치 방식을 지정하는 GridBagConstraints의 인스턴와 관련 됩니다
GridBagLayout을 효율적으로 사용하려면 해당 컴포넌트와 관련된 GridBagConstraints 객체를 하나 이상 조정해야 합니다. 그렇게 함으로서 컴포넌트를 원하는 크기와 위치로 배치합니다.
실제 GridBagLayout을 사용하는것 보다 여러 개의 컨테이너와 Layout Manager를 계층적으로 사용하는것이 훨씬 효율적 입니다.
GridBagConstraints
- gridx, gridy : 해당 컴포넌트가 들어가게될 격자의 x번째, y번째 값, 가장 왼쪽 셀의 주소는 gridx=0, gridy=0 입니다.
- gridwidth, gridheight : 해당 열에 존재할수 있는 최대 컴포넌트의 개수, int값 사용, GridBagConstraints.RELATIVE는 컴포넌트들이 이어져서 들어갈수 있게 해주며,GridBagConstraints.REMAINDER는 마지막 자리에 위치해서 더 이상 컴포넌트가 들어갈수 없게 합니다.
- fill : 컴포넌트를 채울때 특정 방향으로 컴포넌트를 늘여 격자를 채울수 있게 합니다. GridBagConstraints.BOTH, GridBagConstraints.HORIZONTAL, GridBagConstraints.VERTICAL등이 있다.
- ipadx, ipady : 컴포넌트가 가지는 내부적 간격, int값 사용 합니다.
- insets : 컴포넌트와 격자와의 외부적인 간격, java.awt.inset 객체가 사용 됩니다.
- anchor : 격자내에서 컴포넌트가 위치하게 되는 격자내의 절대적인 위치, GridBagConstraints.CENTER(기본값), GridBagConstraints.NORTH, GridBagConstraints.NORTHEAST, GridBagConstraints.EAST, GridBagConstraints.SOUTHEAST, GridBagConstraints.SOUTH, GridBagConstraints.SOUTHWEST, GridBagConstraints.NORTHWEST등이 있습니다.
- weightx, weighty : 컴포넌트가 차지할수 있는 가로와 세로의 영역비율, double 값이 사용 됩니다.

[예제]
import java.awt.*;
public class GridBagLayoutTest extends Frame{
public GridBagLayoutTest(String t) {
super(t);
GridBagLayout gbag = new GridBagLayout();
GridBagConstraints con = new GridBagConstraints();
setLayout(gbag);
con.fill=GridBagConstraints.BOTH;
add(new Button("버튼1"), con);
add(new Button("버튼2"), con);
con.gridwidth = GridBagConstraints.REMAINDER;
add(new Button("버튼3"), con);
add(new Button("버튼4"), con);

con.gridwidth = GridBagConstraints.RELATIVE;
add(new Button("버튼5"), con);
con.gridwidth = GridBagConstraints.REMAINDER;
add(new Button("버튼6"), con);
con.gridwidth = 1;
con.gridheight = 2;
add(new Button("버튼7"), con);
con.gridwidth = GridBagConstraints.REMAINDER;
con.gridheight = 1;
add(new Button("버튼8"), con);
add(new Button("버튼9"), con);
}
public static void main(String[] args) {
Frame f = new GridBagLayoutTest("GridBagLayout");
f.setSize(300, 200);
f.setVisible(true);
}
}

CardLayout
여러화면을 겹쳐 두었다가 특정한 화면만 보이도록 할 경우 사용 합니다.
여러 장의 카드가 있으나 보이는 카드는 하나만 있다는 개념에서 나온 이름 입니다
first(), last(), next(), previous() 등의 도구를 사용하여 카드 간에 순차적으로 이동할 수도 있습니다.
CardLayout() : 간격 크기가 제로(0)인 새로운 카드를 작성 합니다.
CardLayout(int, int) : 지정된 수평 간격 및 수직 간격으로 새로운 카드 배치를 작성 합니다.

[예제] //닫기 기능 추가
import java.awt.*;
import java.awt.event.*;
public class CardLayoutTest1 extends Frame {
public static void main(String[] args) {
Frame f = new Frame("CardLayoutTest");

final Panel tabs = new Panel();

tabs.add(new Button("<><"));>
tabs.add(new Button("<"));
tabs.add(new Button("Options"));
tabs.add(new Button("Settings"));
tabs.add(new Button("Preferences"));
tabs.add(new Button(">"));
tabs.add(new Button(">>"));
f.add(tabs, "North");

final CardLayout layout = new CardLayout();
final Panel cards = new Panel(layout);
cards.add(new CardPanel("Options"), "Options");
cards.add(new CardPanel("Settings"), "Settings");
cards.add(new CardPanel("Preferences"), "Preferences");
f.add(cards, "Center");


ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent ev) {
String cmd = ev.getActionCommand();
if (cmd.equals("<><")) layout.first(cards);
else if (cmd.equals("<")) layout.previous(cards);>
else if (cmd.equals(">")) layout.next(cards);
else if (cmd.equals(">>")) layout.last(cards);
else layout.show(cards, cmd);
}
};

for(int i=0; i
((Button)tabs.getComponent(i)).addActionListener(al);
}
f.setSize(400, 300);
f.setVisible(true);
f.addWindowListener(new WindowListenerProcessing() );
}
}

class CardPanel extends Panel {
CardPanel(String name) {
setLayout(new BorderLayout());
add(new Label("CardPanel : " + name, Label.CENTER),"Center");
Panel p = new Panel();
add(p, "South");
Button btn = new Button("Close");
ActionListener a1 = new ActionListener() {
public void actionPerformed(ActionEvent ev) {
String cmd = ev.getActionCommand();
if (cmd.equals("Close")) {
System.exit(0);
}
}
};
btn.addActionListener(a1);
p.add(btn);
}
}
class WindowListenerProcessing extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}



오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터, iPhone 하이브리드 앱 개발 실무과정(평일야간) 개강확정

iPhone 하이브리드 앱 개발 실무과정

오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷 실무전문 강의)  

강좌명iPhone 하이브리드 앱 개발 실무과정(평일야간)
교재본원 자체교재 무료지원
강좌 일정08월21일(수) ~ 09월09일(월)((평일야간) 19:00~22:00, 14일) 총 42시간
강의 장소[B강의장]구로디지털단지역2번 출구-> 미니스톱끼고 우회전 -> 100m 직진 후 골목길 끝에서 이마트방향 우회전 -> 50m 직진 후 우체국 옆골목으로 길건너서 직진 -> 150미터 직진 후 JnK 타워에서 우회전 -> 50미터 직진 후 우측에 코오롱빌란트2차 803호 (구로구 구로3동 222-8 코오롱디지털타워 빌란트2차 803호)
[약도보기]
수강절차- 강좌내용 확인
- 전화 또는 홈페이지(www.onjprogramming.co.kr)를 통한 수강지원 및 수강료 결제(무통장입금, 온라인 카드결제)
- 고용보험 가입자(재직자)인 경우 고용보험환급 관련 서류 제출
- 수강전 : 커리큘럼 및 장소에 대해 다시 한번 공지
- 교육 전 설문 작성(간단한 개발 경력, 수강 목적, 강좌진행방식 등)
- 강좌 수강
- 수강후 : 교육 후 설문 작성
수강료580,000원
- 맥북무료지원
고용보험 환급(50~80% 환급)
[고용주환급]대기업:17만원 전후,중소기업:216,968원
[개인수강지원(개인환급)]정규직 464,000원 ,비정규직:전액환급

재직자 내일배움카드 : 정부지원금 80% 자기부담금 20%
(구 능력개발카드 명칭이 내일배움카드로 변경 / 연간 총한도 200만원)

* 휴강 :법정공휴일
수강료
입금안내
- 온/오프라인 카드결제, 계좌이체(수강안내->입금안내 참조)
문의사항02-851-4790 번으로 연락 부탁 드립니다.
교육개요본강좌는 아이폰과 아이팟 터치용 앱 개발을 위한 실용적인 경험을 제공하며. 쉽게 따라 해 볼 수 있도록 구성된 여러 샘플 예제를 통해서 Xcode 도구 사용법, 오브젝티브-C, 코어 프레임워크 등을 배우게 된다. 자신도 모르는 사이에 앱 개발에 필요한 기술은 물론이고 아이튠즈 앱스토어에 앱을 제출하는 과정도 알게 된다. 아이폰 프로그래밍에 첫 발을 내딛는 입문자 혹은 랭귀지 개발자에게 적합한 교육이다.

Xcode와 인터페이스 빌더 사용법, 오브젝티브-C를 이용한 모델-뷰-컨트롤러 구조, 데이터 입력 인터페이스 구현 및 입력 데이터 핸들링, 다양한 예제를 빌드를 통해 일반적으로 발생하는 문제 해결법, 앱스토어와 임시 배포에 필요한 요구 사항, 아이폰 가속도계, 근접 센서, 아이폰의 설정 앱 핸들링,이후 아이폰에서의 SQLite 활용, SQLite 관리 도구 활용, 실전에서 활용 가능한 최적화 기법 등의 내용을 배우게 됩니다.
교육목표- MAC 사용방법 실습
- Objective-C 프로그램 언어 이해
- Xcode와 인터페이스 빌더 사용법
- 오브젝티브-C를 이용한 모델-뷰-컨트롤러 구조 이해
- 데이터 입력 인터페이스 구현 및 입력 이헤
- 데이터 핸들링 이해
- 앱스토어와 임시 배포에 필요한 요구 사항
- UIKit프레임웍 이해
- 프로토콜, 델리게이트의 이해
- NSXMLParser
- 웹서버와 GET, POST 방식의 통신
- 임베디드 기기를 위한 SQLite 최적화
- SQLite 활용, SQLite 관리 도구 활용 이해
- SQLite 실전에서 활용 가능한 최적화 기법 이해
- 하이브리드앱 개발
교육대상-Objective-C 활용분야에 관심이 있는 자
-Cocoa / Xcode / iPhone 기반 애플리케이션/스마트폰 개발자
-SQLite 개발자
-SDK APP 개발자 
선수학습- c, c++
-프로그래밍 초보자
 



아이폰 개발 준비- MAC에 대한 개요와 이해
- MAC 사용방법 실습
- 개발자 라이센스 등록 절차 및 인증서 등록
- 앱의 다양한 배포방법(adHoc, Appstore, OTA)
objective-c- objective-c의 개요
- 콘솔창에서 클래스 만들고 gcc로 컴파일하기
- iPhone에 대한 개요과 구조 설명, Xcode 사용방법
- 메모리 관리(수동메모리관리)
- Foundation 프레임웍 개요
- UIKit프레임웍의 개요
- 세터와 게터 만들기
- 프로퍼티에 대한 이해, 점연산자
- 프로퍼티 속성
- 메시지 전달 방식에 대한 이해
- 프로토콜, 델리게이트의 이해 및 실습
iPhone SDK- Xcode에서 프로젝트 설정
- NSLog 및 출력 서식 사용하기
- 인터페이스 빌더, IBOutlet, IBAction에 대해 이해하기
- Immutable, Mutable 클래스의 차이
- MVC, Delegate, SingleTon, Target Action 패턴 이해
- 아이폰의 샌드박스구조에 대한 이해 및 파일처리
- UIButton, UILabel, UIImmageView 실습
- UISwitch, Webkit, UISegmetedControl 실습
- UITextField, UITextView, UISlider 실습
- main 구조파헤치기
- UIApplication 라이프 사이클 이해하기
- UIViewController , UIView 라이프 사이클 이해하기
- UIAlertView, UIActionSheet 실습
- UIPickerView 커스터마이징
- TableView 커스터마이징
- TableView Cell 커스터마이징
- UIKit Frameowork 와 Interface builder의 개연성 이해하기
- NSXMLParser
- 웹서버와 GET, POST 방식의 통신 구현
- Navigation Template 구현하기
- NSConnection을 이용한 ASynchronous 통신
SQLite3- Sqlite3 사용실습
- Sqlite3 사용실습
실무 하이브리드앱 개발- 하이브리드앱 개발
- 하이브리드앱 개발
- 하이브리드앱 개발
 

[오라클자바,자바교육,ORACLEJAVA]AWT 프로그래밍

이번 강좌 부터는 AWT의 기본적인 사항을 확인하고 AWT와 관련된 클래스에 대해 알아 보도록 하겠습니다.


오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷 실무전문 강의)  



자바에서 윈도우를 띄우는 것은 프레임을 띄우는 것과 유사한데 이번에는 그것에 대해 알아 보겠습니다.

프레임이용방법 -상속

import java.awt.*;
public class AwtTest1 extends Frame {
Button btn;
public AwtTest1() {
btn = new Button("버튼");
}
public void display() {
add(btn);
setSize(100,100);
setVisible(true);
}
public static void main(String args[]) {
AwtTest1 f = new AwtTest1();
f.display();
}
}
[결과]
p>

프레임이용방법 -멤버변수로 선언하여 사용
import java.awt.*;
public class 1 {
Button btn;
Frame f;
public AwtTest2() {
btn = new Button("버튼");
f = new Frame();
}
public void display() {
f.add(btn); f.setSize(100,100); f.setVisible(true);
}
public static void main(String args[]) {
AwtTest2 myFrame = new AwtTest2();
myFrame.display();
}
}
[결과]


위의 두프로그램은 같은 결과를 나타내지만 Frame을 이용하는 형태가 다르다. 하나는 직접 상속을 했고 하나는 그렇지 않다. 특별히 상속할 것이 없으면 Frame을 상속하면 되겠지만 이미 중요한 다른 클래스를 상속했다면 자바는 다중 상속을 지원하지 않으므로(상속은 하나만 허용) 두번째 방법을 이용한다.

예제( AwtTest .java) – 각종 Component
import java.awt.*;
public class AwtTest extends Frame {
Button btn; Label lbl ; TextArea ta; TextField tf; Checkbox cb1, cb2;
Choice choice; List list;
AwtTest () {
btn = new Button("버튼");
lbl = new Label("라벨");
ta = new TextArea("TextArea", 5, 20); // 5행, 20열
tf = new TextField("TextField", 20); // 20칸
cb1 = new Checkbox("체크박스1");
cb2 = new Checkbox("체크박스2");
choice = new Choice();
list = new List(3,true); // 보여지는것은 2개이고 다중선택은 true로 지정
}
void display() {
setLayout(new FlowLayout()); // 컴포넌트 배치 설정
add(btn);
add(lbl);
add(ta);
add(tf);
add(cb1);
add(cb2);

choice.add("초록"); // 콤보박스에 항목 추가
choice.add("빨강");
choice.add("파랑");
add(choice);
list.add("봄"); // 리스트박스에 항목 추가
list.add("여름");
list.add("가을");
list.add("겨울");
add(list);
pack();
setVisible(true);
}
public static void main(String args[]) {
AwtTest myFrame = new AwtTest();
myFrame.display();
}
}

2013년 8월 6일 화요일

[오라클자바교육강좌]Easy Struts를 이용한 예제

Easy Struts를 이용한 예제 


오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷 실무전문 강의)  



1.Tomcat Project를 하나 만듭니다.

- File  --> New를 선택 후 “Project”를 선택 합니다.

-Java 옵션의 “Tomcat Project”를 선택 후 적절한 프로젝트 이름을 입력 합니다. 그런 다음 Next 하시구요…
(우린 EasyStruts라고 하자구요~)

-“Can update server.xml”을 check 확인 하시구요(이건 디폴트 입니다)

-“Finish” 합니다.

2.Easy Struts가 사용 가능하도록 합니다.

- “New” (좌측 상단에 위치) 버튼을 클릭 합니다.
-“Java” 옵션의 하위 옵션인 “Easy Struts”를 선택 합니다.

 

오른쪽에 보이는 것은 Easy Struts가 제공하는 10가지의 Function 입니다.

- Base package for generation : com.asprise.struts
-“Add Easy Struts support" 를 선택 후 Next 합니다.
-"Copy Struts binary" 와"Copy Struts TLD" 를 체크 합니다.



3.“Easy Action Associated with a Form”을 이용하여 작업 하기

좌 상단의 New 버튼을 누른 후 “Easy Struts Function View”를 띄웁니다. “Easy Action associated with a form" 을 선택하고 아래의 과정을 따라 합니다.

Use case, Forn Name 과 FornType을 변경 합니다. (이건 화면을 띄우면 기본적으로 값이 채워져 있습니다.)

Use case : owner
Form name : ownerForm
Form Type : com.asprise.form.OwnerForm

그런 다음 Form properties에서 “Add”를 클릭 합니다.
아래와 같이 속성을 줍니다.

이름 :: 타입 :: 초기치 :: JSP input type
----------------------------------------------
greet :: java.lang.String : Mr. : :: select
name :: java.lang.String : : :: text
email :: java.lang.String : : :: text
tel :: java.lang.String:: :: text
address :: java.lang.String : : :: text

위와 같이 속성을 주게되면 struts에서는 자동으로 setter와 getter를 생성 하게 되는 겁니다.

그런 다음 아래에서 처음 두 개의 체크 박스를 체크 하시구요 다음으로 넘어 갑니다.

       
4. 위에서 Next를 하게 되면 화면이 하나 나타나는데 기본적으로 input value는 “/form/owner.jsp”로 되어 있을 겁니다.
이 JSP 파일의 Location은 수작업 또는 Preference Setting을 통해 수정 하는 것이 가능 합니다. Preference Setting을 수정
하기 위해서는 “Window” 메뉴의 “Preference”로 이동 후 “Easy Struts” 옵션을 선택 합니다. 그런 다음 “Style” 탭을 선택하고
적절하게 “JSP form localtion”을 수정 합니다. 만약 공백으로 준다면 지금 나타나는 화면에서 /owner.jsp로 나타날 겁니다.
아래에 각 항목에 대한 설명이 있습니다.

Path. 서브밋 되는 Request의 Path이며 반드시 “/”로 시작 해야 합니다.
Type. ActionMapping,에서 사용되는 Action Class의 이름
Attribute. Request Scope나 Session Scope에서 폼빈에 대한 이름
Scope: 폼빈이 이 매핑을 통해 존재하게 될 Scope
input. : 에러 등이 나게 되면 Return하게 되는 context-relative path 
Validate : 이걸 체크하게 되면 ActionForm.validate() method 가 Call 됩니다.
Parameter. Action에게 넘겨 줄 파라미터 등을 기술

Path : /owner
Type : com.asprise.struts.OwnerAction
Attribute : ownerForm
Scope : Request
(Create JSP)Input : /owner.jsp

 
4.위화면에서 Next를 누르게 되면 Forward와 Exception을 설정 하게 되는데 그 내용은 아래와 같습니다.

Forward : Action이 포워드될 Servlet이나 JSP 자원에 대한 Context-relative 경로
Exception : 이 mapping과 관련된 Exception Handler

아래와 같이 Forward를 만듭니다.

Forward name : success
Forward path : /success.jsp

 

화면에서  Finish를 클릭하면 Struts 시스템에서는 자동으로 com.asprise.struts.form.OwnerForm.java and com.asprise.struts.action.OwnerAction.java 파일을 만들게 됩니다. (EasyStruts/WEB-INF/src/ 아래에 만듭니다) 이와 동시에 /owner.jsp 파일도 자동으로 만들어 집니다.  개발자는 적절히 이러한 파일들을 수정을 하면됩니다. 폼빈에서는 validate 메소드 등을 적절히 완성하면 됩니다.

5.이번에는 자동으로 만들어진 Action Class를 수정해 보도록 합니다.

아래의 소스가 자동으로 만들어진 Action Class 입니다. 여기에서 Interger라고 한 부분을 int로 수정 하시구요….

여러분들은 validate() 메소드를 추가해 주시면 됩니다. Validate가 추가된 소스는 다음에 있으니 참고 바랍니다.

Validate() 메소드가 추가된 OwnerForm.java 파일은 다음과 같습니다.

==================================================================

// Created by Xslt generator for Eclipse.
// XSL :  not found (java.io.FileNotFoundException:  (No such file or directory))
// Default XSL used : easystruts.jar$org.easystruts.xslgen.JavaClass.xsl

package com.asprise.struts.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

/**
 * OwnerForm.java created by EasyStruts - XsltGen.
 * http://easystruts.sf.net
 * created on 01-25-2005
 *
 * XDoclet definition:
 * @struts:form name="ownerForm"
 */
public class OwnerForm extends ActionForm {

        // --------------------------------------------------------- Instance Variables

        /** greet property */
        private String greet = "Mr.";

        /** address property */
        private String address;

        /** email property */
        private String email;

        /** tel property */
        private String tel;

        /** name property */
        private String name;

        // --------------------------------------------------------- Methods

        /**
        * Method validate
        * @param ActionMapping mapping
        * @param HttpServletRequest request
        * @return ActionErrors
        */
        public ActionErrors validate(
                ActionMapping mapping,
                HttpServletRequest request) {

                        ActionErrors errors = new ActionErrors();
                  if (greet == null || greet.trim().equals("")) {
                        errors.add("greet", new ActionError("error.greet"));
                  }
                  if (name == null || name.trim().equals("")) {
                        errors.add("name", new ActionError("error.name"));
                  }
                  if (address == null || address.trim().equals("")) {
                        errors.add("address", new ActionError("error.address"));
                  }
                  if (email == null || email.trim().equals("")) {
                        errors.add("email", new ActionError("error.noEmail"));
                  }
                  else if (email.indexOf("@")==-1) {
                        errors.add("email", new ActionError("error.wrongEmail"));
                  }
                  if (tel == null || tel.trim().equals("")) {
                        errors.add("tel", new ActionError("error.tel"));
                  }
                  return errors;
    }

       

        /**
        * Method reset
        * @param ActionMapping mapping
        * @param HttpServletRequest request
        */
        public void  reset(ActionMapping mapping, HttpServletRequest request) {
                greet = "Mr.";
                address = "";
                email = "";
                tel = "";
                name = "";

        }

        /**
        * Returns the greet.
        * @return String
        */
        public String getGreet() {
                return greet;
        }

        /**
        * Set the greet.
        * @param greet The greet to set
        */
        public void setGreet(String greet) {
                this.greet = greet;
        }

        /**
        * Returns the address.
        * @return String
        */
        public String getAddress() {
                return address;
        }

        /**
        * Set the address.
        * @param address The address to set
        */
        public void setAddress(String address) {
                this.address = address;
        }

        /**
        * Returns the email.
        * @return String
        */
        public String getEmail() {
                return email;
        }

        /**
        * Set the email.
        * @param email The email to set
        */
        public void setEmail(String email) {
                this.email = email;
        }

        /**
        * Returns the tel.
        * @return String
        */
        public String getTel() {
                return tel;
        }

        /**
        * Set the tel.
        * @param tel The tel to set
        */
        public void setTel(String tel) {
                this.tel = tel;
        }

        /**
        * Returns the name.
        * @return String
        */
        public String getName() {
                return name;
        }

        /**
        * Set the name.
        * @param name The name to set
        */
        public void setName(String name) {
                this.name = name;
        }

}

=================================================================================

6.이번에는 OwnerAction.java 에서 사용된 error key에 대한 부분을 ApplicationResources.properties 파일에 설정 합니다.

# Resources for parameter 'com.asprise.struts.ApplicationResources'
# Project P/EasyStruts

errors.header=<h4>Validation Error(s)</h4><ul>
errors.footer=</ul><hr>

error.greet=<li>Choose your greet
error.name=<li>Enter your name
error.address=<li>Enter your address
error.tel=<li>Enter your contact number
error.wrongEmail=<li>Correct your email
error.noEmail=<li>Enter your email


7.이번에는 OwnerAction.java 파일을 변경 합니다.

===========================================================================

// Created by Xslt generator for Eclipse.
// XSL :  not found (java.io.FileNotFoundException:  (No such file or directory))
// Default XSL used : easystruts.jar$org.easystruts.xslgen.JavaClass.xsl

package com.asprise.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.asprise.struts.form.OwnerForm;

/**
 * OwnerAction.java created by EasyStruts - XsltGen.
 * http://easystruts.sf.net
 * created on 01-25-2005
 *
 * XDoclet definition:
 * @struts:action path="/owner" name="ownerForm" input="/owner.jsp" validate="true"
 * @struts:action-forward name="/success.jsp" path="/success.jsp"
 */
public class OwnerAction extends Action {


        /**
        * Method execute
        * @param ActionMapping mapping
        * @param ActionForm form
        * @param HttpServletRequest request
        * @param HttpServletResponse response
        * @return ActionForward
        * @throws Exception
        */
        public ActionForward execute(
                ActionMapping mapping,
                ActionForm form,
                HttpServletRequest request,
                HttpServletResponse response)
                throws Exception {
                        OwnerForm ownerForm = (OwnerForm) form;
     
                  String greet = ownerForm.getGreet();
                  String name = ownerForm.getName();
                  request.setAttribute("name", name);
                  request.setAttribute("greet", greet);

                  // Forward control to the specified success target

                  return (mapping.findForward("success"));

        }

}

====================================================================

8.이번에는 owner.jsp를 수정 합니다.

“greet”라는 속성을 만들 때 select 형태로 주었습니다, 이 부분에 적절한 옵션을 추가해 주시면 됩니다.

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
<html>
  <head>
      <meta
        name = "Generator"
        content = "Easy Struts Xslt generator for Eclipse (http://easystruts.sf.net).">
      <title>Struts Form for ownerForm</title>
  </head>
  <body>
      <html:form action="/owner">
        greet : <html:select property="greet">
                    <html:option value=""></html:option>
                    <html:option value="Mr.">Mr.</html:option>
                    <html:option value="Miss">Miss</html:option>
                    <html:option value="Mrs.">Mrs.</html:option>
                </html:select><html:errors property="greet"/>
    name : <html:text property="name"/><html:errors property="name"/></br>
    address : <html:text property="address"/><html:errors property="address"/></br>
    email : <html:text property="email"/><html:errors property="email"/></br>
    tel : <html:text property="tel"/><html:errors property="tel"/></br>
        <html:submit/><html:cancel/>
      </html:form>
    <html:errors />
  <body>
</html>


9.이번에는 success.jsp를 만듭니다. (EasyStruts 프로젝트에서 New , File 한 후 추가 합니다)

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

<logic:present name="name" scope="request">
Thank you,
  <logic:present name="greet" scope="request">
      <bean:write name="greet" scope="request"/>
  </logic:present>
  <bean:write name="name" scope="request"/>
</logic:present>


10.이번에는 struts-config.xml 파일을 열어 설정을 확인합니다. UI형태를 지원하므로 편리하게 struts-config.xml을 설정하는 것이 가능 합니다

Struts-config.xml을 클릭하면 다음과 같은 UI를 가진 화면이 나타나는데 여기서 기존 방법보다 좀 더 편리하게 struts의 설정을 할 수가 있습니다.

 

11.실행 결과 확인 

2013년 8월 2일 금요일

간단한 JAVA Swing Button 예제

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

public class SwingButtonTest {
        public void Test() {
        JFrame f = new JFrame("Swing 테스트"); //frame을 생성하고,
        JPanel p = new JPanel();              // panel을 생성합니다.
        JButton b = new JButton("예");        //그리고 button을...
        p.add(b);                                      // button을 panel에 추가합니다
        b.setToolTipText("이건 튤팁입니다.");
        f.getContentPane().add(p);
        f.pack();
        f.setVisible(true);
        }
public static void main(String args[]) {
        new SwingButtonTest().Test();
}
}

JAVA

"자바 디자인 패턴 입문" 이라는 책의 내용을 정리하여 올립니다.

시스템내에 단 한 개만 존재하는 것을 프로그램으로 표현시 클래스의 인스턴스를 하나만 만든다.
 지정한 클래스의 인스턴스가 하나만 존재하고 이를 프로그램 상에서 보장하는 패턴을 Singleton Pattern이라 한다.
 다수의 인스턴스가 존재하는 경우 상호간에 영향을 주어 예기치 못한 오류가 발생할 확률이 높으므로 이를 제한하는 경우에 사용



 예제의 Singleton Class는 인스턴스를 하나만 만들고 static으로 singleton이 정의되어 클래스가 메모리에 로드될때 한번 초기화 된다. 

오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷 실무전문 강의) 


생성자가 private으로 되어 있으므로 외부에서 new Singleton()을 하게되면 컴파일 시에 오류가 발생한다.Singleton 패턴의 경우 개발자가 부주의 하더라도 인스턴스는 하나만 존재


// Singleton.java
public class Singleton {
    private static Singleton singleton = new Singleton();
    private Singleton() {
        System.out.println("인스턴스 생성!");                   
    }
    public static Singleton getInstance() {       
        return singleton;
    }                                         
}


//Main.java
public class Main extends Thread {
    public static void main(String[] args) {
        System.out.println("Start.");       
    Singleton obj1 =    Singleton.getInstance();
      Singleton obj2 = Singleton.getInstance();
        if (obj1 == obj2){
System.out.println("obj1 == obj2");
        }
        else { System.out.println("obj1 != obj2");
        }
    }
}

java inheritence and composition(자바 상속 컴포지션)

상속과 컴포지션은 동전의 양면과 같이 유사하게 서로에게 관련이 있다. 
 - 상속은 마치 양파가 여러 껍질로 이루어진 것과 같이 계층화된 객체
 - 컴포지션은 여러 재료(객체)가 한데 뭉쳐서 만들어진 죽
 - 컴포지션은 개체들간의 'has a' 관계, 상속은 ‘is a’관계
 - 상속과 컴포지션은 상호 배타적이지 않으며 개발자는 이 둘을 같이 사용한다.

오라클자바커뮤니티에서 설립한 오엔제이프로그래밍 실무교육센터
(오라클SQL, 튜닝, 힌트,자바프레임워크, 안드로이드, 아이폰, 닷넷 실무전문 강의) 



Composition Exam

class Soap {
  private String s;
  Soap() {
    System.out.println("Soap()");
    s = new String("Constructed");
  }
  public String toString() { return s; }
}

public class Bath {
  private String 
    // Initializing at point of definition:
    s1 = new String("Happy"), 
    s2 = "Happy", 
    s3, s4;
  Soap castille;
  int i;
  float toy;
  Bath() {
    System.out.println("Inside Bath()");
    s3 = new String("Joy");
    i = 47;
    toy = 3.14f;
    castille = new Soap();
  }
  void print() {
    // Delayed initialization:
    if(s4 == null)
      s4 = new String("Joy");
    System.out.println("s1 = " + s1);
    System.out.println("s2 = " + s2);
    System.out.println("s3 = " + s3);
    System.out.println("s4 = " + s4);
    System.out.println("i = " + i);
    System.out.println("toy = " + toy);
    System.out.println("castille = " + castille);
  }

  public static void main(String[] args) {
    Bath b = new Bath();
    b.print();
  }
}