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

2013년 8월 9일 금요일

[ORACLEJAVA커뮤니티 .NET교육, JAVA교육]닷넷(C#)으로 만든 주소록 예제

닷넷 주소록은 Visual Studio .Net 에서 작성하시면 되구요 ... 대충 보시면 이해가 되겠지만 ADO.Net을 사용한 예제이며 DB는 오라클을 사용 했습니다.
(주소에 대한 입력/수정/삭제 가능하구요, 검색도 되는 멋진 주소록 입니다.)

Oracle의 Scott에 아래의 주소록 테이블을 만드신 후 실습 바랍니다.
/*
*
* 실습용 Table script
create table AddrBook (
name varchar2(20) not null primary key,
sex varchar2(2) not null constraint ck_sex check (sex in ('M','F')),
addr varchar2(50),
tel varchar2(20) not null
)
*
* */

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



--------------------------------------------------------------------
Visual Studio .Net을 실행 하신 후 C#, Window 응용 프로그램을 선택, 프로젝트 이름은 주소록으로 주시기 바랍니다.

AddrBook.cs와 CodeFile1.cs 두개의 파일을 만들어 주시면 됩니다. CodeFile1은 AddrBook.cs에서 DB 처리 부분을 탇게될 라이브러리 형태 입니다. AddrBook.cs 파일을 만들려면 새프로젝트가 시작된 상태에서 우측의 솔루션 탐색기에서 주소록에서 마우스 우측 버튼을 눌러 추가 --> 구성요소 추가 --> 새항목 추가 --> 윈도우 폼을 하시고 CodeFile1.cs의 경우 CodeFile 로 하자구요~

우선 아래의 AddrBook.cs를 다 입력하고 나면 저절로 디자인 화면에 아래처럼 디자인된 화면이 나타날겁니다. 물론 실제 개발하면 대부분의 GUI 프로그램 처럼 먼저 디자인을 하고 나중에 필요한 스크립트를 추가하는 형태가 되겠죠...

-------------------------
1. AddrBook.cs
-------------------------
using System;
using System.Data.OleDb;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
namespace medical
{
///

/// CDJohap에 대한 요약 설명입니다.
///

public class AddrBook : System.Windows.Forms.Form
{
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.ListView listView1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.ColumnHeader Gubun;
private System.Windows.Forms.ColumnHeader JohapCd;
private System.Windows.Forms.ColumnHeader JohapNm;
private System.Windows.Forms.ColumnHeader Bigo;
private System.Windows.Forms.Button btnNew;
private System.Windows.Forms.Button btnInput;
private System.Windows.Forms.Button btnUpdate;
private System.Windows.Forms.Button btnDelete;
private System.Windows.Forms.Button btnSearch;
private System.Windows.Forms.TextBox txtAddr;
private System.Windows.Forms.TextBox txtName;
private System.Windows.Forms.TextBox txtTel;
private System.Windows.Forms.ComboBox comSex;
private System.Windows.Forms.TextBox txtSearchName;
///

/// 필수 디자이너 변수입니다.
///

private System.ComponentModel.Container components = null;

public AddrBook()
{
//
// Windows Form 디자이너 지원에 필요합니다.
//
InitializeComponent();
//
// TODO: InitializeComponent를 호출한 다음 생성자 코드를 추가합니다.
//
}
///

/// 사용 중인 모든 리소스를 정리합니다.
///

protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
///

/// 디자이너 지원에 필요한 메서드입니다.
/// 이 메서드의 내용을 코드 편집기로 수정하지 마십시오.
///

private void InitializeComponent()
{
this.Gubun = new System.Windows.Forms.ColumnHeader();
this.JohapCd = new System.Windows.Forms.ColumnHeader();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.btnSearch = new System.Windows.Forms.Button();
this.txtSearchName = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.txtAddr = new System.Windows.Forms.TextBox();
this.JohapNm = new System.Windows.Forms.ColumnHeader();
this.listView1 = new System.Windows.Forms.ListView();
this.Bigo = new System.Windows.Forms.ColumnHeader();
this.txtName = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.txtTel = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.comSex = new System.Windows.Forms.ComboBox();
this.btnNew = new System.Windows.Forms.Button();
this.btnInput = new System.Windows.Forms.Button();
this.btnUpdate = new System.Windows.Forms.Button();
this.btnDelete = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// Gubun
//
this.Gubun.Text = "성별";
this.Gubun.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.Gubun.Width = 100;
//
// JohapCd
//
this.JohapCd.Text = "성명";
this.JohapCd.Width = 80;
//
// groupBox1
//
this.groupBox1.Controls.Add(this.btnSearch);
this.groupBox1.Controls.Add(this.txtSearchName);
this.groupBox1.Location = new System.Drawing.Point(8, 6);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(264, 52);
this.groupBox1.TabIndex = 38;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "사용자 검색창 : 성명";
//
// btnSearch
//
this.btnSearch.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(224)), ((System.Byte)(224)), ((System.Byte)(224)));
this.btnSearch.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnSearch.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnSearch.Font = new System.Drawing.Font("굴림", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(129)));
this.btnSearch.Location = new System.Drawing.Point(176, 16);
this.btnSearch.Name = "btnSearch";
this.btnSearch.Size = new System.Drawing.Size(72, 26);
this.btnSearch.TabIndex = 47;
this.btnSearch.Text = "검색";
this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
//
// txtSearchName
//
this.txtSearchName.AutoSize = false;
this.txtSearchName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtSearchName.Font = new System.Drawing.Font("굴림", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(129)));
this.txtSearchName.Location = new System.Drawing.Point(17, 16);
this.txtSearchName.Name = "txtSearchName";
this.txtSearchName.Size = new System.Drawing.Size(160, 26);
this.txtSearchName.TabIndex = 47;
this.txtSearchName.Text = "";
//
// label6
//
this.label6.BackColor = System.Drawing.Color.White;
this.label6.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.label6.Font = new System.Drawing.Font("굴림", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(129)));
this.label6.Location = new System.Drawing.Point(16, 130);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(550, 2);
this.label6.TabIndex = 34;
//
// txtAddr
//
this.txtAddr.AutoSize = false;
this.txtAddr.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtAddr.Font = new System.Drawing.Font("굴림", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(129)));
this.txtAddr.Location = new System.Drawing.Point(103, 94);
this.txtAddr.Name = "txtAddr";
this.txtAddr.Size = new System.Drawing.Size(160, 26);
this.txtAddr.TabIndex = 33;
this.txtAddr.Text = "";
//
// JohapNm
//
this.JohapNm.Text = "주소";
this.JohapNm.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.JohapNm.Width = 200;
//
// listView1
//
this.listView1.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(255)), ((System.Byte)(225)));
this.listView1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.JohapCd,
this.Gubun,
this.JohapNm,
this.Bigo});
this.listView1.Font = new System.Drawing.Font("굴림", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(129)));
this.listView1.FullRowSelect = true;
this.listView1.GridLines = true;
this.listView1.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.listView1.Location = new System.Drawing.Point(8, 144);
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(568, 368);
this.listView1.TabIndex = 31;
this.listView1.View = System.Windows.Forms.View.Details;
this.listView1.SelectedIndexChanged += new System.EventHandler(this.listView1_SelectedIndexChanged);
//
// Bigo
//
this.Bigo.Text = "전화번호";
this.Bigo.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.Bigo.Width = 175;
//
// txtName
//
this.txtName.AutoSize = false;
this.txtName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtName.Font = new System.Drawing.Font("굴림", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(129)));
this.txtName.Location = new System.Drawing.Point(103, 70);
this.txtName.Name = "txtName";
this.txtName.Size = new System.Drawing.Size(160, 26);
this.txtName.TabIndex = 29;
this.txtName.Text = "";
//
// label3
//
this.label3.BackColor = System.Drawing.SystemColors.Control;
this.label3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label3.Font = new System.Drawing.Font("굴림", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(129)));
this.label3.Location = new System.Drawing.Point(8, 94);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(96, 26);
this.label3.TabIndex = 28;
this.label3.Text = "주소";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label2
//
this.label2.BackColor = System.Drawing.SystemColors.Control;
this.label2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label2.Font = new System.Drawing.Font("굴림", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(129)));
this.label2.Location = new System.Drawing.Point(8, 70);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(96, 26);
this.label2.TabIndex = 27;
this.label2.Text = "성명*";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label1
//
this.label1.BackColor = System.Drawing.SystemColors.Control;
this.label1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label1.Font = new System.Drawing.Font("굴림", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(129)));
this.label1.Location = new System.Drawing.Point(262, 70);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(96, 26);
this.label1.TabIndex = 32;
this.label1.Text = "성별*";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// txtTel
//
this.txtTel.AutoSize = false;
this.txtTel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtTel.Font = new System.Drawing.Font("굴림", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(129)));
this.txtTel.Location = new System.Drawing.Point(357, 94);
this.txtTel.Name = "txtTel";
this.txtTel.Size = new System.Drawing.Size(216, 26);
this.txtTel.TabIndex = 39;
this.txtTel.Text = "";
//
// label4
//
this.label4.BackColor = System.Drawing.SystemColors.Control;
this.label4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label4.Font = new System.Drawing.Font("굴림", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(129)));
this.label4.Location = new System.Drawing.Point(262, 94);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(96, 26);
this.label4.TabIndex = 40;
this.label4.Text = "전화번호*";
this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// comSex
//
this.comSex.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comSex.Font = new System.Drawing.Font("굴림", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(129)));
this.comSex.ImeMode = System.Windows.Forms.ImeMode.NoControl;
this.comSex.Location = new System.Drawing.Point(357, 72);
this.comSex.Name = "comSex";
this.comSex.Size = new System.Drawing.Size(216, 23);
this.comSex.TabIndex = 41;
//
// btnNew
//
this.btnNew.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(224)), ((System.Byte)(224)), ((System.Byte)(224)));
this.btnNew.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnNew.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnNew.Font = new System.Drawing.Font("굴림", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(129)));
this.btnNew.Location = new System.Drawing.Point(288, 24);
this.btnNew.Name = "btnNew";
this.btnNew.Size = new System.Drawing.Size(72, 26);
this.btnNew.TabIndex = 43;
this.btnNew.Text = "신규";
this.btnNew.Click += new System.EventHandler(this.btnNew_Click);
//
// btnInput
//
this.btnInput.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(224)), ((System.Byte)(224)), ((System.Byte)(224)));
this.btnInput.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnInput.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnInput.Font = new System.Drawing.Font("굴림", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(129)));
this.btnInput.Location = new System.Drawing.Point(359, 24);
this.btnInput.Name = "btnInput";
this.btnInput.Size = new System.Drawing.Size(72, 26);
this.btnInput.TabIndex = 44;
this.btnInput.Text = "입력";
this.btnInput.Click += new System.EventHandler(this.btnInput_Click);
//
// btnUpdate
//
this.btnUpdate.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(224)), ((System.Byte)(224)), ((System.Byte)(224)));
this.btnUpdate.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnUpdate.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnUpdate.Font = new System.Drawing.Font("굴림", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(129)));
this.btnUpdate.Location = new System.Drawing.Point(430, 24);
this.btnUpdate.Name = "btnUpdate";
this.btnUpdate.Size = new System.Drawing.Size(72, 26);
this.btnUpdate.TabIndex = 45;
this.btnUpdate.Text = "수정";
this.btnUpdate.Click += new System.EventHandler(this.btnUpdate_Click);
//
// btnDelete
//
this.btnDelete.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(224)), ((System.Byte)(224)), ((System.Byte)(224)));
this.btnDelete.Cursor = System.Windows.Forms.Cursors.Hand;
this.btnDelete.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnDelete.Font = new System.Drawing.Font("굴림", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(129)));
this.btnDelete.Location = new System.Drawing.Point(501, 24);
this.btnDelete.Name = "btnDelete";
this.btnDelete.Size = new System.Drawing.Size(72, 26);
this.btnDelete.TabIndex = 46;
this.btnDelete.Text = "삭제";
this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
//
// AddrBook
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(252)), ((System.Byte)(242)), ((System.Byte)(255)));
this.ClientSize = new System.Drawing.Size(584, 516);
this.Controls.Add(this.btnDelete);
this.Controls.Add(this.btnUpdate);
this.Controls.Add(this.btnInput);
this.Controls.Add(this.btnNew);
this.Controls.Add(this.comSex);
this.Controls.Add(this.txtTel);
this.Controls.Add(this.label4);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.label6);
this.Controls.Add(this.txtAddr);
this.Controls.Add(this.listView1);
this.Controls.Add(this.txtName);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "AddrBook";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "주소록";
this.Load += new System.EventHandler(this.CDJohap_Load);
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);

}
#endregion
static void Main()
{
Application.Run(new AddrBook());
}
private OleDbConnection LocalConn;
//**************************************************************
//
// ListView에 성명 데이터 전체를 로드하는 함수
//
//
//**************************************************************
private void DataLoad(OleDbDataReader myDataReader)
{
listView1.Items.Clear();
while(myDataReader.Read())
{
ListViewItem myitem1;
string gubun;
if (myDataReader["Sex"].ToString()=="M")
{
gubun = "남자";
}
else
{
gubun = "여자";
}

myitem1 = new ListViewItem(myDataReader["Name"].ToString());
myitem1.SubItems.Add(gubun);
//myitem1.SubItems.Add(myDataReader["Addr"].ToString());
//주소가 null 값을 리턴하면...
if(myDataReader.IsDBNull(2))
{
myitem1.SubItems.Add("");
}
else
{
myitem1.SubItems.Add(myDataReader["Addr"].ToString());
}
//Bigo 가 null 값을 리턴하면...
myitem1.SubItems.Add(myDataReader["Tel"].ToString());

listView1.Items.Add(myitem1);
}
myDataReader.Close();
}

//**************************************************************
//
// 주소록 폼이 로딩 될때 전체 데이터를 ListView에 로딩
// 콤보박스 초기화 작업
//
//**************************************************************
private void CDJohap_Load(object sender, System.EventArgs e)
{
try
{
//--------------------------------------------
LocalConn = Common_DB.DBConnection();
//--------------------------------------------
LocalConn.Open();
OleDbDataReader myReader = Common_DB.DataSelect("select * from AddrBook ",LocalConn);
DataLoad(myReader);

//Combo Box 채우기
comSex.Items.Add("남자");
comSex.Items.Add("여자");
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "AddrBook Form Loading");
}
finally
{
LocalConn.Close();
}
}
//**************************************************************
//
// ListView에 마우스를 클릭 했을때 윗부분의 TextBox에 자료 로딩
// 2003.10.20
//
//**************************************************************
private void listView1_SelectedIndexChanged(object sender, System.EventArgs e)
{
try
{
txtName.Text = listView1.SelectedItems[0].SubItems[0].Text;
comSex.Text = listView1.SelectedItems[0].SubItems[1].Text;
txtAddr.Text = listView1.SelectedItems[0].SubItems[2].Text;
txtTel.Text = listView1.SelectedItems[0].SubItems[3].Text;
}
catch(Exception)
{
//MessageBox.Show(ex.Message, "listView1_SelectedIndexChanged");
}
}
//**************************************************************
//
// 신규버튼 클릭시... TextBox부분을 Clear(새로운 데이터 입력을 위한)
//
//
//**************************************************************
private void btnNew_Click(object sender, System.EventArgs e)
{
txtName.Text="";
txtAddr.Text="";
comSex.Text="남자";
txtTel.Text="";
}
//**************************************************************
//
// 입력 버튼 클릭시 DB에 Insert 하는 부분
//
//
//**************************************************************
private void btnInput_Click(object sender, System.EventArgs e)
{
if(txtName.Text==""|| txtTel.Text==""||comSex.Text=="")
{
MessageBox.Show("성명, 성별, 전화번호는 필수 입력사항 입니다.");
txtName.Focus();
return;
}

string gubun;
if (comSex.Text=="남자")
{
gubun="M";
}
else
{
gubun="F";
}
LocalConn.Open();
string myExecuteQuery = "Insert Into AddrBook (Name, Sex, Addr, Tel) values(";
myExecuteQuery += "'" + txtName.Text+"'"+",";
myExecuteQuery += "'" + gubun+"'"+",";
myExecuteQuery += "'"+ txtAddr.Text + "'" + ",";
myExecuteQuery += "'"+ txtTel.Text + "'" + ")";

if (Common_DB.DataManupulation(myExecuteQuery, LocalConn))
{
OleDbDataReader myReader = Common_DB.DataSelect("select * from AddrBook",LocalConn);
DataLoad(myReader);
MessageBox.Show("정상적으로 입력 되었습니다...");
}
LocalConn.Close();
}
//**************************************************************
//
// 수정 버튼 클릭시 DB에 Update 하는 부분
//
//
//**************************************************************
private void btnUpdate_Click(object sender, System.EventArgs e)
{
if(txtName.Text==""|| txtTel.Text==""||comSex.Text=="")
{
MessageBox.Show("성명, 성별, 전화번호는 필수 입력사항 입니다.");
txtName.Focus();
return;
}

string gubun;
if (comSex.Text=="남자")
{
gubun="M";
}
else
{
gubun="F";
}
LocalConn.Open();
string myExecuteQuery = "Update AddrBook set Name='" + txtName.Text + "'" + ",";
myExecuteQuery += " Addr = '" + txtAddr.Text + "'" + ",";
myExecuteQuery += " Sex = '" + gubun + "'" + ",";
myExecuteQuery += " Tel = '" + txtTel.Text + "'" ;
myExecuteQuery += " where Name = " + "'" + txtName.Text + "'";

if (Common_DB.DataManupulation(myExecuteQuery, LocalConn))
{
OleDbDataReader myReader = Common_DB.DataSelect("select * from AddrBook",LocalConn);
DataLoad(myReader);
MessageBox.Show(" 정상적으로 수정 되었습니다...");
}
LocalConn.Close();
}
//**************************************************************
//
// 삭제 버튼클릭시 DB의 자료를 Delete
//
//
//**************************************************************
private void btnDelete_Click(object sender, System.EventArgs e)
{
OleDbDataReader myReader=null;
if(txtName.Text==""|| txtTel.Text==""||comSex.Text=="")
{
MessageBox.Show("성명, 성별, 전화번호는 필수 입력사항 입니다.");
txtName.Focus();
return;
}
//------- 삭제 확인
if (MessageBox.Show ("정말 삭제 하시겠습니까?", "삭제확인",
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
!= DialogResult.Yes)
{
return;
}

LocalConn.Open();
string myExecuteQuery = "Delete AddrBook ";
myExecuteQuery += " where Name = " + "'" + txtName.Text + "'";

if (Common_DB.DataManupulation(myExecuteQuery, LocalConn))
{
myReader = Common_DB.DataSelect("select * from AddrBook",LocalConn);
DataLoad(myReader);
MessageBox.Show(" 정상적으로 삭제 되었습니다...");
}
LocalConn.Close();
}
//**************************************************************
//
// 검색 버튼클릭시 DB의 자료를 검색
//
//
//**************************************************************
private void btnSearch_Click(object sender, System.EventArgs e)
{
OleDbDataReader myReader=null;

LocalConn.Open();
myReader = Common_DB.DataSelect("select * from AddrBook where name like '%"+txtSearchName.Text +"%'",LocalConn);
if (myReader != null)
{
DataLoad(myReader);
myReader.Close();
}
LocalConn.Close();
}
}
}


-------------------------
2. CodeFile1.cs
-------------------------
using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlTypes;
using System.Windows.Forms;
public class Common_DB
{
//-----------------------------------------------------------------------------
// DataBase Connection
//-----------------------------------------------------------------------------
public static OleDbConnection DBConnection()
{
OleDbConnection Conn;
//아래는 오라클용 접속 문자열, data source 애는 tnsnames.ora 파일에 있는 Alias명을 넣으면 됩니다.
string ConStr = ("Provider=MSDAORA;data source=\\printserver;User ID=scott;Password=tiger");
Conn = new OleDbConnection(ConStr);
return Conn;
}
//-----------------------------------------------------------------------------
// DataSelect
//-----------------------------------------------------------------------------
public static OleDbDataReader DataSelect(string sql, OleDbConnection Conn)
{
try
{
OleDbCommand myCommand = new OleDbCommand(sql, Conn);
return myCommand.ExecuteReader();
}
catch(Exception ex)
{
//Log File에 출력
MessageBox.Show(sql + "\n" + ex.Message, "DataSelect");
return null;
}
finally
{
}
}
//-----------------------------------------------------------------------------
// DataDelete, DataInsert
//-----------------------------------------------------------------------------
public static bool DataManupulation(string sql, OleDbConnection Conn)
{
try
{
OleDbCommand myCommand = new OleDbCommand(sql, Conn);
myCommand.ExecuteNonQuery();
return true;
}
catch(Exception ex)
{
//Log File에 출력
MessageBox.Show(sql + "\n" + ex.Message, "DataManupulation");
return false;
}
finally
{

}
}
/*
*
* 실습용 Table script
create table AddrBook (
name varchar2(20) not null primary key,
sex varchar2(2) not null constraint ck_sex check (sex in ('M','F')),
addr varchar2(50),
tel varchar2(20) not null
)
*
* */
}



2013년 8월 8일 목요일

[오라클자바커뮤니티, JAVAORACLE교육]자바 JVM의 메모리 구죠, 자바교육

JAVA JVM의 메모리 구조


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




JVM 의 실행 메모리 영역

메쏘드(method) 영역 : 클래스의 메소드에 대한 바이트코드, 전역변수(클래스 변수)
힙(heap) 영역 : 객체를 저장할때 사용하는 메모리
스택(stack) 영역 : 지역변수,함수의 인자,함수의 리턴값,리턴 번지
레지스터(registers) : 가상 머신의 현재 상태를 보여줌, 현재 실행되고 있는 메소드의 실행 포인터를 저장
실행 풀(Runtime Constant Pool) : 숫자 리터럴과 상수 필드 포함, 메소드 영역으로 부터 할당 받는다.


JVM 의 실행 메모리 영역 ]


메소드 내에서 객체 참조형으로 선언된 변수인 경우(String s = new String("abc") 일때의 s) 지역변수로서 스택에 위치하며 힙에 저장되어 있는 객체에 대한 참조값을 가지게 됩니다.
객체 참조형 변수의 값이 null 이라는 의미는 아무것도 참조하고 있지 않다는 의미 입니다.
New 연산자는 힙(heap) 메모리에 객체를 만들고 그 객체의 참조값을 반환 합니다.(Hello h = new Hello()) ---> Memory Heap에 Hello 클래스의 인스턴스(객체)를 만들고 그것을 스택에 있는 h라는 변수가 참조하도록 합니다. C에서의 포인터 변수와 유사 합니다.)
객체 참조 변수의 경우 대입, 메소드 호출시의 인자, 반환형 등으로 사용 될 때 참조 값만 전달 될 뿐, 객체 자체가 복제되어 전달되는 것은 아닙니다.
아래의 예제를 참고하세요

class C
{
public static void
main(String[] args)
{
int i = 3;
f(i);
}
static void f(int arg)
{
int i = 10;
double f = 3.14
}
}


이상 JVN의 메모리 영역에 대해 살펴 보았습니다.







[오라클교육,자바교육,오라클자바교육,오라클자바커뮤니티]JAVA AWT 프로그래밍-Toolkit

이번 강좌에서는 Java.awt.Toolkit 에 대해 알아 보겠습니다.


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

 

-------------------
Java.awt.Toolkit
-------------------

그래픽 자원관련 시스템 정보 제공 합니다.
new 명령으로 만들수 없으며 Component의 Method인 getToolkit()이나 Toolkit.getDefaultToolkit을 사용해야 합니다.( Toolkit 객체가 하나만 존재해야 하므로…)

beep() : beep 음 출력

createimage(), getImage() : 이미지를 만들거나 Network 경로를 통해얻을 사용 합니다.

getPrintJob() : 프린터와 연결된 객체인 java.awt.PrintJob을 얻게 해 줍니다.

getScreenSoze() : 실제 화면의 크기를 구해주며 스플레쉬(Splash) 윈도우를 만들때 유용 합니다.

getScreenResolution() : 현재 화면이 인치당 몇 개의 점이 들어가는 해상도인지 알려줌.

getSystemClipboard() : 클립보드 객체를 리턴해준다. 이 객체에 내용을 넣어 다른 프로그램등에 전달 해줄때 사용 합니다.



[예제]

/* 화면 한 가운데 width, height가 반인 윈도우 그리기 */
import java.awt.*;

public class ToolkitExam extends Frame {
public ToolkitExam(String title) {
super(title);
}
public static void main(String[] args) {
ToolkitExam halfWindow = new ToolkitExam("Toolkit Sample");
Toolkit toolkit = halfWindow.getToolkit();
Dimension size = toolkit.getScreenSize();

halfWindow.setBounds(size.width/4, size.height/4,
size.width/2, size.height/2);
halfWindow.setVisible(true);

[스프링프레임워크, iBATIS, 자바교육]Spring3.X, MyBatis, Hibernate실무과정


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












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

대기업(상시근로자 300인 이상 대기업)은 개인환급 불가합니다.



* 휴강 :법정공휴일
수강료
입금안내
- 온/오프라인 카드결제, 계좌이체(수강안내->입금안내 참조)
문의사항 02-851-4790 번으로 연락 부탁 드립니다.
교육개요 본과정은 자바 웹개발에서 가장 많이 사용되고 있는 자바기반 프레임워크인 Spring3.2를 학습하는데 스프링이 왜 도입되어야 하는지부터, 기본모듈구성, 아키텍처 DI, DL, IoC, 최근 개발모델의 핵심인 Spring AOP, AspectJ Annotation, 표현언어인 SpEL, Spring MVC, Spring MVC TEST Framework, Spring WebFlow, Spring JDBC, Spring Transaction등 개발에 필요한 부분을 체계적으로 실습을 통해 학습하며 SQLMapper인 MyBatis, Hibernate 까지 학습하는 Spring 최고의 교육 입니다.

[특징]
- 실무/실습에 근거한 이론 취득
- 단기간에 스프링 개발자로 양성
- 문답씩 수업으로 수강 효과 극대화
- 이론/실습 과제로 인한 개발력 UP
교육목표 - Spring의 도입배경 및 아키텍처에 대해 이해한다.
(자바빈의 태동부터 EJB, 그리고 현재까지)
- Eclipse, Maven, STS 플러그인에 대한 이해
(개발환경 설정의 이해)
- Spring IoC(DI, DL)의 이해
(실습을 통한 setter,getter,constructor injection의 이해)
- Spring AOP의 이해
(실습을 통한 Spring AOP의 이해, AOP어렵지 않습니다)
- AspectJ Annotation에 대한 이해
(Spring의 AspectJ 지원 및 Annotation 대한 이해 by 실습)
- Spring Web MVC, JDBC의 이해
(실습을 통한 Spring MVC, JDBC의 이해)
- Spring Controller에 대한 이해
(간단한 Controller의 구현을 통한 MVC Font Contrller의 이해)
- Spring Web Flow에 대한 이해
(실습을 통한 Spring Web Flow 및 JSF에 대한 이해)
- SpEL에 대한 이해
(실습을 통한 Spring SpEL의 이해)
- Servlet3 비동기 요청에 대해 이해한다.
(실습을 통한 비동기 서블릿에 대한 이해)
- MyBatis Mapper에 대해 이해한다.
(실습을 통한 MyBatis 구성, 작동원리 이해)
- Hibernate Mapper에 대해 이해한다.
(실습을 통한 Hibernate 구성, 작동원리 이해)
- 실무 개발 환경에 적응력 UP
(Spring, MyBATIS 기반 게시판 작성)
교육대상 - JAVA, JSP 개발자
- 자바개발은 오래 했지만 프레임워크에 대해 자신이 없는 개발자
- 단기간에 스프링을 박살 내고 싶은 개발자.
(스프링 혼자 공부하기는 어렵습니다!!)
선수학습 - JAVA, JSP
 


Spring3.2 J2EE Framework에 대한 흐름과 Spring Framework에 대한 이해
개발 환경 설정(Eclipse4.2, Tomcat7, Spring3.2 다운로드 및 설치)
Maven, STS 플러그인 설치
Spring IoC
DL(Dependency LookUp) &DI(Dependency Injection)
Dependency Pull, CDL(Contaxtualized Lookup)
Setter/Constructor/Mathod Injection
Spring 설정
Spring AOP 란 ?Code, Advice, JoinPoint, PointCut, Aspect, WeavingProxyFactoryBean
Annotation기반 AOP(AspectJ)
기타 Spring의 선언적 AOP 선언
Spring JDBC
Spring MVC
Spring Controller
Spring Webflow, JSF
Spring 표현언어 SpEL
Servlet3 비동기 요청처리
Spring3.2 Transaction 관리
Spring MVC TEST Framework
MyBatis/hibernate [MyBatis]
개요 및 소개
개발환경 설정 및 설치
Data Mapper란
sqlMapConfig 이해 및 환경설정
Spring, MyBatis 연동
SQL Map XML File 이해
SqlMapClient 이해
SQL의 실행(Insert/update/delete) 이해와 실습
고급 쿼리 사용방법의 이해와 실습
Spring MyBatis 응용예제 작성

[Hibernate]
Hibernate 소개
SessionFactory 설정
1:1, 1:다 매핑
Session Interface
Hibernate DML
Spring, Hibernate 예제 프로그램 작성
 

[오라클자바커뮤니티]에서 파라미터 넘기는 법

보통 <global-forwards>에서는 다음과 같은 방법을 매핑될 페이지를
입력합니다.

<forward name="insert_success"        path="BoardList.do" />

여기서 파라미터를 다음과 같이 입력해서 코딩하면 xml 파싱에러가 납니다.
파라미터가 하나는 들어가는데 두개이상이 안들어 가게 됩니다.

<forward name="order"        path="BoardList.do?code=00001" />
  => 에러 안남

<forward name="order"        path="BoardList.do?code=00001&page=1" />
  => 에러 발생

이 경우에는 다음과 같은 방법으로 코딩하면 다수의
파라미터값을 넘길 수 있습니다.

<forward name="board_insert_success"      path="/BoardList.do?run=BoardList & a m p ; current_page=1"/>

윗 부분의 & a m p ; <=요 부분의 띄어쓰기된 부분을 붙여주면 됩니다.
유용하게 쓰일때가 꼭 있을 거라는 생각이 들어서 올려봤습니다. ^^

스트럿츠 예제 Constants.java [오라클자바닷넷커뮤니티강좌교육]

package oraclejavanew;

public class Constants {
        /**
        * 로그인한 사용자의 LoginForm이 저장될 세션 범위의 Attriute 이름
        */
        public static final String USER_KEY = "user";
       
        /**
        * 로그인한 사용자의 선택 상품을 보관할  세션 범위의 CART
        */
        public static final String CART_KEY = "cart";
       
        /**
        * 로그인한 사용자의 선택 상품을 보관할  세션 범위의 CART(MAP에서 빠져니온 ArrayList)
        * ArrayList안에는 CartItem이 있다.
        */
        public static final String CART_LIST = "cartlist";
       
        /**
        * 로그인한 사용자의 배송지를 보관할  세션 범위의 BAESONGJI
        */
        public static final String BAESONGJI_KEY = "baesongji";
       
        /**
        * 카드 결재시 승인 후 결과 페이지
        */
        public static final String CARD_RESULT_PAGE = "resultpage";
       
        /**
        * 주문번호 생성시 오류 발생한 경우 이동할 페이지
        */
        public static final String ORDER_NO_ERROR = "ordernoerror";
       
       
        /**
        * 무통장 주문완료 후  결과 페이지, 이곳에서 PayAction을 부름...
        */
        public static final String MU_RESULT_PAGE = "muresultpage";
       
       
        /**
        * 로그인한 사용자의 배송지를 보관할  세션 범위의 BAESONGJI
        * ArrayList안에 BaesongjiItem이 들어가 있다.
        *
        */
        public static final String BAESONGJI_LIST = "baesongjilist";
       
       
                     
        /**
        * ActionForward에서 사용되는 값       
        */
        public static final String LOGINOK      = "loginok";
        public static final String LOGIN        = "login";
        public static final String CARTOK      = "cartok";
        public static final String ORDERPAGE    = "orderpage";
        public static final String ORDERMOD    = "ordermod";
        public static final String ORDERCONFIRM = "orderconfirm";
        public static final String LOGOFFOK    = "logoffok";
        public static final String MAIN        = "main";       
        public static final String SHOPINGEND  = "shopingend"; 
        public static final String BADACTION    = "badaction";
       
        public static final String CART      = "/oraclejava/goods/cart.jsp";
        public static final String ORDER      = "/oraclejava/goods/order.jsp";
                       
}

[오라클자바커뮤니티강좌,자바교육]Struts에서의 예외처리-2

Struts에서의 예외처리(2)



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




스트럿츠가 제공 하는 예외 처리

스트럿츠 1.1. 이후에는 작지만 효율적인 예외처리 프레임워크를 추가 했습니다. 또한 org.apache.struts.util.AppException 클래스는 ActionError를 포함하며 java.lang.Exception을 확장한 클래스 입니다.

아래와 같이 스트럿츠에서 사용하면 되는데

throw new AppException(“error.password.invalid”);

생성자의 “error.password.invalid”는 리소스 번들의 key 이며 프레임웍에서는 자동적으로 예외의 ActionError 객체를 생성하고 적절한 scope에 저장 합니다. 물론 애플리케이션에서 AppException에 대해 확장이 가능 합니다.

----------------------------------------------------
선언적 예외 처리와 프로그램적 예외처리
----------------------------------------------------

선언적 예외처리는 struts-config.xml등에 예외에 대해서 정의 하는 것 입니다. 이에 반해 프로그램적 예외 처리는 선언적 예외 처리와 정반대되는 개념으로 애플리케이션에서 정의한 내부 코드를 통해 예외를 처리하는 전통적인 방법 입니다.

아래는 login Action에서 발생하는 세가지 예외를 정의한 것 입니다.

<action-mappings>
                <action
                        path="/login"
                        type="com.oreilly.struts.storefront.security.LoginAction"
                        name="loginForm"
                        scope="request"
                        input="/login.jsp">
               
                <!--The following exceptions can be thrown during the login action -->
                <exception
                        key="security.error.changepassword"
                        path="/changePassword.jsp"
        type="com.oreilly.struts.framework.exceptions.ExpiredPasswordException"/>

                <exception
                        key=" security.error.loginfailed"
                type="com.oreilly.struts.framework.exceptions.InvalidLoginException"
                        path="/login.jsp"/>

                <exception
                        key="security.error.accountlocked"
        type="com.oreilly.struts.framework.exceptions.AccountLockedException"
                        path="/accountLocked.jsp"/>
        </action>
</action-mappings>


위에서 exception 요소는 정의한 예외가 발생 할 경우 포워드할 경로를 액션 매핑이나 전역 예외에 정의 합니다. Login Action이 실행하는 동안 ExpiredPasswordException이 발생 한다면 컨트롤러의 제어를 changePassword.jsp로 포워드 됩니다.

예외를 Action 클래스에 프로그램 코드를 통해 코딩을 하지 않았다면 RequestProcessor는 정의한 예외 타입을 설정한 exception 요소가 있는지 확인 하며 만약 exception 요소가 있다면 컨트롤러는 exception 요소의 path 속성에 지정된 자원으로 포워드 합니다.

아래는 RequestProcessor 클래스의 processException() 메소드 입니다. 메소드의 시작 시점에 findException() 메소드가 ExceptionConfig 객체를 반환 하는데 ExceptionConfig 객체는 설정 파일에 기술된 exception 요소가 메모리에 있는 것으로 생각하면 됩니다.

만약 findException() 메소드가 발생한 예외와 대응하는 exception 요소를 찾지 못하면 스트럿츠 프레임워크에서의 예외 처리 없이 클라이언트에 반환 됩니다. 발생한 예외가 IOException이나 IOException 클래스의 서브 클래스가 아니면 ServletException 인스턴스로 감싸서 다시 던집니다.

만약 특정한 예외를 정의한 Action Mapping이 있다면 findException() 메소드를 통해 ExceptionConfig 객체를 반환 합니다.

getHandler() 메소드는 ExceptionConfig 객체를 추출하고 추출한 핸들러를 예외를 처리하는데 사용 합니다.

--------------------------------------------------------
protected ActionForward processException(HttpServletRequest        request,
                                        HttpServletResponse response,
                                        Exception exception,
                                        ActionForm form,
                                        ActionMapping mapping)
                                        throws IOException, ServletException {
        // Is there a defined handler for this exception?
        ExceptionConfig config =mapping.findException(exception.getClass( ));

        if (config == null){
                if (log.isDebugEnabled( )){
                        log.debug(getInternal().getMessage("unhandledException",exception.getClass( )));
                }

        if (exception instanceof IOException){
                throw (IOException) exception;
        }
        else if (exception instanceof ServletException){
                throw (ServletException) exception;
        }
        else{
                throw new ServletException(exception);
        }


        // Use the configured exception handling
        try {
                Class handlerClass = Class.forName(config.getHandler( ));
                ExceptionHandler handler =(ExceptionHandler)handlerClass.newInstance( );
                return (handler.execute(exception, config, mapping,        form,request, response));
        }
        catch (Exception e){
                throw new ServletException(e);
        }
}


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

스트럿츠 프레임워크에서는 예외 처리에 관한 환경 설정이 되어 있지 않은 경우 사용 가능한 기본 예외 처리 클래스를 포함 하고 있는데. org.apache.struts.action.ExceptionHandler가 기본 핸들러 입니다.

기본 핸들러의 execute() 메소드는 ActionError를 생성하고 적절한 scope에 저장한 다음 exception 요소의 path 속성에 할당 되어 있는 ActionForward 객체를 반환 합니다. 결국 Actionforward의 경로로 제어를 넘기게 됩니다.

예외가 발생 했을 때 다른 처리를 원한다면 exception 요소는 핸들러 클래스에 대한 오버라이드를 허용 합니다. 즉 struts-config.xml 파일에 exception 요소 안에서 handler 속성에 org.apache.struts.action.ExceptionHandler 클래스를 상속하는 클래스를 명시 함으로서 가능 합니다. Handler 클래스의 execute() 메소드를 오버라이드 함으로서 각각의 애플리케이션들은 기본 예외에서 확장된 예외 처리를 할 수 있습니다.



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

import java.util.List;
import java.util.ArrayList;
import java.io.PrintStream;
import java.io.PrintWriter;
/**
* 이 클래스는 애플리케이션 예외의 공통 슈퍼 클래스 입니다.
* 이 클래스와 이 클래스의 서브 클래스는 chained exception 기능을 제공
* chained exception 기능은 원래 문제를 이 클래스나 이 클래스의 서브 클래스로
* 감싸서 다시 실행 할 수 있습니다.
* 이 클래스는 exception을 List로 관리 함으로서 다중 예외 처리가 가능 합니다.
*/
public class BaseException extends Exception{
        protected Throwable rootCause = null;
       
        //예외를 여러 개 관리하고 나중에 ActionError를 만들 때도 반영
        private List exceptions = new ArrayList( );

        private String messageKey = null;
        private Object[] messageArgs = null;

        public BaseException( ){
                super( );
        }
       
        //생성자
        public BaseException( Throwable rootCause ) {
                this.rootCause = rootCause;
        }

        public List getExceptions( ) {
                return exceptions;
        }

        public void addException( BaseException ex ){
                exceptions.add( ex );
        }

        public void setMessageKey( String key ){
                this.messageKey = key;
        }

        public String getMessageKey( ){
                return messageKey;
        }
       
        //어떤 메시지는 아규먼트가 여러 개 일 수 있습니다.
        // 예를들면 나이는 0 ~ 99 사이의 수가 들어와야 합니다.
        public void setMessageArgs( Object[] args ){
                this.messageArgs = args;
        }

        public Object[] getMessageArgs( ){
                return messageArgs;
        }

        public void setRootCause(Throwable anException) {
                rootCause = anException;
        }

        public Throwable getRootCause( ) {
                return rootCause;
        }

        public void printStackTrace( ) {
                printStackTrace(System.err);
        }

        public void printStackTrace(PrintStream outStream) {
                printStackTrace(new PrintWriter(outStream));
        }

        public void printStackTrace(PrintWriter writer) {
                super.printStackTrace(writer);
                if ( getRootCause( ) != null ) {
                        getRootCause( ).printStackTrace(writer);
                }
                writer.flush( );
        }
}



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

아래에서 messageKey는 ActionError 클래스의 생성자에 전달되고 스트럿츠 프레임웍에서는 키와 리소스 번들의 메시지를 대응 시킵니다. 또한 클래스는 생성된 예외들을 추가 할 수 있는 객체 배열을 포함합니다.

객체 배열에 있는 예외 객체들은 MessageFormat을 기반으로 파라미터에 따라 리소스 번들의 메시지를 교환 할 수 있습니다. 번들 안에 있는 메시지는 다음과 같습니다.

global.error.invalid.price=The price must be between {0} and {1}.

아래는 기본 예외 핸들러 클래스를 확장 하고 ActionError 생성자 내부의 인자를 동적으로 생성하는 기능을 제공 합니다.

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ExceptionHandler;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionError;
import org.apache.struts.util.AppException;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.config.ExceptionConfig;
import com.oreilly.struts.framework.exceptions.BaseException;

public class SpecialExceptionHandler extends ExceptionHandler
{
        protected ActionForward execute(Exception ex,
                        ExceptionConfig config,
                        ActionMapping mapping,
                        ActionForm formInstance,
                        HttpServletRequest request,
                        HttpServletResponse response)
                                        throws ServletException {
                ActionForward forward = null;
                ActionError error = null;
                String property = null;

                /* input 속성이나 exception 요소에서 포워드할 path를 가져옴 */
                String path = null;
                if (config.getPath( ) != null) {
                        path = config.getPath( );
                }
                else{
                        path = mapping.getInput( );
                }

                // Construct the forward object
                forward = new ActionForward(path);

                /* Figure out what type of exception has been thrown.The Struts
                * AppException is not being used in this example.
                */
                if( ex instanceof BaseException) {
                        // ********* 특화된 처리 부분
                        BaseException baseException = (BaseException)ex;
                        String messageKey = baseException.getMessageKey( );
                        Object[] exArgs = baseException.getMessageArgs( );
                        if ( exArgs != null && exArgs.length > 0 ){
                        // If there were args provided, use them in the       
ActionError
                                error = new ActionError( messageKey, exArgs );
                        }
                        else{
                                // Create an ActionError without any arguments
                                error = new ActionError( messageKey );
                        }
                }
                else{
                        error = new ActionError(config.getKey( ));
                        property = error.getKey( );
                }

                // Store the ActionError into the proper scope
                // The storeException method is defined in the parent        class
                storeException(request, property, error, forward,
                config.getScope( ));
                return forward;
        }
}


스트럿츠의 예외 처리에 대해 정리해보면 Action에서 execute() 메소드를 실행 시 예외처리를 위해 try-catch로 쌉니다. 예외가 발생 했다면 RequestProcessor 클래스의 findException이 호출되어 ExceptioConfig 객체를 반환 합니다. 다음으로 getHandler() 메소드가 호출 되어 핸들러를 얻습니다. 다음으로 기본 핸들러만 정의되어 있다고 보면 핸들러 클래스의 execute() 메소드가 호출되고 여기에서 ActionError를 생성 후 적절한 scope에 저장 후 path 속성에 정의된 리소스로 제어를 넘깁니다.

 


-------------------------------
프로그램에서 오류 처리하기
-------------------------------

Action 클래스에서 예외가 발생 했을 때 만약 발생한 예외가 애플리케이션 예외 인 경우 로그를 남기고 ActionError를 생성하여 해당 스코프에 저장한 후 ActionForward를 통해 제어를 넘기는 식으로 처리 합니다.

예외의 효과적인 관리를 위해 최상위 래퍼 클래스(BaseException)를 하나 만들고 애플리케이션 예외를 모두 그 안에 두는 것 입니다. 이렇게 하면 catch 문에서 BaseException만 받아내면 될 것 입니다. (BaseException이 아니면 시스템 예외라고 가정 할 수 있으며 이렇게 처리 해야 합니다.)

시스템 예외 처리 방법은 예외를 로그로 남기고 시스템 에러 페이지를 만들어 그곳으로 포워드 시키면 됩니다.

아래는 Action안에서의 처리 입니다.

try{
        // Peform some work that may cause an application or system        exception
}
catch( BaseException ex ){
        // Log the exception
        // Create and store the action error
        ActionErrors errors = new ActionErrors( );
        ActionError newError = new ActionError( ex.getErrorCode(),ex.getArgs( ) );
        errors.add( ActionErrors.GLOBAL_ERROR, newError );
        saveErrors( request, errors );

        // Return an ActionForward for the Failure resource
        return mapping.findForward( "Failure" )
}
catch( Throwable ex ){
        // Log the exception
        // Create and store the action error
        ActionError newError = new        ActionError( "error.systemfailure" );
        ActionErrors errors = new ActionErrors( );
        errors.add( ActionErrors.GLOBAL_ERROR, newError );
        saveErrors( request, errors );
        // Return an ActionForward for the system error resource
        return mapping.findForward( IConstants.SYSTEM_FAILURE_PAGE );
}

Action마다 이렇게 한다는 것은 중복되는 코드가 발생 할 수 있는데 앞에서 설명 드린 선언적 접근 방법을 이용한다면 해결 할 수 있지만 Action의 최상위인 BaseAction을 하나 만들어 이를 해결 할 수 있습니다.

모든 action에 공통적으로 들어가야 할 기능이 있다면 (로그인 체크,접속/비 접속 체크,쇼핑 카트 등) 그것을 구현해 놓고(추상 클래스로), 다른 action들이 struts의 action을 상속받지 않고, 이 공통 action을 상속받게 합니다. 이것은 필수요소가 아니라 선택사항입니다. 공통사항이 없다면 하지 않아도 상관 없습니다.

아래에 최상위 Action에 관련된 예문이 있으니 참고 바랍니다.
 
//execute( ) method of the BaseAction(Action의 최상위 클래스로서 추상클래스 입니다.)
//아래의 경우 예외 발생시 execute 메소드의 catch에 의해 잡힙니다.
public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception {
ActionForward forwardPage = null;
        try{
                UserContainer userContainer = getUserContainer( request );
                // 이부분에 필요하다면 모든 액션들이 공통으로 확인해야 되는 사항이
                //있다면 처리 합니다.(로그인 여부, 장바구니 확인 등)

        // 별도로 선언된 executeAction을 실행 시킵니다.
        // executeAction은 서브 액션의 입맛에 맞게 적절히 구현해서 사용 합니다.
        //예를들면 게시판 기능이라면 게시물을 읽는 기능, 쓰는 기능, 삭제 기능, 수정 기능 등이  될 수 있습니다.
                forwardPage = executeAction(mapping, form, request,        response, userContainer);
        }
        //아래의 catch문이 모든 Action에 있어야 하는 겁니다.
        catch (BaseException ex){
                // Log the application exception using your logging        framework
                // Call the generic exception handler routine
                forwardPage = processExceptions( request, mapping,        ex );
        }catch (Throwable ex){
                // Log the system exception using your logging framework
                // Make the exception available to the system error page
                request.setAttribute( Action.EXCEPTION_KEY, ex );

                // Treat all other exceptions as system errors
                forwardPage =mapping.findForward( IConstants.SYSTEM_FAILURE_KEY );
        }
        return forwardPage;
}

//추상메소드로 선언하고 이 최상위 액션을 상속 받는 하위 액션들의 입맛에 맞게 구현토록 합니다.
abstract public ActionForward executeAction( ActionMapping mapping,
                                                                                        ActionForm form,
                                                                                        HttpServletRequest request,
                                                                                        HttpServletResponse response,
                                                                                        UserContainer userContainer )
throws BaseException;


다음은 execute() 메소드에서 예외가 발생 되었을 때 이것을 처리하기 위한 BaseAction의processException() 메소드를 보도록 합니다.

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

Action안에 정의 되어 있습니다. 이 메소드는 여러 개일지 모르는 예외를 찾아 예외의 수 만큼 processBaseException 이라는 메소드를 다시 불러 그곳에서 ActionError등에 저장 하는 기능 등을 수행하도록 합니다.

protected ActionForward processExceptions( HttpServletRequest request,
                                        ActionMapping mapping,
                                        BaseException ex )
{
        ActionErrors errors = new ActionErrors( );
        ActionForward forward = null;

        // 사용자의 지역 설정을 가지고 옵니다.
        Locale locale = getUserContainer( request ).getLocale( );
        if (locale == null){
                        // 지역이 설정되지 않았다면 기본 지역을 사용
                        environment locale = Locale.getDefault( );
        }

        processBaseException(errors, (FieldException) ex, locale);

        // 입력된 리소스와 failure 포워드를 반환 합니다.
        String inputStr = mapping.getInput( );
        String failureForward = mapping.findForward(IConstants.FAILURE_KEY);

        if ( inputStr != null) {
                forward = new ActionForward( inputStr );
        }
        else if (failureForward != null){
                forward = failureForward;
        }

        // 예외가 하위 예외를 포함하고 있는지 확인
        List exceptions = ex.getExceptions( );

        if (exceptions != null && !exceptions.isEmpty( ) ){
                int size = exceptions.size( );
                Iterator iter = exceptions.iterator( );

                while( iter.hasNext( ) ){
                        // 모든 하위예외들은 BaseException이어야 합니다.
                        BaseException subException =(BaseException)iter.next( );
                        processBaseException(errors, subException, locale);
                }
        }

        // Tell the Struts framework to save the errors into the request
        saveErrors( request, errors );

        // Return the ActionForward
        return forward;
}


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

processException 메소드의 수행 과정은 다음과 같습니다.

1.        사용자의 지역 확인
2.        Top레벨 예외의 processBaseException() 메소드를 수행
3.        다른 서브 예외가 있다면 각각의 예외를 수행
4.        생성한 모든 ActionError를 저장
5.        제어를 input 속성에 있는 리소스나 액션에 설정된 “Failure” Actionforward에 넘김


아래는 BaseAction의 processBaseException 메소드 입니다.


protected void processBaseException( ActionErrors errors,
                                                                        BaseException ex,
                                                                        Locale locale)
{

        // 추가될 ActionError의 레퍼런스 저장
        ActionError newActionError = null;

        // 에러 코드는 리소스 번들의 키값
        String errorCode = ex.getMessageKey( );

        /*MessageFormat 객체가 사용하는 추가적인 인자가 있다면
        * args에 예외를 추가
        */
        Object[] args = ex.getMessageArgs( );

       
        // ACtionError 클래스의 인스턴스 생성자
        if ( args != null && args.length > 0 ){
                // Use the arguments that were provided in the exception
                newActionError = new ActionError( errorCode, args );
        }
        else{
                newActionError = new ActionError( errorCode );
        }

        errors.add( ActionErrors.GLOBAL_ERROR, newActionError );

[오라클자바닷넷강의, ORACLEJAVA]스트럿츠에서의 예외처리

Struts에서의 예외처리 방법입니다. 참고하세요

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

자바의 예외는 애플리케이션에서 비정상적인 상황이 발생 할 때 생성되는 객체 입니다. 자바에서 예외가 발생하면 java.lang.Throwable  객체를 상속한 객체를 생성하는 것입니다. Throwable 아래에는 java.lang.Error와 java.lang.Exception등이 있습니다.

 

일반적으로 Exception의 경우 Application에서 처리 가능한 예외이며 스트럿츠에서의 모든 예외는 Exception 클래스의 서브 클래스로 생성하고 발생해야 합니다.

Exception을 제외한 Error 부분은 심각한 문제들을 위해 예약되어 있습니다. 예를 들어 애플리케이션에서 사용 할 시스템 메모리가 부족한 에러 등이 해당 합니다. 그러므로 일반적으로 Error클래스의 서브 클래스의 경우는 애플리케이션에서 예외를 처리하기는 어려우며 대부분 JVM 자체에서 Error또는 Error클래스의 서브 클래스의 인스턴스를 발생 시킵니다.

JVM은 각 스레드의 호출 순서를 추적하는데 사용하기 위해 호출 스택(Call Stack)이라고 부르는 메소드 호출 스택(Method Invocation Stack)을 사용 합니다. main()에서부터 출발하여 각각의 메소드가 호출 될 때 마다 메소드 호출 스택의 상단에 추가되고 새롭게 추가된 메소드 스택이 현재 실행할 메소드가 되는 것 이며 각 메소드 필드 상태는 해당하는 스택 프레임에 저장됩니다.

JVM은 자바 메소드가 정상적으로 종료하면 최상단의 현재 메소드의 스택 프레임을 꺼내고 다음 스택 프레임을 실행 합니다. 그러나 예외가 발생 한다면 예외 핸들러를 찾는데 우선 현재 메소드에서 try-catch 구문이 있는지 확인을 합니다. 만약 현재 예외가 발생 한 곳에 try-catch 구문이 없다면 JVM은 발생한 예외 혹은 그 예외의 상위 예외를 처리하는 구문을 찾을 때 까지 호출 스택에서 메소드 프레임을 하나씩 꺼냅니다.

만약 JVM이 모든 스택 프레임을 꺼냈는데도 해당 예외를 처리하는 구문이 없을 경우 예외가 발생 한 쓰레드는 종료하게 됩니다. 만약 종료한 쓰레드가 메인 쓰레드이고 다른 비데몬 쓰레드가 없다면 애플리케이션 자체가 종료하게 됩니다.

이와는 달리 JVM이 예외를 처리하는 구문을 만난다면 그 구문이 있는 스택 프레임을 스택의 맨 위에 위치 시키고 다시 실행을 재개 하게 됩니다.

 




--------------------------
Checked와 Unchecked
--------------------------

자바의 예외는 checked 예외와 unchecked 예외로 구분해 볼 수 있습니다. Checked 예외는 클라이언트가 반드시 처리해야 하는 것이며 이에 대한 처리를 위해 메소드에서는 try-catch로 처리하거나 throws을 이용하여 예외를 던져 버려야 합니다.

JVM은 컴파일 시 checked 예외를 검사하지만 unchecked 예외에 대해서는 무시 합니다. Unchecked 예외로는 java.lang.ClassCastException등과 같은 예외가 있는데 일반적으로 부정확한 로직이나 프로그래밍의 오류로 인해 발생 되는 오류들 입니다.

또한 checked와 unchecked 예외는 예외 계층에서의 위치로도 결정 되는데 RuntimeException의 서브 클래스를 제외한 java.lang.Exception 클래스의 자식 클래스는 모두 checked 예외 입니다. 즉 이 예외는 try-catch로 처리 하든지 아니면 throw 절에 의해 처리되는 것이 보장 되어야 합니다.

Runtime 클래스와 그 자식 예외들은 unchecked 예외인데 이 예외는 try-catch 또는 throws 절에 위해 처리 되지 않아도 프로그램은 컴파일 되고 수행이 됩니다. 그러므로  unchecked라고 하는 겁니다.

보통 자바에서 try-carch문을 이용하는 것은 애플리케이션의 성능에 큰 영향을 주지 않습니다. 실제 예외가 발생 했을 때만  영향을 미치는데 이러한 이유는 JVM이 예외를 처리할 핸들러를 찾기 때문 입니다. 만약 예외를 처리 할 catch 문이 예외가 발생 한 메소드안에 있으면 성능에는 문제가 없지만 예외를 처리하기 위해 아래의 스택 프레임을 뒤진다면 성능에 영향을 줄 수 있습니다.

따라서 try-catch문은 오류에 대한 처리 조건으로 이용되어야 하며 프로그램의 흐름을 컨트롤 하기 위해서 사용 되어져서는 안됩니다. 아래는 잘못 사용된 예 입니다.

Double basePrice = null;
String basePriceStr =request.getParameter( "BASE_PRICE_AMOUNT" );

// Use a try/catch to make sure the value is a number
try{
basePrice = Double.valueOf( basePriceStr );
}
catch( NumberFormatException ex )
{
// The value could not be converted to a valid Double; set the default
basePrice = ApplicationDefaults.DEFAULT_BASE_PRICE;
}


--------------------------
Chained 예외 사용하기
--------------------------

때에 따라서는 특정 타입의 예외를 catch한 후 다른 유형의 예외를 발생하는 경우가 있습니다. 예를 들어 스트럿츠에서 애플리케이션의 Action 클래스를 호출해서 데이터베이스에 이미지를 저장 하는 경우라고 했을 때 Action 클래스에서는 다음과 같은 update  메소드를 호출 합니다.

public void updateImageFile( String imagePath ) throws UploadException;

메소드를 호출하면 이미지 파일을 업로드 하고 예외가 발생하면 UploadException이 발생 합니다. 에러가 발생하는 실제 오류를 보면 데이터베이스에 저장 공간이 없을 수도 있고 여러 가지 오류의 경우가 나올 수 있습니다. 아마도 최초 발생 하는 예외는 IOException이나 SQLException등이 될 것 입니다.

그러나 사용자는 이 레벨의 오류를 알 필요가 없습니다. 단지 필요한 것은 이미지의 업로드기 실패 했다는 것이 됩니다. 이런 경우 추후 개발자가 확인을 위해 시스템에 로깅을 통해 SQLExceptio이나 IOException은 기록을 하고 사용자에게는 “입력 실패 입니다”와 같은 오류 메시지를 보여 주어야 할 것 입니다.

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

Example 10-1. An exception class that supports chained exceptions
import java.io.PrintStream;
import java.io.PrintWriter;
/**
* 이 클래스는 애플리케이션 예외의 슈퍼 클래스 입니다.
* 이 클래스와 이 클래스의 서브 클래스는 chained 예외 기능을 제공 합니다.
* chained 예외기능 이란 원래의 문제를 이 클래스나 이 클래스의 서브
* 클래스로 감싸서 다시 예외를 발생 시키는 것 입니다.
*/
public class BaseException extends Exception {
        protected Throwable rootCause = null;
        protected BaseException( Throwable rootCause ) {
                this.rootCause = rootCause;
        }

        public void setRootCause(Throwable anException) {
                rootCause = anException;
        }

        public Throwable getRootCause( ) {
                return rootCause;
        }

        public void printStackTrace( ) {
                printStackTrace(System.err);
        }

        public void printStackTrace(PrintStream outStream) {
                printStackTrace(new PrintWriter(outStream));
        }

        public void printStackTrace(PrintWriter writer) {
                super.printStackTrace(writer);
                if ( getRootCause( ) != null ) {
                        getRootCause( ).printStackTrace(writer);
                }
                writer.flush( );
        }
}

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

위 예제는 원래의 Throwable을 감싸고 있으며 이러한 경우의 장점은 저 수준 예외에 대한 자세한 부분들을 추상화 할 수 있다는 것입니다. 동시에 예외의 자세한 사항을 로그에 기록하고 게발자가 사용 할 수 있도록 할 수 있습니다. 이러한 예외들을 계속 연결 할 수 있기 때문에 chained 예외라고 합니다.

“exception chaining”은 JDBC같은 저 수준의 오류를 사용자에게 전달하는 것을 막을 수 있습니다.


----------------------------
다중 예외
----------------------------

한 메소드에서 여러 예외가 발생 한다는 개념으로 “exception chaining”을 약간 변형 한 것입니다.

인터넷을 통해 회원가입을 하려고 합니다. 비밀번호와 비밀번호 확인이 잘못 되었으며 주소도 입력하지 않았고 전화번호도 기입하지 않았습니다. 이 경우 여러 항목들을 입력하고 “저장” 버튼을 누르면 오류가 차례차례로 하나씩 나타나 사용자를 불편하게 할 것입니다.

닷넷인 경우 Validation Check를 위한 객체를 지원하여 이러한 부분이 해결 가능 하지만 자바에서는 기본적으로 지원하지 않습니다. 불행이도 자바에서는 오직 하나의 Throwable만 던질 수 있습니다.

다중 예외를 처리하는 한가지 방법은 예외 클래스가 다른 예외들의 컬렉션을 지원하는 기본 예외를 갖도록 하는 것입니다. 아래의 예문에서는 메소드가 실행 하는 동안 예외가 하나 이산 발생 하면 추가적인 예외들을 추가하여 클라이언트에 반환 합니다.

import java.util.List;
import java.util.ArrayList;
import java.io.PrintStream;
import java.io.PrintWriter;
/**
* exceptions라는 인스턴스 변수에서 여러 예외를 지원 합니다.
*/
public class BaseException extends Exception{
        protected Throwable rootCause = null;
        private List exceptions = new ArrayList( );

        public BaseException( ){
                super( );
        }

        public BaseException( Throwable rootCause ) {
                this.rootCause = rootCause;
        }

        public List getExceptions( ) {
                return exceptions;
       

        public void addException( BaseException ex ){
                exceptions.add( ex );
        }

        public void setRootCause(Throwable anException) {
                rootCause = anException;
        }

        public Throwable getRootCause( ) {
                return rootCause;
        }

        public void printStackTrace( ) {
                printStackTrace(System.err);
        }

        public void printStackTrace(PrintStream outStream) {
                printStackTrace(new PrintWriter(outStream));
        }

        public void printStackTrace(PrintWriter writer) {
                super.printStackTrace(writer);

                if ( getRootCause( ) != null ) {
                        getRootCause( ).printStackTrace(writer);
                }
                writer.flush( );
        }

[오라클자바,자바교육,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월 4일 일요일

재귀호출을 이용한 팩토리얼 구하기

재귀호출을 이용한 팩토리얼 구하기

 class RecursionTest {
  long factorial(int value) {
  if(value <= 1) return 1L;
  return value*factorial(value-1);
  }
  public static void main(String[] args) {
  if (args.length<1) {
  System.out.println("Usage : java RecursionTest number ");
  System.exit(1);
  }
                                    int value = Integer.parseInt(args[0]);
  RecursionTest r = new RecursionTest();
  long fact = r.factorial(value);
  System.out.println(value + "! = " + fact);
  }