728x90
728x90

안드로이드 레이아웃

 

레이아웃은 ViewGroup 클래스로부터 상속된다. 아래는 레이아웃 안에서 자주 사용되는 속성이다.

* orientation : 배치할 위젯의 방향 설정. (수직(Vertical)/수평(Horiwontal) 중 설정). 
* gravity : 위젯의 정렬 방향 설정 (좌, 우, 중앙). 중력의 시작점
* padding :  위젯의 여백
* layout_weight : 레이아웃이 전체 화면에서 차지하는 공간의 가중 값. 여러 레이아웃이 중복될 때 사용
* baselineAligned : 보기 좋게 정렬. true / false

 

안드로이드 레이아웃 종류

 

1) 리니어 (LinearLayout) : 가장 많이 사용. 왼쪽 위부터 아래쪽 또는 오른쪽으로 차례로 배치

2) 렐러티브** : 관계적 레이아웃. 위젯 자신이 속한 레이아웃의 상하좌우 위치를 지정.

3) 테이블 : span 기능이 없다.

4) 그리드 : 그리드레이아웃은 웹(html)의 테이블 개념과 가깝다.

5) 프레임 : 왼쪽 위에 일률적으로 겹쳐 배치, 중복된 것 처럼 보인다.

 

 

1. 리니어레이아웃의 속성들

 

orientation, gravity, layout_gravity

android:orientation="vertical"
android:gravity="right:bottom"
android:layout_gravity="center"

 

baselineAligned : 크기가 다른 위젯들을 보기 좋게 정렬하며 true, false 값을 가진다.

 

중복 리니어레이아웃으로 LinearLayout 안에 LinearLayout들을 가질 수 있다.

layout_weight: 리니어 레이아웃이 여러개일때 가중치로 각 레이아웃의 크기를 지정한다. (1:1:1) 비율로 생각하면 편함
LinearLayout, gridLayout일 때만 먹히는 속성이다. relative는 먹지 않는다.

android:layout_weight="1"
android:layout_weight="1"
android:layout_weight="1"

 

 

 

2. 렐러티브레이아웃

상대레이아웃은 레이아웃 내부에 포함된 위젯들을 상대적인 위치로 배치한다.
부모(레이아웃)이 기준이 될 수도 있고 뷰가 기준이 될 수도 있다.

layout_alignParentLeft
layout_alignParentRight
layout_alignParentTop
layout_alignParentBottom
layout_centerVertical
layout_centerHorizontal

 

다른 위젯의 상대 위치에 배치할 때는 다른 위젯에 id를 지정해서 사용

 @+id/기준 위젯의 아이디

 

 

 

3. 테이블레이아웃

좌우로 합치는 것만 된다. row개념으로 생각하면 된다. <TableRow> 태그를 사용하는데 이 개수가 행의 개수가 된다. 열의 개수는 이 안에 포함된 위젯의 개수로 결정. 첫 번째 셀은 0부터 시작

layout_column : 지정된 열에 현재 위젯 표시
stretchColumns : 지정된 열의 폭을 늘린다.
stretchColumns = "*" : 각 셀을 같은 크기로 확장, 전체화면 꽉 채움

 

 

 

4. 그리드레이아웃


위젯을 표 형태로 배치할 때 사용. 

rowCount 행 개수
columnCount 열 개수
orientation : 방향 우선
layout_row : 자신이 위치할 행 번호 (0부터 시작)
layout_column : 자신이 위치할 열 번호 (0부터)
layout_rowSpan : 행을 지정된 개수만큼 확장
layout_columnSpan : 열을 지정된 개수만큼 확장
layout_gravity : fill, fill_vertical, foll_horizontal. 셀 확장 시 위젯을 확장된 셀에 꽉 채우는 효과

 

 

 

5. 프레임레이아웃

탭 위젯 등과 혼용해 사용할 때 유용. html의 z-index처럼 순서를 잘 조절해서 사용한다. visibility를 이용해서 조절한다.
개발에서 까다로운 편이다.

foreground : 전경 이미지
foregroundGravity : 전경 이미지의 위치

 


 

문제풀기

5-1 리니어레이아웃으로 다음 화면을 구성하는 XML을 작성하라.

* orientation : vertical
* button은 총 3개이며 layout_width : 110dp, layout_height:100dp
* 각각 중앙, 좌측, 우측 배열을 설정한다.
* button에 gravity와 layout_gravity(부모 기준)를 모두 설정한다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
              
    <Button android:layout_width="110dp"
            android:layout_height="100dp"
            android:text="버튼1"
            android:layout_gravity="center"
            android:gravity="right|top"
    />
    <Button android:layout_width="110dp"
            android:layout_height="100dp"
            android:gravity="left|center"
            android:text="버튼2"
    />
    <Button android:layout_width="110dp"
            android:layout_height="100dp"
            android:text="버튼3"
            android:layout_gravity="end"
			android:gravity="right|bottom"
    />
</LinearLayout>

 

 

5-2 리니어레이아웃으로 다음 화면을 구성하는 XML을 작성하라. 단 레이아웃은 구분되어 보이도록 서로 다른색으로 하며 레이아웃 안에 다시 레이아웃을 중첩해도 된다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">
    <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1">
        <LinearLayout
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:background="#00bb00"
                android:layout_weight="1"
                >
        </LinearLayout>
        <LinearLayout
                android:orientation="vertical"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1">
            <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                android:background="#000000"
                android:layout_weight="1">
            </LinearLayout>
            <LinearLayout
                    android:orientation="vertical"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                android:background="#dddddd"
                android:layout_weight="1">
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
    
    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#00FF00">
    </LinearLayout>
</LinearLayout>

 

 

5-3 버튼을 클릭하면 토스트 메시지가 출력되는 화면을 자바로 코딩해보자.
* XML 없이 자바로만 화면 코딩 (추천하지는 않으나 할 줄은 알아야 한다.)

프로젝트명 : Project5_1
패키지명 : com.cookandroid.project5-1
토스트 메세지 내용 : 코드로 생성한 버튼입니다.

 

MainActivity.java

package com.example.project5_1;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);

        LinearLayout baseLayout = new LinearLayout(this);
        baseLayout.setOrientation(LinearLayout.VERTICAL);
        baseLayout.setBackgroundColor(Color.rgb(0,255,0));
        setContentView(baseLayout,params);

        Button btn = new Button(this);
        btn.setText("버튼입니다");
        btn.setBackgroundColor(Color.MAGENTA);
        baseLayout.addView(btn);

        btn.setOnClickListener(new View.OnClickListener(){
            public void onClick(View arg0){
                Toast.makeText(getApplicationContext(),
                        "코드로 생성한 버튼입니다",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

5-4 다음 화면을 XML파일 없이 Java 코드만 이용하여 완성하라. 레이아웃에는 에디트텍스트 1개와 버튼 1개, 텍스트뷰 1개를 생성한다. 버튼을 클릭하면 에디트텍스트에 써진 문자열이 텍스트뷰에 나타나도록 한다.

MainActivity.java

package com.example.project5_1;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView tv;  //멤버. 그래야 안에서 쓸 수 있다
    EditText et;

    @Override
    //전역(final:어디서든 부를 수 있다), 지역
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);

        LinearLayout baseLayout = new LinearLayout(this);
        baseLayout.setOrientation(LinearLayout.VERTICAL);
        setContentView(baseLayout, params);

        et = new EditText(this);
        et.setHint("값을 입력하세요");
        baseLayout.addView(et);

        tv = new TextView(this);
        baseLayout.addView(tv);

        Button btn = new Button(this);
        btn.setText("버튼입니다");
        btn.setBackgroundColor(Color.YELLOW);
        baseLayout.addView(btn);

        btn.setOnClickListener(new View.OnClickListener(){
            public void onClick(View argo){
                tv.setText(et.getText().toString());
            }
        });

    }
}

 

 

5-5 다음 화면의 XML 코드를 중복 리니어레이아웃과 렐러티브레이아웃으로 각각 작성해보자. 텍스트뷰 1개, 에디트텍스트 1개, 버튼 2개로 구성한다.

<?xml version="1.0" encoding="UTF-8"?>

	<LinearLayout tools:context=".MainActivity" 
    	android:orientation="vertical" 
        android:layout_height="match_parent" 
        android:layout_width="match_parent" 
        xmlns:tools="http://schemas.android.com/tools" 
        xmlns:app="http://schemas.android.com/apk/res-auto" 
        xmlns:android="http://schemas.android.com/apk/res/android">
		
        <LinearLayout 
    		android:orientation="horizontal" 
       	 	android:layout_height="wrap_content" 
        	android:layout_width="match_parent">

		<TextView 
			android:layout_height="wrap_content" 
   			android:layout_width="wrap_content"
   			android:textSize="30sp" 
    		android:text="전화번호:"/>

		<EditText 
			android:layout_height="wrap_content" 
  		  	android:layout_width="match_parent" 
  		  	android:text="000-0000-0000"/>

		</LinearLayout>

        <LinearLayout 
            android:orientation="horizontal" 
            android:layout_height="wrap_content" 
            android:layout_width="match_parent" 
            android:gravity="right">

            <Button 
                android:layout_height="wrap_content" 
                android:layout_width="wrap_content" 
                android:text="입력"/>

            <Button 
                android:layout_height="wrap_content" 
                android:layout_width="wrap_content" 
                android:text="취소"/>

        </LinearLayout>

	</LinearLayout>
<?xml version="1.0" encoding="UTF-8"?>

	<RelativeLayout 
        android:layout_height="match_parent" 
        android:layout_width="match_parent" 
        xmlns:android="http://schemas.android.com/apk/res/android">

        <TextView 
            android:layout_height="wrap_content" 
            android:layout_width="wrap_content" 
            android:textSize="30sp" 
            android:text="전화번호" 
            android:id="@+id/tv1"/>

        <EditText 
            android:layout_height="wrap_content" 
            android:layout_width="match_parent" 
            android:hint="000-0000-0000" 
            android:layout_toRightOf="@+id/tv1"/>

        <Button 
            android:layout_height="wrap_content" 
            android:layout_width="wrap_content" 
            android:text="취소" 
            android:id="@+id/btn1" 
            android:layout_alignParentRight="true" 
            android:layout_below="@+id/tv1"/>

        <Button 
            android:layout_height="wrap_content" 
            android:layout_width="wrap_content" 
            android:text="확인" 
            android:layout_alignBaseline="@+id/btn1" 
            android:layout_toLeftOf="@+id/btn1"/>

	</RelativeLayout>

 

 

 

5-6 테이블레이아웃을 활용하여 숫자 버튼까지 있는 계산기를 만들어보자.

프로젝트명 :Project5_2
패키지명 :com.cookandroid.project5-2
TableLayout (1) TableRow (9) EditText(2) 숫자Button(10) 연산 Button(4) TextView(1)
연산 버튼 위젯에 layout_margin 재량껏 지정하며 결과를 보여줄 TextView 는 빨간색상, 글자 크기는 20dp 지정하며 각 위젯의 id는 차례로 Edit1, Edit2, BtnNum0~9, BtnAdd, BtnSub, BtnMul, BtnDiv, TextResult로 지정한다.

<?xml version="1.0" encoding="UTF-8"?>

	<GridLayout 
        android:orientation="vertical" 
        android:columnCount="5" 
        android:rowCount="9" 
        android:layout_height="match_parent" 
        android:layout_width="match_parent" 
        android:id="@+id/tableLayout1" 
        xmlns:tools="http://schemas.android.com/tools" 
        xmlns:android="http://schemas.android.com/apk/res/android">

		<EditText 
            android:id="@+id/Edit1" 
            android:hint="숫자1 입력" 
            android:layout_gravity="fill_horizontal" 
            android:layout_columnSpan="5" 
            android:layout_weight="1"/>

		<EditText 
            android:id="@+id/Edit2" 
            android:hint="숫자2 입력" 
            android:layout_gravity="fill_horizontal" 
            android:layout_columnSpan="5" 
            android:layout_weight="1"/>


		<LinearLayout 
            android:layout_height="wrap_content" 
            android:layout_width="match_parent">


 		<LinearLayout 
          android:layout_height="wrap_content" 
          android:layout_width="match_parent">

            <Button 
              android:layout_height="wrap_content" 
              android:layout_width="wrap_content" 
              android:id="@+id/BtnNum5" 
              android:layout_weight="1" 
              android:text="5"/>

            <Button 
              android:layout_height="wrap_content" 
              android:layout_width="wrap_content" 
              android:id="@+id/BtnNum6" 
              android:layout_weight="1" 
              android:text="6"/>

            <Button 
                android:layout_height="wrap_content" 
                android:layout_width="wrap_content" 
                android:id="@+id/BtnNum7" 
                android:layout_weight="1" 
                android:text="7"/>

            <Button 
                android:layout_height="wrap_content" 
                android:layout_width="wrap_content" 
                android:id="@+id/BtnNum8" 
                android:layout_weight="1" 
                android:text="8"/>

            <Button 
                android:layout_height="wrap_content" 
                android:layout_width="wrap_content" 
                android:id="@+id/BtnNum9" 
                android:layout_weight="1" 
                android:text="9"/>

		</LinearLayout>

		<Button 
        	android:layout_height="wrap_content" 
            android:layout_width="wrap_content" 
            android:id="@+id/BtnAdd" 
            android:layout_gravity="fill_horizontal" 
            android:layout_columnSpan="5" 
            android:layout_weight="1" 
            android:text="더하기" 
            android:layout_margin="5dp"/>

		<Button 
        	android:layout_height="wrap_content" 
            android:layout_width="wrap_content" 
            android:id="@+id/BtnSub" 
            android:layout_gravity="fill_horizontal" 
            android:layout_columnSpan="5" 
            android:layout_weight="1" 
            android:text="빼기" 
            android:layout_margin="5dp"/>

		<Button 
        	android:layout_height="wrap_content" 
            android:layout_width="wrap_content" 
            android:id="@+id/BtnMul" 
            android:layout_gravity="fill_horizontal"
            android:layout_columnSpan="5" 
            android:layout_weight="1" 
            android:text="곱하기" 
            android:layout_margin="5dp"/>

		<Button 
        	android:layout_height="wrap_content" 
            android:layout_width="wrap_content" 
            android:id="@+id/BtnDiv" 
            android:layout_gravity="fill_horizontal" 
            android:layout_columnSpan="5" 
            android:layout_weight="1" 
            android:text="나누기" 
            android:layout_margin="5dp"/>

		<TextView 
        	android:layout_height="wrap_content" 
            android:layout_width="wrap_content" 
            android:id="@+id/TextResult" 
            android:layout_gravity="fill_horizontal" 
            android:layout_columnSpan="5" 
            android:text="계산 결과 : " 
            android:layout_margin="5dp" 
            android:textSize="20dp" 
            android:textColor="#FF0000"/>

</GridLayout>
728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

오늘은 안드로이드 개발 환경을 구축해보겠습니다.

 

 


 


안드로이드 스튜디오


 

 

 

Download Android Studio and SDK tools

developer.android.com

 

다운로드 후 설치를 진행한다.

 

 

해석하자면 Android Studio : 에디터
Virtual Device : 가상장치.
자바로 치면 JVM(가상머신)과 비슷하다. 

 

 

그대로 진행하면 끝!
finish까지 진행한 후 import할 게
있으면 시키고 진행한다.

 

 

실행하면 위치를 볼 수 있다.

 

 


항목 해석




Emulator : 가상 핸드폰과 같은 것
SDK : JDK과 비슷. 안드로이드 ADK
Platform : 운영체제
Intel x86 Emulator Accelerator : 가속기
가상폰을 만들기 위해 운영체제 안에
운영체제를 깔기 위해 하드웨어에서
가상화기능을 쓸 수 있게 열어주는 것 (설정)

 

 

짚고 넘어가면 좋은 개념

1) 플랫폼 (os) : C#
2) Framework : 플랫폼을 없애기 위해
.Net Framework만 만들려고 했었음. JVM처럼
결과적으로 좀 가벼운 플랫폼이 되어버림

 

 

Start a new Android Studio project를 눌러 새 프로젝트를 생성한다.
Check out project from~을 보면 지원은 CVS가 기본적이고 Git도 가능하다.
Configure에 AVD Manager 가상핸드폰, SDK Manager는 운영체제를 말함.




깃과 깃허브의 차이




1) Git : 로컬 컴퓨터에 버전별로 저장하는 것.
2) Github : 서버에 버전별로 커밋해 업로드하는 것.

 

 

여러 태블릿 중에 목적에 맞는 걸 선택한다.
이번에는 Empty Activity를 선택.
코틀린
은 좋은 언어이지만 과정상 자바 과정이어서
Language는 자바를 선택해서 개발할 계획.

 

 

자바 동기화 (syncing), processes running이 진행된다.
장소를 옮겨서 개발하던 프로젝트를 이어 진행할 때도
이 과정이 필요한데 자동으로 프로그램이 해 준다.

 


설치 마지막 단계에 오류가 있었다면

 

제어판 >프로그램 및 기능 > Windows 기능 켜기/끄기
들어가서 Hyper-V 옵션을 해제해줍니다.

 

 

 


개발 버전은? 9.0? 8.0?

 

 

Tools > SDK Manager 에 들어가서
너무 신 버전은 오류가 생길 수 있기에

그 아래 버전인 9.0으로 바꿔준다.
계속 ok, accept를 누르면서 진행한다.

 

 

 

 

메뉴바 > Tools > AVD Manager
Nexus S를 눌러서 파이 버전을 설치해준다.

 

 

폴더구성

1) manifest (적재) : 환경설정 부분
2) Java
3) res (자원) : resourse의 약자. 그림, 글자 등
단 오디오 등은 데이터베이스를 통해 처리한다.
* res> layout > activity_main.xml : 디자인을 하는 리소스로 가장 중요.

프로그램 구성

화면(gui) + 제어(for, if...) + 데이터
(변수 (변수처리 or 배열 or 객체 or 객체배열) DB, 파일처리 )

1) 화면 : XML로 작성한다.

 

 

 궁금할 때 우측 마우트버튼 > go to를 누르면 어디서 메소드를 상속받았는지 볼 수 있다.
사용은 import문으로 받아서 사용한다.


XML 파일 만드는 방법

 

XML

LinearLayout : element (구성요소)
orientation : property (속성), 속성값 순으로 나열된다.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

</LinearLayout>

 

 

 

728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

 

 

오늘은 jsp와 자바를 이용, 투표프로그램을 만들어 볼 것이다. 역시 텍스트편집 프로그램은 이클립스를 이용한다.

 


 

ObjectAid 플러그인 설치

이클립스 > help > install new software > (Work with) add > 아래와 같이 입력한다.
next와 약관 동의를 체크하여 설치를 마친다.

 

 

사진에서는 Contact all update sites during install to find required software
옵션이 체크되어있지만 오류가 날 경우 저 옵션을 해제해주면 문제없이 설치된다.

 

 

ObjectAid UML Explorer

 

www.objectaid.com

 

이클립스의 플러그인은 개발을 좀 더 윤택하고 편리하게 한다. 
예전에는 폴더를 찾아 직접 다운로드 했어야 했는데 지금은 그럴 필요가 없다.

 

 

ObjectAid Class Diagram 을 선택하여 생성한 후 poll 폴더 안의 자바 프로그램들을 선택하여
pollUML.ucls 문서 위로 드래그하면 자동으로 이렇게 생성된다.

 

 

프로젝트 파일과 폴더 구성은 아래와 같이 할 것이다. 자세한 코드는 아래에. 이놈이 분명 올려뒀다고 했는데 보이지 않는 경우 접은 글 기능을 이용한 것이니 클릭하면 숨겨진 내용들이 펼쳐지면서 보인다.

 

 

 


 

자바 파일 (poll 패키지)

 

1) DBConnectionMgr.java

더보기
package poll;

import java.sql.*;
import java.util.Properties;
import java.util.Vector;

public class DBConnectionMgr {
    private Vector connections = new Vector(10);
    private String _driver = "org.gjt.mm.mysql.Driver",
    _url = "jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=EUC_KR",
    _user = "root",  //각자의 아이디와 비번
    _password = "1234";
    
    private boolean _traceOn = false;
    private boolean initialized = false;
    private int _openConnections = 50;
    private static DBConnectionMgr instance = null;

    public DBConnectionMgr() {
    }

    /** Use this method to set the maximum number of open connections before
     unused connections are closed.
     */
     
    public static DBConnectionMgr getInstance() {
        if (instance == null) {
            synchronized (DBConnectionMgr.class) {
                if (instance == null) {
                    instance = new DBConnectionMgr();
                }
            }
        }

        return instance;
    }

    public void setOpenConnectionCount(int count) {
        _openConnections = count;
    }


    public void setEnableTrace(boolean enable) {
        _traceOn = enable;
    }


    /** Returns a Vector of java.sql.Connection objects */
    public Vector getConnectionList() {
        return connections;
    }


    /** Opens specified "count" of connections and adds them to the existing pool */
    public synchronized void setInitOpenConnections(int count)
            throws SQLException {
        Connection c = null;
        ConnectionObject co = null;

        for (int i = 0; i < count; i++) {
            c = createConnection();
            co = new ConnectionObject(c, false);

            connections.addElement(co);
            trace("ConnectionPoolManager: Adding new DB connection to pool (" + connections.size() + ")");
        }
    }


    /** Returns a count of open connections */
    public int getConnectionCount() {
        return connections.size();
    }


    /** Returns an unused existing or new connection.  */
    public synchronized Connection getConnection()
            throws Exception {
        if (!initialized) {
            Class c = Class.forName(_driver);
            DriverManager.registerDriver((Driver) c.newInstance());

            initialized = true;
        }


        Connection c = null;
        ConnectionObject co = null;
        boolean badConnection = false;


        for (int i = 0; i < connections.size(); i++) {
            co = (ConnectionObject) connections.elementAt(i);

            // If connection is not in use, test to ensure it's still valid!
            if (!co.inUse) {
                try {
                    badConnection = co.connection.isClosed();
                    if (!badConnection)
                        badConnection = (co.connection.getWarnings() != null);
                } catch (Exception e) {
                    badConnection = true;
                    e.printStackTrace();
                }

                // Connection is bad, remove from pool
                if (badConnection) {
                    connections.removeElementAt(i);
                    trace("ConnectionPoolManager: Remove disconnected DB connection #" + i);
                    continue;
                }

                c = co.connection;
                co.inUse = true;

                trace("ConnectionPoolManager: Using existing DB connection #" + (i + 1));
                break;
            }
        }

        if (c == null) {
            c = createConnection();
            co = new ConnectionObject(c, true);
            connections.addElement(co);

            trace("ConnectionPoolManager: Creating new DB connection #" + connections.size());
        }

        return c;
    }


    /** Marks a flag in the ConnectionObject to indicate this connection is no longer in use */
    public synchronized void freeConnection(Connection c) {
        if (c == null)
            return;

        ConnectionObject co = null;

        for (int i = 0; i < connections.size(); i++) {
            co = (ConnectionObject) connections.elementAt(i);
            if (c == co.connection) {
                co.inUse = false;
                break;
            }
        }

        for (int i = 0; i < connections.size(); i++) {
            co = (ConnectionObject) connections.elementAt(i);
            if ((i + 1) > _openConnections && !co.inUse)
                removeConnection(co.connection);
        }
    }

    public void freeConnection(Connection c, PreparedStatement p, ResultSet r) {
        try {
            if (r != null) r.close();
            if (p != null) p.close();
            freeConnection(c);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void freeConnection(Connection c, Statement s, ResultSet r) {
        try {
            if (r != null) r.close();
            if (s != null) s.close();
            freeConnection(c);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void freeConnection(Connection c, PreparedStatement p) {
        try {
            if (p != null) p.close();
            freeConnection(c);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void freeConnection(Connection c, Statement s) {
        try {
            if (s != null) s.close();
            freeConnection(c);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /** Marks a flag in the ConnectionObject to indicate this connection is no longer in use */
    public synchronized void removeConnection(Connection c) {
        if (c == null)
            return;

        ConnectionObject co = null;
        for (int i = 0; i < connections.size(); i++) {
            co = (ConnectionObject) connections.elementAt(i);
            if (c == co.connection) {
                try {
                    c.close();
                    connections.removeElementAt(i);
                    trace("Removed " + c.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            }
        }
    }


    private Connection createConnection()
            throws SQLException {
        Connection con = null;

        try {
            if (_user == null)
                _user = "";
            if (_password == null)
                _password = "";

            Properties props = new Properties();
            props.put("user", _user);
            props.put("password", _password);

            con = DriverManager.getConnection(_url, props);
        } catch (Throwable t) {
            throw new SQLException(t.getMessage());
        }

        return con;
    }


    /** Closes all connections and clears out the connection pool */
    public void releaseFreeConnections() {
        trace("ConnectionPoolManager.releaseFreeConnections()");

        Connection c = null;
        ConnectionObject co = null;

        for (int i = 0; i < connections.size(); i++) {
            co = (ConnectionObject) connections.elementAt(i);
            if (!co.inUse)
                removeConnection(co.connection);
        }
    }


    /** Closes all connections and clears out the connection pool */
    public void finalize() {
        trace("ConnectionPoolManager.finalize()");

        Connection c = null;
        ConnectionObject co = null;

        for (int i = 0; i < connections.size(); i++) {
            co = (ConnectionObject) connections.elementAt(i);
            try {
                co.connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            co = null;
        }

        connections.removeAllElements();
    }


    private void trace(String s) {
        if (_traceOn)
            System.err.println(s);
    }

}


class ConnectionObject {
    public java.sql.Connection connection = null;
    public boolean inUse = false;

    public ConnectionObject(Connection c, boolean useFlag) {
        connection = c;
        inUse = useFlag;
    }
}

 

 

 

2) 빈즈 파일

더보기

PollItemBean

package poll;

public class PollItemBean {
	private int listnum;
	private int itemnum;
	private String [] item;
	private int count;
	
	public int getListnum() {
		return listnum;
	}
	public void setListnum(int listnum) {
		this.listnum = listnum;
	}
	public int getItemnum() {
		return itemnum;
	}
	public void setItemnum(int itemnum) {
		this.itemnum = itemnum;
	}
	public String[] getItem() {
		return item;
	}
	public void setItem(String[] item) {
		this.item = item;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
}

 

 

PollListBean

package poll;

public class PollListBean {
	private int num;
	private String question;
	private String sdate;
	private String edate;
	private String wdate;
	private int type;
	private int active;
	
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public String getQuestion() {
		return question;
	}
	public void setQuestion(String question) {
		this.question = question;
	}
	public String getSdate() {
		return sdate;
	}
	public void setSdate(String sdate) {
		this.sdate = sdate;
	}
	public String getEdate() {
		return edate;
	}
	public void setEdate(String edate) {
		this.edate = edate;
	}
	public String getWdate() {
		return wdate;
	}
	public void setWdate(String wdate) {
		this.wdate = wdate;
	}
	public int getType() {
		return type;
	}
	public void setType(int type) {
		this.type = type;
	}
	public int getActive() {
		return active;
	}
	public void setActive(int active) {
		this.active = active;
	}
}

 

 

PollMgr.java

package poll;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;

import com.sun.org.apache.bcel.internal.generic.LSTORE;

public class PollMgr {

	private DBConnectionMgr pool;

	public PollMgr() {
		// single-tone pattern. 싱글톤패턴은 private이다.
		pool = DBConnectionMgr.getInstance();
		// math의 메소드는 all static이다. getInstance도 그렇다
	}

	// Max Num
	public int getMaxNum() {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		int maxNum = 0;

		try {
			con = pool.getConnection();
			sql = " select max(num) from tblPollList ";
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if (rs.next())
				maxNum = rs.getInt(1);
			// num이 넘어오지 않으면 가장 최신의 num값을 리턴한다.
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return maxNum;
	}

	// Poll Insert(설문작성)
	public boolean insertPoll(PollListBean plBean, PollItemBean piBean) {
		Connection con = null;
		PreparedStatement pstmt = null;
		String sql = null;
		boolean flag = false;
		try {
			con = pool.getConnection();
			sql = "insert tblPollList(question, sdate, edate, wdate, type) "
					+ "values(?,?,?,now(),?)";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, plBean.getQuestion());
			pstmt.setString(2, plBean.getSdate());
			pstmt.setString(3, plBean.getEdate());
			pstmt.setInt(4, plBean.getType());  //1:복수, 0:단일
			int cnt = pstmt.executeUpdate(); 
			if(cnt==1) { //save
				sql = "insert tblPollItem values(?,?,?,0)";
				pstmt = con.prepareStatement(sql);
				String item[] = piBean.getItem();
				int listNum = getMaxNum();	
				int j = 0;
				for (int i = 0; i < item.length; i++) {
					//space
					if(item[i]==null||item[i].trim().equals(""))
						break;
					pstmt.setInt(1, listNum);
					pstmt.setInt(2, i);
					pstmt.setString(3, item[i]);
					j = pstmt.executeUpdate();
				}//--for
				if(j==1) 
					flag=true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt);
		}
		return flag;
	}

	// Poll All List : Y (벡터)
	public Vector<PollListBean> getAllList() {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		Vector<PollListBean> vlist = new Vector<>();
		try {
			con = pool.getConnection();
			sql = "select * from tblPollList order by num desc";
			pstmt = con.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				PollListBean plBean = new PollListBean();
				plBean.setNum(rs.getInt("num"));
				plBean.setQuestion(rs.getString("question"));
				plBean.setSdate(rs.getString("sdate"));
				plBean.setEdate(rs.getString("edate"));
				vlist.addElement(plBean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return vlist;
	}

	// Sum Count (총 투표한 수)
	public int sumCount(int listNum) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		int sum = 0;
		try {
			con = pool.getConnection();
			sql = "select sum(count) from tblPollItem where listnum=?";
			pstmt = con.prepareStatement(sql);
			if(listNum==0)
				listNum = getMaxNum();  //가장 최신의 설문
			pstmt.setInt(1, listNum);
			rs = pstmt.executeQuery();
			if(rs.next())
				sum = rs.getInt(1);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return sum;
	}

	// Poll Read (설문 읽어오기) : 하나의 설문을 가져온다
	public PollListBean getPollRead(int num) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		PollListBean plBean = new PollListBean();
		try {
			con = pool.getConnection();
			sql = "select * from tblPollList where num = ?";
			pstmt = con.prepareStatement(sql);
			if(num==0) 
				num = getMaxNum();
			pstmt.setInt(1, num);
			rs = pstmt.executeQuery();
			if(rs.next()) {
				plBean.setNum(rs.getInt("num"));
				plBean.setQuestion(rs.getString("question"));
				plBean.setType(rs.getInt("type"));
				plBean.setActive(rs.getInt("active"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return plBean;
	}

	// Poll Item List : Y (표의 설문항목, num, count값 벡터로 리턴)
	public Vector<String> getItem(int listNum) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		Vector<String> vlist = new Vector<>();
		try {
			con = pool.getConnection();
			sql = "select item from tblPollItem " + "where listNum = ?";
			pstmt = con.prepareStatement(sql);
			if (listNum == 0)
				listNum = getMaxNum();
				System.out.print("리스트넘:"+listNum);
			pstmt.setInt(1, listNum);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				/*
				 * String item = rs.getString("item"); vlist.addElement(item);
				 */
				vlist.addElement(rs.getString("item"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return vlist;
	}

	// Poll Update(투표실행. for 사용해서 배열로 db로 간다.)
	public boolean updatePoll(int listNum, String itemNum[]) {
		//itemnum = 0&itemnum=1&itemnum=2&num=2
		Connection con = null;
		PreparedStatement pstmt = null;
		String sql = null;
		boolean flag = false;
		try {
			con = pool.getConnection();
			sql = "update tblPollItem set count=count+1"
					+ "where listnum=? and itemnum=?"; //2가지 조건
			pstmt = con.prepareStatement(sql);
			if(listNum==0) {
				listNum = getMaxNum();
			}
			for (int i = 0; i < itemNum.length; i++) {
				pstmt.setInt(1, listNum);
				pstmt.setInt(2, Integer.parseInt(itemNum[i]));
				if(pstmt.executeUpdate()==1) {
					flag = true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt);
		}
		return flag;
	}

	// Poll View (투표결과)
	public Vector<PollItemBean> getView(int listNum){
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		Vector<PollItemBean> vlist = new Vector<PollItemBean>();
		try {
			con = pool.getConnection();
			sql = "select item, count from tblPollItem where listnum=?";
			pstmt = con.prepareStatement(sql);
			if(listNum==0) {
				listNum = getMaxNum();
			}
			pstmt.setInt(1, listNum);
			rs = pstmt.executeQuery();
			while(rs.next()) {
				PollItemBean piBean = new PollItemBean();
				String item[] = new String[1];
				item[0]=rs.getString("item");
				piBean.setItem(item);
				piBean.setCount(rs.getInt("count"));
				vlist.addElement(piBean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return vlist;
	}
	

	// Max Count (하이라이트)
		public int getMaxCount(int listNum) {
			Connection con = null;
			PreparedStatement pstmt = null;
			ResultSet rs = null;
			String sql = null;
			int maxCnt = 0;
			try {
				con = pool.getConnection();
				sql = "select max(count) from tblPollitem "
						+ "where listNum = ?";
				pstmt = con.prepareStatement(sql);
				if(listNum==0)
					listNum = getMaxNum();
				pstmt.setInt(1, listNum);
				rs = pstmt.executeQuery();
				if(rs.next())
					maxCnt = rs.getInt(1);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				pool.freeConnection(con, pstmt, rs);
			}
			return maxCnt;
		}
}

 

 


 

Style.CSS

BODY {
	FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
TD {
	FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
TH {
	FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
SELECT {
	FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
DIV {
	FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
FORM {
	FONT-SIZE: 9pt; COLOR: black; LINE-HEIGHT: 160%; FONT-FAMILY: 굴림,verdana,tahoma
}
TEXTAREA {
	BORDER-RIGHT: 1px solid #999999; BORDER-TOP: 1px solid #999999; FONT-SIZE: 9pt; BORDER-LEFT: 1px solid #999999 ; COLOR: BLACK; BORDER-BOTTOM: 1px solid #999999; FONT-FAMILY: 굴림,verdana; BACKGROUND-COLOR: white
}
INPUT {
	BORDER-RIGHT: 1px solid #999999; BORDER-TOP: 1px solid #999999; FONT-SIZE: 9pt; BORDER-LEFT: 1px solid #999999; COLOR: BLACK; BORDER-BOTTOM: 1px solid #999999; FONT-FAMILY: 굴림,verdana; HEIGHT: 19px; BACKGROUND-COLOR: white
}

A:link {text-decoration:none;color:#696969}
A:hover{text-decoration:yes;color:#66CCFF}
A:visited {text-decoration:none;color:#330066}

 

 

Table.sql

//쿼리문을 돌려주세요

create table tblPollList(
 num int primary key auto_increment,
 question varchar(200) not null,
 sdate date,
 edate date,
 wdate date,
 type smallint default 1,
 active smallint default 1
)COLLATE='euckr_korean_ci';

create table tblPollItem(
 listnum int not null,
 itemnum smallint default 0,
 item varchar(50) not null,
 count int,
 primary key(listnum, itemnum)
)COLLATE='euckr_korean_ci';

 

 


 

jsp 파일 (poll 폴더)

 

pollForm

<!-- pollForm.jsp -->
<%@page import="java.util.Vector"%>
<%@page import="poll.PollListBean"%>
<%@page contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!-- db연동 -->
<jsp:useBean id="mgr" class="poll.PollMgr" />
<% 
	request.setCharacterEncoding("EUC-KR"); 
	int num = 0;
	if(request.getParameter("num")!=null){
		num = Integer.parseInt(request.getParameter("num"));
	} //요청한 값이 mgr로 넘어간다
	PollListBean plBean=mgr.getPollRead(num);
	System.out.println("넘:"+num);
	Vector<String> vlist = mgr.getItem(num);
	String question = plBean.getQuestion();
	int type = plBean.getType();
	int active = plBean.getActive();
%>
<form action="pollFormProc.jsp">
<table border="1">
	<tr>
		<td colspan="2" width="300">Q: <%=question %></td>
	</tr>
	<tr>
		<td colspan="2">
	<%
	for(int i=0; i<vlist.size(); i++){
		String item = vlist.get(i);
	%>
	<%if(type==1){%>
	<input type="checkbox" name="itemnum" value="<%=i%>">
	<%}else{%>
	<input type="radio" name="itemnum" value="<%=i%>">
	<%} %>
		<%=item%><br/>
		<%} //for	%>
		</td>
	</tr>
	<tr>
		<td width="150">
		<%if(active==1){%>
		<input type="submit" value="투표">
		<%}else{%>
			투표종료
		<%}%>
		</td>
		<td width="150">
			<input type="button" value="결과" 
			onclick="javascript:window.open('pollView.jsp?num=<%=num%>'
			,'pollView','width=500, height=350')">
		</td>
	</tr>
</table>
<input type="hidden" name="num" value="<%=num%>">
</form>

 

 

pollFormProc

<!-- pollFormProc.jsp -->
<%@page import="poll.PollMgr"%>
<%@page contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<% request.setCharacterEncoding("EUC-KR"); 
	int num = Integer.parseInt(request.getParameter("num"));
	PollMgr mgr = new PollMgr();
	String itemNum[] = request.getParameterValues("itemnum");
	boolean result = mgr.updatePoll(num, itemNum);
	String msg= "투표가 등록되지 않았습니다.";
	if(result)
		msg= "투표가 등록 되었습니다.";
%> 
<script>
	alert("<%=msg%>");
	location.hrerf="pollst.jsp?num=<%=num%>";
</script>

 

 

pollInsert

<!-- pollInsert.jsp -->
<%@ page contentType="text/html; charset=EUC-KR" %>
<html>
<head>
<title>JSP Poll</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript">
	function send() {
		f = document.frm;
		f.sdate.value = f.sdateY.value+"-"
		+ f.sdateM.value+"-"+f.sdateD.value;
		f.edate.value = f.edateY.value+"-"
		+ f.edateM.value+"-"+f.edateD.value;
		f.submit();
	}
</script>
</head>
<body bgcolor="#FFFFCC">
	<div align="center">
		<br />
		<h2>투표프로그램</h2>
		<hr width="600" />
		<b>설문작성</b>
		<hr width="600" />
		<form name="frm" method="post" action="pollInsertProc.jsp">
			<table border="1" width="500">
				<tr>
					<td><b>질문</b></td>
					<td colspan="2"><input name="question" size="30"></td>
				</tr>
				<tr>
					<td rowspan="10"><b>항목</b></td>
					<%
						for (int i = 1; i <= 4; i++) {
							out.println("<td>" + (i * 2 - 1)
									+ ": <input name='item'></td>");
							out.println("<td>" + (i * 2)
									+ ": <input name='item'></td>");
							out.println("</tr>");
							if (i == 9) {
								out.println("");
							} else {
								out.println("<tr>");
							}
						}//for end
					%>
				<tr>
					<td>시작일</td>
					<td colspan="2"><select name="sdateY">
							<option value="2019">2019
							<option value="2020">2020
					</select>년 <select name="sdateM">
							<%
								for (int i = 1; i <= 12; i++) {
									out.println("<option value='" + i + "'>" + i);
								}
							%>
					</select>월 <select name="sdateD">
							<%
								for (int i = 1; i <= 31; i++) {
									out.println("<option value='" + i + "'>" + i);
								}
							%>
					</select>일</td>
				</tr>
				<tr>
					<td>종료일</td>
					<td colspan=2><select name="edateY">
							<option value="2019">2019
							<option value="2020">2020
					</select>년 <select name="edateM">
							<%
								for (int i = 1; i <= 12; i++) {
									out.println("<option value='" + i + "'>" + i);
								}
							%>
					</select>월 <select name="edateD">
							<%
								for (int i = 1; i <= 31; i++) {
									out.println("<option value='" + i + "'>" + i);
								}
							%>
					</select>일</td>
				</tr>
				<tr>
					<td>복수투표</td>
					<td colspan=2>
						<input type="radio" name="type" value="1" checked>yes 
						<input type="radio" name="type" value="0">no
					</td>
				</tr>
				<tr>
					<td colspan=3>
						<input type="button" value="작성하기" onclick="send()"> 
						<input type="reset" value="다시쓰기"> 
						<input type="button" value="리스트" onClick="javascript:location.href='pollList.jsp'">
					</td>
				</tr>
			</table>
			<input type="hidden" name="sdate">
			<input type="hidden" name="edate">
		</form>
	</div>
</body>
</html>

 

 

 

pollInsertProc

<!-- pollInsertProc.jsp -->
<%@ page contentType="text/html; charset=EUC-KR" %>
<%request.setCharacterEncoding("EUC-KR");%>
<jsp:useBean id="mgr" class="poll.PollMgr" />
<jsp:useBean id="plBean" class="poll.PollListBean" />
<jsp:setProperty property="*" name="plBean"/>
<jsp:useBean id="piBean" class="poll.PollItemBean" />
<jsp:setProperty property="*" name="piBean"/>
<%
	boolean result = mgr.insertPoll(plBean, piBean);
	String msg="설문 추가에 실패";
	String location = "pollInsert.jsp";
	if(result){
		msg = "설문 추가 성공";
		location = "pollList.jsp";
	}
%>
<script>
	alert("<%=msg%>");
	location.href="<%=location%>";
</script>

 

 

 

pollview

<%@page import="poll.PollItemBean"%>
<%@page import="java.util.Random"%>
<%@page import="java.util.Vector"%>
<%@page import="poll.PollListBean"%>
<%@page contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<jsp:useBean id="mgr" class="poll.PollMgr" />
<% 
	request.setCharacterEncoding("EUC-KR"); 
	int num=0;
	if(request.getParameter("num")!=null){
		num = Integer.parseInt(request.getParameter("num"));
	}		
	PollListBean plbBean = mgr.getPollRead(num); //설문에 대한 값
	Vector<PollItemBean> vlist = mgr.getView(num);
	int sumCount = mgr.sumCount(num);
	String question = plbBean.getQuestion();  //투표수
	Random r= new Random(); //막대그래프 랜덤한 색깔 부여
	
%> 
<html>
<head>
<title>JSP Poll</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body bgcolor="#FFFFCC">
<div align="center"><br/>
<h2>투표 결과</h2>
<table border="1" width="400">
	<tr>
		<td colspan="4">
		<b>Q : <%=question%></b>	
		</td>
	</tr>
	<tr>
		<td colspan="3">
		<b>총 투표자 : <%=sumCount%>명<%= %></b>	
		</td>
		<td width="40"><b>count(%)</b></td>
	</tr>
	<%
		for(int i=0; i<vlist.size(); i++){
			PollItemBean piBean = vlist.get(i);
			String item[] = piBean.getItem();
			int count = piBean.getCount();
			int ratio = new Double(Math.round((double)
					count/sumCount*100)).intValue();
			String rgb = "#"+Integer.toHexString(r.nextInt(255*255*255)); //색상수
			int maxCnt = mgr.getMaxCount(num);
	%>
	<tr>
		<td width="20" align = "center"><%=i+1%></td>
		<td width="120" align = "center">
		<%if(maxCnt==count){ %><font color="red"><b><%}%>
			<%=item[0]%>
		<%if(maxCnt==count){ %></b></font><%}%>
		</td>
		<td>
			<table width="<%=ratio%>">
				<tr>
					<td bgcolor="<%=rgb%>" height = "15"></td>
				</tr>
			</table>
		</td>
		<td width="40" align = "center"><%=count%>(<%=ratio%>)</td>
	</tr>
	<%
		}
	%>
</table><br/>
<a href="javascript:window.close()">닫기</a>
</div>
</body>
</html>

 

 

 

pollList

<%@page import="poll.PollListBean"%>
<%@page import="java.util.Vector"%>
<%@page contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<% 
request.setCharacterEncoding("EUC-KR"); 
%> 
<jsp:useBean id="mgr" class="poll.PollMgr" />
<html>
<head>
	<title>JSP Poll</title>
	<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body bgcolor="#FFFFCC">
	<div align = "center"><br/>
		<h2>투표 프로그램</h2>
		<hr width="60%" />
		<b>설문폼</b>
		<!-- include 지시자(@include), 액션 태그 두 가지가 있다. 지시자는 조각모음(항상 있는 메뉴들, 기능이 없는데 반복해서 쓸 경우) 때 쓴다. -->
		<!-- include 액션태그(jsp:include...)는 요청정보가 같이 넘어간다. 포워드처럼 -->
		<jsp:include page="pollForm.jsp" />
		<hr width="60%" />
		<b>설문리스트</b>
<table>
	<tr>
		<td>
		<table  border="1">
			<tr>
				<th width="50">번호</th>
				<th width="250" align="left">질문</th>
				<th width="200">시작일~종료일</th>
			</tr>
		<!-- 설문 리스트 Start -->
		<%
			Vector<PollListBean> vlist = mgr.getAllList();
			for(int i=0; i<vlist.size(); i++){
				PollListBean plBean = vlist.get(i);
				int num=plBean.getNum();
				String question = plBean.getQuestion();
				String sdate = plBean.getSdate();
				String edate = plBean.getEdate();
		%>
			<tr align="center">
				<td><%=vlist.size()-i %></td>
				<td align="left">
					<a href="pollList.jsp?num=<%=num%>"><%=question %>
				</td>
				<td><%=sdate+"~"+edate%></td>
			</tr>
			<%} //--for %>
		<!-- 설문 리스트 End -->
		</table>
		</td>
	</tr>
	<tr>
		<td align="center">
			<a href="pollInsert.jsp">설문작성하기</a>
		</td>
	</tr>
</table>
</div>
</body>
</html>

 

* include 지시자와 액션 태그의 차이점

 

JSP include(지시자와 액션태그)

JSP include(지시자와 액션태그) JSP페이지를 모듈화하여 다른 페이지에 include하는 방법은 지시자(directive)와 액션태그(action tag)를 사용하는 방법이 있다. 1. 지시자 include(directive include) '지시자..

doublesprogramming.tistory.com

pollList.jsp 예제에서는 지시자 방식을 사용했다.

728x90
728x90

'Java Friends > JSP' 카테고리의 다른 글

JSP 파일업로드 기능 구현  (0) 2019.07.16
JSP 방명록 구현하기  (0) 2019.07.15
JSP 회원가입, 로그인, 로그아웃 기능 구현  (1) 2019.07.11
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

 

명품자바프로그래밍 11장. 기본적인 스윙 컴포넌트와 활용

명품자바프로그래밍 11장 요약

 

GUI 프로그래밍

- 컴포넌트 기반 : 스윙 패키지에 주어진 GUI 컴포넌트 이용하며 구성이 쉽다. 일반적인 GUI 프로그램에 적합하며 자바 패키지에 제공하는 GUI 컴포넌트 한계가 있다.

- 그래픽 기반 (명품자바 12장) : 선, 원, 도형, 이미지를 직접 그리는 그래픽 화면 구성. 개발자의 작업 부담이 높으며 자바 패키지에 없는 독특한 GUI 구성 가능. 게임 등 자유로운 GUI

 

스윙 컴포넌트와 상속 관계

 

스윙 컴포넌트 의 공통 메소드, JComponent는 컴포넌트의 모양, 상태, 위치, 크기에 관련된 메소드와 컨테이너를 위한 메소드가 있다.

 

JLabel : 문자열이나 이미지를 컴포넌트화해 출력해줌

- 생성자;

JButton :

JCheckBox :

JRadioButton :

- 라디오버튼 : 하나만 선택. 반드시 논리적 버튼그룹 객체가 필요하다.

- 체크박스 : 다중 선택

JTextField

JTextArea

JList<E>

JComboBox<E>

JSlider : 마우스로 움직이면서 값을 선택하는 컴포넌트

메뉴 만드는 과정 : JMenuBar->JMenu컴포넌트->JMenuItem->JMenuBar컴포넌트를 JFrame 에 붙인다.

팝업 다이얼로그

입력 다이얼로그

확인 다이얼로그

 

 

명품자바프로그래밍 11장 예제

 

| 예제 11-1 |

| 예제 11-2 |

 

| 예제 11-3 | 각 이미지 파일로부터 normalIcon, rolloverIcon, pressedIcon을 각각 생성하고 JButton에 등록하여 다음과 같이 작동하는 버튼을 작성하라. 이미지 파일은 프로젝트 폴더 밑의 images 폴더에 있어야 한다.

 

| 예제 11-4 |  문자열 체크박스 2개와 이미지 체크박스 1개를 가진 프로그램을 작성하라. 이미지 체크박스에는 선택 상태를 나타내는 이미지를 지정하여야 한다.

package test11;

import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class CheckBoxTest extends JFrame{
	CheckBoxTest(){
		setTitle("CheckBox");
		setSize(300, 200);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		JPanel p=new JPanel();
		ImageIcon checked=new ImageIcon("images/rpgiab_icon_pack/32x32/star.png");
		ImageIcon nonchecked=new ImageIcon("images/rpgiab_icon_pack/32x32/wizard.png");
			
		JCheckBox apple=new JCheckBox("머글");
		JCheckBox pear=new JCheckBox("마법사", true);
		JCheckBox cherry=new JCheckBox("뾰로롱", nonchecked);
		cherry.setBorderPainted(true);
		cherry.setSelectedIcon(checked);  //선택이 되었을 때
		
		p.add(apple); p.add(pear); p.add(cherry);
		add(p);
		setVisible(true);
	}
	public static void main(String[] args) {
		new CheckBoxTest();
	}
}

 

 

 

| 예제 11-5 |  다음 그림과 같이 세 과일에 대해 각각 체크박스를 만들고, 사용자가 과일을 선택하거나 해제하면 바로 선택된 과일의 합산을 보여주는 응용프로그램을 작성하라.

package test11;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class ItemEventTest extends JFrame {
	private JCheckBox[] fruits;
	private String[] names = { "사과", "배", "체리" };
	private JLabel sumLa;

	ItemEventTest() {
		setTitle("11-5");
		setSize(300, 200);
		setDefaultCloseOperation(EXIT_ON_CLOSE);

		Container c = getContentPane();
		c.setLayout(new FlowLayout());
		JPanel p = new JPanel();    //안묶어주면 오류가 많다.

		fruits = new JCheckBox[3];
		MyItemListener l = new MyItemListener();
		for (int i = 0; i < fruits.length; i++) {
			fruits[i] = new JCheckBox(names[i]);
			fruits[i].addItemListener(l);
			p.add(fruits[i]);

		}
		sumLa = new JLabel("현재 금액은 0원입니다");
		c.add(new JLabel("사과 100원 배 500원 체리 20000원"));
		c.add(p);
		c.add(sumLa);
		setVisible(true);

	}

	public static void main(String[] args) {
		new ItemEventTest();

	}

	class MyItemListener implements ItemListener{
		private int sum=0;

		@Override
		public void itemStateChanged(ItemEvent e) {
			if(e.getStateChange()==ItemEvent.SELECTED) 
			{
				if(e.getItem()==fruits[0]) 
				{
					sum+=100;
				}else if(e.getItem()==fruits[1]) {
					sum+=500;
				}else {
					sum+=20000;
				}
			}	
			else    // 버튼을 뺄 때
			{	
				if(e.getItem()==fruits[0]) 
				{
					sum-=100;
				}
				else if(e.getItem()==fruits[1])
				{
					sum-=500;
				}
				else 
				{ 
					sum-=20000;
				}
		}
		sumLa.setText("현재 금액은 "+sum+"입니다");
		}
	}
}

 

 

 

| 예제 11-6 | 문자열 라디오버튼 2개와 이미지 라디오버튼 1개를 가진 응용프로그램을 작성하라.

 

 

| 예제 11-7 | 3개의 라디오버튼을 생성하고 각 라디오버튼이 선택될 때 해당 이미지를 출력하는 응용프로그램을 작성하라. 3개의 라디오버튼을 만들고 동일한 버튼 그룹에 삽입, 그중 한 라디오버튼을 초기에 선택 상태로 만든다. JPanel 객체를 하나 생성하고 그 곳에 3개의 라디오버튼을 붙이고, JPanel 객체를 컨텐트팬의 NORTH에 배치한다. 이미지는 JLabel을 통해 출력하며 컨텐트팬의 CENTER에 배치한다.

package test11;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

public class RadioButtonEx extends JFrame {
	JRadioButton[] rb = new JRadioButton[3];
	ImageIcon[] icon = { new ImageIcon("images/rpgiab_icon_pack/32x32/star.png"),
			new ImageIcon("images/rpgiab_icon_pack/32x32/puzzle.png"),
			new ImageIcon("images/rpgiab_icon_pack/32x32/palette.png") };
	String[] str = { "별", "퍼즐", "빠레뜨" };
	JLabel imgLa;

	RadioButtonEx() {
		setTitle("예제");
		setSize(300, 200);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		JPanel p = new JPanel();
		p.setBackground(Color.GRAY);
		
		ButtonGroup g = new ButtonGroup();
		MyItemListener l = new MyItemListener();
		imgLa = new JLabel(icon[0]);
		
		for (int i = 0; i < rb.length; i++) {
			rb[i] = new JRadioButton(str[i]);
			rb[i].addItemListener(l);
			g.add(rb[i]);
			p.add(rb[i]);
		}
		rb[0].setSelected(true);
	
		add(p, BorderLayout.NORTH);
		add(imgLa);

		setVisible(true);
		
	}

	public static void main(String[] args) {
		new RadioButtonEx();
	}

	class MyItemListener implements ItemListener {

		@Override
		public void itemStateChanged(ItemEvent e) {
			// TODO Auto-generated method stub
			if (e.getStateChange() == ItemEvent.DESELECTED) // 미선택
				return;
			if (rb[0].isSelected()) {
				imgLa.setIcon(icon[0]);
			} else if (rb[1].isSelected()) {
				imgLa.setIcon(icon[1]);
			} else {
				imgLa.setIcon(icon[2]);
			}
		}
	}
	class MyActionListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			String str=e.getActionCommand();
			if(str.equals("추가")) {	
			}else if(str.equals("취소")){
			}	
		}
	}
}

 

 

 

| 예제 11-8 | JTextField를 이용하여 그림과 같이 이름, 학과, 주소를 입력받는 폼을 만들어라. 입력 창의 열의 개수는 모두 20으로 한다.

package test11;

import java.awt.Container;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class p1108 extends JFrame{
	p1108(){
		setTitle("11-08");
		setSize(300, 200);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		Container c=getContentPane();
		c.setLayout(new FlowLayout());
		
		c.add(new JLabel("이름"));
		c.add(new JTextField(20));
		c.add(new JLabel("학과"));
		c.add(new JTextField("컴공", 20));
		c.add(new JLabel("주소"));
		c.add(new JTextField("서울시",20));
	
		setVisible(true);
	}
	
	public static void main(String[] args) {
		new p1108();
	}
}

 

 

 

| 예제 11-9 |

그림과 같이 사용자가 텍스트필드 창에 문자열을 입력한 후 <Enter>키를 입력하면 텍스트영역 창에 문자열을 추가하고 텍스트필드 창에 입력된 문자열을 지우는 프로그램을 작성하라.

 

| 예제 11-10 | 다음 그림과 같이 3개의 리스트를 가진 프로그램을 작성하라. 마지막 리스트는 JScrollPane을 이용하여 스크롤되도록 하라.

 

 

 

| 예제 11-11 |

 

| 예제 11-12 |

 

| 예제 11-13 |

package test11;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class ComboTest extends JFrame{
	String[] str= {"1번마", "2번마", "3번마"};
	ImageIcon[] imgs= {
			new ImageIcon("images/rpgiab_icon_pack/32x32/star.png"),
			new ImageIcon("images/rpgiab_icon_pack/32x32/light.png"),
			new ImageIcon("images/rpgiab_icon_pack/32x32/weather_sun.png")};
	
	JLabel la=new JLabel();

	ComboTest(){
		setTitle("ComboTest");
		setSize(300, 100);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		JComboBox<String> combo=new JComboBox<String>(str);
		Container c=getContentPane();
		c.setLayout(new FlowLayout());
		
		la.setIcon(imgs[0]);
		c.add(combo);
		c.add(la);
		
		setVisible(true);
		combo.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				int index=combo.getSelectedIndex();
				la.setIcon(imgs[index]);
			}
		});
	}

	public static void main(String[] args) {
		new ComboTest();
	}
}

 

 

 

| 예제 11-14 | 다음과 같이 0과 200사이의 값을 선택할 수 있는 수평 슬라이더를 만들어라.

 

| 예제 11-15 | 다음 그림과 같이 JSlider를 이용하여 3개의 슬라이더를 만들고, 각 슬라이더는 색의 구성 요소인 r(red), g(green), b(blue) 값을 선택하는데 사용하라. 사용자가 선택한 r,g,b 값을 조합하여 레이블의 배경색으로 출력하라.

package test0507;

import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
	
public class SliderTest extends JFrame{
	private JLabel colorLabel;
	private JSlider[] sl=new JSlider[3];

	SliderTest(){
		setTitle("11-15");
		setSize(300, 250);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		Container c=getContentPane();
		c.setLayout(new FlowLayout());
		
		colorLabel=new JLabel("슬라이드 테스트");
		colorLabel.setOpaque(true);
		
		for(int i=0; i<sl.length; i++) {
			sl[i]=new JSlider(JSlider.HORIZONTAL, 0, 255, 128);
			sl[i].setPaintLabels(true);   //숫자라벨
			sl[i].setPaintTicks(true);   //눈금
			sl[i].setPaintTrack(true);    // ?
			sl[i].setMajorTickSpacing(50);
			sl[i].setMinorTickSpacing(10);
			sl[i].addChangeListener(new MyChangeListener());
			c.add(sl[i]);
		}
		c.add(colorLabel);
		
		sl[0].setForeground(Color.RED);
		sl[1].setForeground(Color.GREEN);
		sl[2].setForeground(Color.BLUE);
		
		int r=sl[0].getValue();
		int g=sl[1].getValue();
		int b=sl[2].getValue();
		
		colorLabel.setBackground(new Color(r,g,b));
		
		setVisible(true);
	}

	public static void main(String[] args) {
		new SliderTest();

	}
	class MyChangeListener implements ChangeListener{

		@Override
		public void stateChanged(ChangeEvent e) {
			int r=sl[0].getValue();
			int g=sl[1].getValue();
			int b=sl[2].getValue();
			colorLabel.setBackground(new Color(r,g,b));
			
		}
		
	}

}

 

 

 

| 예제 11-16 | 메뉴를 만들어보자. 그림과 같이 Screen, Edit, Source, Project, Screen, Edit, Source, Project, Run Run의 5개 메뉴를 가지며 Screen 메뉴에만 4개의 메뉴아이템과 분리선 (separator) 을 가지도록 프로그램을 작성하라 .

package test0507;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class MenuTest01 extends JFrame{
	MenuTest01(){
		setTitle("이벤트처리");
		setSize(300, 200);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		JMenuBar mb=new JMenuBar();
		JMenu screenMenu=new JMenu("Screen");
		mb.add(screenMenu);
	
		screenMenu.add(new JMenuItem("Load"));
		screenMenu.add(new JMenuItem("Hide"));
		screenMenu.add(new JMenuItem("ReShow"));
		screenMenu.addSeparator(); //구분선
		screenMenu.add(new JMenuItem("Exit"));
		
		setJMenuBar(mb);
		
		setVisible(true);
	}

	public static void main(String[] args) {
		new MenuTest01();
	}
}

 

 

 

| 예제 11-17 | 메뉴에 액션 이벤트 달기

package test0507;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class MenuTest01 extends JFrame{
	JLabel imgLa;
	String[] menuStr= {"Load", "Hide", "ReShow", "Exit"};
	JMenuItem[] menuItem=new JMenuItem[4];
	
	MenuTest01(){
		setTitle("이벤트처리");
		setSize(400, 400);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		JMenuBar mb=new JMenuBar();
		JMenu screenMenu=new JMenu("Screen");
		mb.add(screenMenu);
		imgLa=new JLabel();
		imgLa.setOpaque(true);
		imgLa.setBackground(Color.GRAY);
		
		
		for(int i=0; i<menuItem.length; i++) {
			menuItem[i]=new JMenuItem(menuStr[i]);
			menuItem[i].addActionListener(new MenuActionListener());
			screenMenu.add(menuItem[i]);
			if(i==2) screenMenu.addSeparator();
		}
	
		setJMenuBar(mb);
		add(imgLa);
		setVisible(true);
	}

	public static void main(String[] args) {
		new MenuTest01();

	}
	//event
	class MenuActionListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			String cmd=e.getActionCommand();   //스트림에 따라 명령
			switch(cmd) {
				case "Load":
					if(imgLa.getIcon()!=null)
						return;
						imgLa.setIcon(new ImageIcon("images/aa.jpg"));
						break;
				case "Hide":
					imgLa.setVisible(false);
					break;
				case "Reshow":
					imgLa.setVisible(true);
					break;
				case "Exit":
					System.exit(0);   
					break;
			}
		}	
	}
}

 

 

 

| 예제 11-18 | 메뉴를 만들고 서식, 폰트(굴림, Font.PLAIN.16) , 크기(확대/축소), 색상(빨,파,녹) 으로 구성하라.

728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

 

명품자바프로그래밍 10장 이벤트 처리

10장. 자바의 이벤트 처리 요약

 

이벤트 기반 프로그래밍 : 이벤트의 발생에 의해 프로그래밍

이벤트 소스 :
이벤트 객체 :

*ActionEvent, MouseEvent 많이 씀

 

이벤트 리스너 :

- 독립 클래스 :
- 내부 클래스 :
- 익명 클래스 :

어댑터 클래스

keyEvent 와 keyListener
-component.setFocusable(true);
-component.requestFocus();

keyTyped()
MouseEvent, MouseListener, MouseMotionListener, MouseWheelListener

유니코드키
유니코드가 아닌 키
가상 키

 

 

10장. 자바의 이벤트 처리 예제


| 예제 10-1 |
버튼을 클릭할 때 발생하는 Action 이벤트를 처리할 MyActionListener 클래스를 독립클래스로 작성하고 클릭할 때마다 버튼 문자열이 "Action"과 "액션"으로 번갈아 변하도록 하라.

※ 독립클래스로 Action 이벤트의 리스너 작성

package test10;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;


/*class MyAction implements ActionListener{

	@Override
	public void actionPerformed(ActionEvent arg0) {
		JButton b=(JButton)arg0.getSource();  //이벤트 발생한 소스를 얻는다
		if(b.getText().equals("Action"))
			b.setText("액션");
		else b.setText("Action");
		}
	}*/

public class EventTest01 extends JFrame {
	JButton btn;
	
	EventTest01() {
		setTitle("이벤트처리");
		setSize(300, 200);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		Container c=getContentPane();
		c.setLayout(new FlowLayout());
		btn=new JButton("Action");
		c.add(btn);
		setVisible(true);
		btn.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				JButton b=(JButton)arg0.getSource();  //이벤트 발생한 소스를 얻는다
				if(b.getText().equals("Action"))
					b.setText("액션");
				else b.setText("Action");
	}
		});
	}
	public static void main(String[] args) {
		new EventTest01();
	}
	/*class MyAction implements ActionListener{
		@Override
		public void actionPerformed(ActionEvent arg0) {
			JButton b=(JButton)arg0.getSource();  //이벤트 발생한 소스를 얻는다
			if(b.getText().equals("Action"))
				b.setText("액션");
			else b.setText("Action");*/
}

 

 

 

| 예제 10-2 |  10-1과 같은 내용을 내부 클래스로 이벤트 리스너를 만들어보자.

※ 내부클래스로 Action 이벤트의 리스너 작성

package test10;

import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

//class MyAction implements ActionListener{
//	private JTextField tf1, tf2;
//	private JLabel la;
//	MyAction(JTextField tf1, JTextField tf2, JLabel la){
//		this.tf1=tf1;
//		this.tf2=tf2;
//		this.la=la;
//	}
//	@Override
//	public void actionPerformed(ActionEvent arg0) {
//		//JButton b=(JButton)arg0.getSource();
//		int num1=Integer.parseInt(tf1.getText());
//		int num2=Integer.parseInt(tf2.getText());
//		la.setText((num1+num2)+"   ");
//		
//	}
//	
//}

public class EventTest02 extends JFrame {
	JTextField tf1, tf2;
	JLabel la; //값이 안바뀌어서 만들필요 ㄴㄴ
	JButton btn;

	EventTest02() {
		setTitle("이벤트처리");
		setSize(200, 300);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		Container c=getContentPane();
		c.setLayout(new GridLayout(4,1));
		
		JPanel p1 = new JPanel();
		JPanel p2 = new JPanel();
		JPanel p3 = new JPanel();

		tf1 = new JTextField(10);
		p1.add(new JLabel("숫자1: "));
		p1.add(tf1);

		tf2 = new JTextField(10);
		p2.add(new JLabel("숫자2: "));
		p2.add(tf2);
		
		la=new JLabel("처리결과");
		p3.add(new JLabel("계산결과"));
		p3.add(la);
		btn=new JButton("더하기");
		c.add(p1);
		c.add(p2);
		c.add(btn);
		c.add(p3);
				
		setVisible(true);
		btn.addActionListener(new MyAction());
	}

	public static void main(String[] args) {
		new EventTest02();
	}
	class MyAction implements ActionListener{
//		private JTextField tf1, tf2;
//		private JLabel la;
//		MyAction(JTextField tf1, JTextField tf2, JLabel la){
//			this.tf1=tf1;
//			this.tf2=tf2;
//			this.la=la;
//		}
		@Override
		public void actionPerformed(ActionEvent arg0) {
			//JButton b=(JButton)arg0.getSource();
			int num1=Integer.parseInt(tf1.getText());
			int num2=Integer.parseInt(tf2.getText());
			la.setText((num1+num2)+"   ");
			
		}
		
	}
}

 

 

 

| 예제 10-3 | 10-1, 10-2와 같은 내용을 내부 클래스로 이벤트 리스너를 만들어보자.

※ 익명클래스로 Action 이벤트의 리스너 작성

대기중

 

 

 

| 예제 10-4 | 컨탠트팬의 아무 위치에 마우스버튼을 누르면 마우스 포인트가 있는 위치로 "hello"문자열을 옮기는 스윙 응용프로그램을 작성하라. #마우스이벤트연습

package test10;

import java.awt.Color;
import java.awt.Container;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class MouseTest extends JFrame implements MouseListener{
	JLabel la;
	Container c;
	
	MouseTest(){
		setTitle("Mouse 이벤트예제");
		setSize(300, 200);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		c=getContentPane();
		c.setLayout(null);
		la=new JLabel("Hello");
		la.setSize(50,20);
		la.setLocation(10, 10);
		c.add(la);		
		setVisible(true);
		c.addMouseListener(this);
	}
	public static void main(String[] args) {
		new MouseTest();
	}
	@Override
	public void mouseClicked(MouseEvent arg0) {
		// 좌표가 없어도 됨
		// c.setBackground(Color.RED);
	}
	@Override
	public void mouseEntered(MouseEvent e) {
		// 마우스가 화면 안에 들어올 때
		// c.setBackground(Color.BLACK);
	}
	@Override
	public void mouseExited(MouseEvent e) {
		// 마우스가 화면 밖에 나갈 때
		// c.setBackground(Color.YELLOW);
	}
	@Override
	public void mousePressed(MouseEvent e) {
		int x=e.getX();
		int y=e.getY();
		la.setLocation(x, y);  //클릭하는 위치
	}
	@Override
	public void mouseReleased(MouseEvent e) {
         // 안쓴다고 지우면 에러납니다.
        // 키를 떼는 순간
	}
}

 

 

 

| 예제 10-5 | MouseAdapter를 이용하여 예제 10-4를 수정하라.

package test10;

import java.awt.Container;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class MouseAdapterTest extends JFrame {
	JLabel la;
	
	MouseAdapterTest(){
		setTitle("마우스어댑터테스트");
		setSize(300, 200);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		Container c=getContentPane();
		c.setLayout(null);
		
		la=new JLabel("Hello");
		la.setBounds(10,10,50,20);
		c.add(la);
		setVisible(true);
		
		c.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent e) {
				int x=e.getX();
				int y=e.getY();
				la.setLocation(x, y);
			}
		});
	}
	public static void main(String[] args) {
		new MouseAdapterTest();
	}
}

 

 

 

| 예제 10-6 | 입력된 키의 키코드, 유니코드, 키의 이름 문자열을 읽는 코드.

※ keyEvent와 keytListener의 활용

package test10;

import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class KeyEventTest01 extends JFrame implements KeyListener{
	private JLabel[] keyMessage;
	
	KeyEventTest01(){
		setTitle("keyListener 예제");
		setSize(300, 200);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		Container c=getContentPane();
		c.setLayout(new FlowLayout());
		c.addKeyListener(this);
		keyMessage=new JLabel[3];
		keyMessage[0]=new JLabel("getKeyCode");
		keyMessage[1]=new JLabel("getKeyChar");
		keyMessage[2]=new JLabel("getKeyText");
		
		for(int i=0; i<keyMessage.length; i++) {
			c.add(keyMessage[i]);
			keyMessage[i].setOpaque(true);  //레이블 배경은 기본이 투명. 텍스트는 아님!
			keyMessage[i].setBackground(Color.YELLOW);
		}
		setVisible(true);  
		c.setFocusable(true);  //포커스 받을 수 있게 함
		c.requestFocus();  		
	}

	public static void main(String[] args) {
		new KeyEventTest01();		
	}

	@Override
	public void keyPressed(KeyEvent arg0) {
		//눌러졌을때 키코드를 얻음
		//1번 (작동순서)
		int keyCode=arg0.getKeyCode();
		int keyChar=arg0.getKeyChar();
		String keyStr=arg0.getKeyText(keyCode);
		keyMessage[0].setText(keyCode+"");
		keyMessage[1].setText(keyChar+"");
		keyMessage[2].setText(keyStr+"");
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		//3번
//		int keyCode=arg0.getKeyCode();
//		int keyChar=arg0.getKeyChar();
//		String keyStr=arg0.getKeyText(keyCode);
//		keyMessage[0].setText(keyCode+"");
//		keyMessage[1].setText(keyChar+"");
//		keyMessage[2].setText(keyStr+"");
//		
	}

	@Override
	public void keyTyped(KeyEvent arg0) {
		//2번.유니코드만 받습니다.
//		int keyCode=arg0.getKeyCode();
//		int keyChar=arg0.getKeyChar();
//		//String keyStr=arg0.getKeyText(keyCode);
//		keyMessage[0].setText(keyCode+"");
//		keyMessage[1].setText(keyChar+"");
//		keyMessage[2].setText("");
//		
	}
}

 

 

 

| 예제 10-7 | 다음 그림과 같이 <F1> 키를 입력받으면 콘텐트팬의 배경을 초록색으로, % 키를 입력받으면 노란색으로 변경하는 응용프로그램을 만들어라.

※ 사용자가 키를 입력하면 입력된 키의 이름 문자열을 화면에 출력한다. %키는 shift 키 입력 후 5를 입력한 경우로서 최종적으로 입력된 키는 5이므로 오른쪽 화면에 5키가 입력되었음이라고 출력되어 있다. f1키를 받기 위해 KeyEvent의 getKeycode()메소드를 이용하여야 하며, % 키는 getKeyChar() 메소드를 이용하면 된다.

 

 

 

| 예제 10-8 | 상,하,좌,우 키를 이용하여 "Hello" 문자열을 움직이는 응용프로그램을 작성하라.

※ "Hello" 문자열은 JLabel 컴포넌트로 만들어 컨텐트팬에 부착하고 상,하, 좌,우 키를 움직이면 키 방향으로 한 번에 10픽셀씩 움직인다 이를 위해 컨텐트팬의 배치관리자를 삭제하여야 한다. "Hello" 문자열을 초기에 (50,50) 위치에 출력하라.

package test10;

import java.awt.Container;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class p1008 extends JFrame{
	JLabel la;
	int x=50, y=50;
	p1008(){
		setTitle("10장 8번 예제");
		setSize(300, 300);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		Container c=getContentPane();
		c.setLayout(null);
		la=new JLabel("Hello");
		la.setBounds(x,y,30,20);
		c.add(la);
		c.setFocusable(true);
		c.requestFocus();
		setVisible(true);
		c.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				switch((int) e.getKeyCode()) {
				case KeyEvent.VK_UP:
					if(y-10<0)
						y=0; 
					else
						y-=10;  
					break;
				case KeyEvent.VK_DOWN:
					if(y+10>c.getHeight()-20)
						y=c.getHeight()-20;
					else
						y+=10;
					break;
				case KeyEvent.VK_LEFT:
					if(x-10<0)
						x=0;
					else
						x-=10;
					break;
				case KeyEvent.VK_RIGHT:
					if(x+10>c.getWidth()-30)
						x=c.getWidth()-30;
					else
						x+=10;		
				}
				la.setLocation(x, y);
				//이미 있는 위치 옮기는 것은 repaint가 필요없음 
			}
		});
	}	
	public static void main(String[] args) {
		new p1008();
	}
}

 

 

 

| 예제 10-9 | 입력된 키의 키코드, 유니코드, 키의 이름 문자열을 읽는 코드.

※ keyEvent와 keytListener의 활용

package test10;

import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class MouseEventTest02 extends JFrame{
	JLabel la;
	Container c;
	MouseEventTest02(){
		
		setTitle("10-9");
		setSize(300, 200);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		c=getContentPane();
		c.setLayout(new FlowLayout());
		la=new JLabel("No Mouse Event");   //메모리 할당
		c.add(la);
		setVisible(true);
		
		MyMouseListener l=new MyMouseListener();
		c.addMouseListener(l);
		c.addMouseMotionListener(l);
	}

	public static void main(String[] args) {
		new MouseEventTest02();

	}
	class MyMouseListener implements MouseListener,MouseMotionListener {

		@Override
		public void mouseDragged(MouseEvent arg0) {
			la.setText("mouseDragged("+arg0.getX()+","+arg0.getY()+")");
			
		}

		@Override
		public void mouseMoved(MouseEvent arg0) {
			la.setText("mouseMoved("+arg0.getX()+","+arg0.getY()+")");
			
		}

		@Override
		public void mouseClicked(MouseEvent arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void mouseEntered(MouseEvent arg0) {
			c.setBackground(Color.CYAN);
			
		}

		@Override
		public void mouseExited(MouseEvent arg0) {
			c.setBackground(Color.MAGENTA);
			
		}

		@Override
		public void mousePressed(MouseEvent arg0) {
			la.setText("mousePressed("+arg0.getX()+","+arg0.getY()+")");
			
		}

		@Override
		public void mouseReleased(MouseEvent arg0) {
			la.setText("mouseReleased("+arg0.getX()+","+arg0.getY()+")");

		}
	}
}

 

 

| 예제 10-10 |...

728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

 

 

명품자바프로그래밍 9장 요약, 예제

9장. GUI 기초, AWT와 Swing 9장. GUI 기초, AWT와 Swing 요약 GUI : Graphical User Interface. 이미지나 그래픽을 이용하여 화면을 구성하고 (키보드 등) 입력도구를 이용하여 편리하게 작성된 사용자 인터페이..

coding-restaurant.tistory.com

 

명품자바프로그래밍 9장 연습문제

명품자바 9장 연습문제 LuxuryJava Chapter 09. (실습문제는 다음 글에 있습니다.) | 연습문제 9-1 | 자바에서는 AWT 컴포넌트와 스윙 컴포넌트를 제공한다. 이들 중 어떤 것이 경량 컴포넌트이고, 어떤 것이 중..

coding-restaurant.tistory.com

 


 

명품 자바프로그래밍 9장 실습문제
1~8번 문제와 답

LUXURY JAVA Chapter 09.

 

1. "Let's study Java"라는 문자열을 타이틀로 가지고 프레임의 크기가 400*200인 스윙 프로그램을 작성하라.

package test09;

import javax.swing.JFrame;

public class h0901 extends JFrame {
	h0901() {
		setTitle("Let's study Java");
		setSize(400, 200);
		setDefaultCloseOperation(EXIT_ON_CLOSE);

		setVisible(true);
	}

	public static void main(String[] args) {
		new h0901();
	}
}

 

 

 

2. BoderLayout을 사용하여 컴포넌트 사이의 수평 수직 간격이 각각 5픽셀, 7픽셀이 되도록 스윙 응용프로그램을 작성하라.

package test09;

import java.awt.BorderLayout;
import java.awt.Container;

import javax.swing.JButton;
import javax.swing.JFrame;

public class h0902 extends JFrame {
	h0902() {
		setTitle("BorderLayout Practice");
		setSize(400, 200);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		Container c=getContentPane();
		c.setLayout(new BorderLayout(5,7));
		
		c.add(new JButton("North"), BorderLayout.NORTH);  //대문자
		c.add(new JButton("West"), BorderLayout.WEST);
		c.add(new JButton("Center"), BorderLayout.CENTER);
		c.add(new JButton("East"), BorderLayout.EAST);
		c.add(new JButton("South"), BorderLayout.SOUTH);
		setVisible(true);
	}

	public static void main(String[] args) {
		new h0902();
	}
}

 

 

 

3. GridLayout을 사용하여 다음 그림과 같이 한 줄에 10개의 버튼을 동일한 크기로 배치하는 스윙 프로그램을 작성하라.

package test09;

import java.awt.Container;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;

public class h0903 extends JFrame {
	h0903() {
		setTitle("BorderLayout Practice");
		setSize(600, 300);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		Container c=getContentPane();
		c.setLayout(new GridLayout(1,10));
		
		for(int i=0; i<10; i++) {
				c.add(new JButton(i + ""));
		}
		setVisible(true);
	}

	public static void main(String[] args) {
		new h0903();
	}
}

 

 

 

4. 문제 3을 수정하여 다음 결과와 같이 각 버튼의 배경색을 서로 다르게 설정하라.

※ 패널-GridLayout을 사용하며 색이름은 배열과 for문을 이용해보자.

package test09;

import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;

public class h0904 extends JFrame {
	h0904() {
		setTitle("Ten Color Buttons Frame");
		setSize(600, 300);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		Container c=getContentPane();
		c.setLayout(new GridLayout(1,10));
		
		for(int i=0; i<10; i++) {
			Color[] col= {Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN,
					Color.CYAN, Color.BLUE, Color.MAGENTA, 
					Color.GRAY, Color.PINK, Color.LIGHT_GRAY};
			String text=Integer.toString(i);
			JButton b=new JButton(text);
			b.setOpaque(true); 
			b.setBackground(col[i]);
			c.add(b);
			}	
		setVisible(true);
	}
	public static void main(String[] args) {
		new h0904();
	}
}

 

 

 

5. GridLayout을 이용하여 다음 그림과 같이 16개의 색을 배경색으로 하는 4*4 바둑판을 구성하라. #9장실습문제5번

※ 16개의 JLabel 컴포넌트를 생성하고 각 레이블 컴포넌트의 배경색을 칠한다음 하나씩 GridLayout을 가진 컨테이너에 붙이면 된다.

package Luxuryjava09;

import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class h0905 extends JFrame {
	h0905() {
		setTitle("Ten Color Buttons Frame");
		setSize(600, 300);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		Container c=getContentPane();
		c.setLayout(new GridLayout(4,4));
		
		for(int i=0; i<16; i++) {
			
			Color[] col= {Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN,
					Color.CYAN, Color.BLUE, Color.MAGENTA, 
					Color.GRAY, Color.PINK, Color.LIGHT_GRAY,
					Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN,
					Color.CYAN, Color.BLUE};
			JLabel label=new JLabel(i+"");
			label.setBackground(col[i]);
			label.setOpaque(true);
			c.add(label);
			}	
		setVisible(true);
	}
	public static void main(String[] args) {
		new h0905();
	}
}

 

 

 

6. 20개의 10*10 크기의 JLabel 컴포넌트가 프레임 내에 (50,50) 위치에서 (250,250) 영역에서 랜덤한 위치에 출력되도록 스윙프로그램을 작성하라. 프레임의 크기는 300*300으로 하라. 

 

 

※ JLabel 컴포넌트의 위치를 랜덤하게 설정하기 위해 (x,y) 좌표는 다음과 같이 구한다

int x = (int) (Math.random() * 200) + 50;
int y = (int) (Math.random() * 200) + 50;
label.setLocation(x,y);
label.setSize(20,20);
label.setOpaque(true);
package test09;

import java.awt.Color;
import java.awt.Container;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class h0906 extends JFrame {

	public h0906() {
		setTitle("9장 6번문제");
		setSize(300, 300);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		Container c = getContentPane();
		c.setLayout(null);

		for (int i = 0; i < 20; i++) {
			int x = (int) (Math.random() * 200) + 50;
			int y = (int) (Math.random() * 200) + 50;
			
			//int z = (int) (Math.random() * 100) + 1;
			JLabel label = new JLabel((int)(Math.random() * 100)+"");
			// label.setLocation(x,y);
			// label.setSize(20,20);
			label.setBounds(x, y, 20, 20);
			label.setOpaque(true);
			label.setBackground(Color.red);
			c.add(label);
		}
		setVisible(true);
	}
	public static void main(String[] args) {
		new h0906();
	}
}

 

 

 

7. 다음과 같은 GUI 모양을 가진 스윙 프레임을 작성하라. #9장실습문제7번 #자바계산기만들기 #자바계산기틀

※ JButton, JLabel, JTextField 사용. 여러개의 컴포넌트와 패널을 가진 스윙 프레임으로 컨텐트팬의 NORTH, CENTER, SOUTH에 각각 JPanel을 상속받은 패널을 붙이고 그 곳에 버튼이나 JLabel을 붙이면 된다.

package Luxuryjava09;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class h0907 extends JFrame {
	
	h0907() {
		setTitle("계산기 프레임");
		setSize(400, 400);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		Container c=getContentPane();
		JPanel pn=new JPanel();
		JPanel ps=new JPanel();
		JPanel pc=new JPanel();
		
		pn.setBackground(Color.LIGHT_GRAY);
		pc.setLayout(new GridLayout(4,4));
		ps.setBackground(Color.YELLOW);

		c.add(pc);
		c.add(pn, BorderLayout.NORTH);
		c.add(ps, BorderLayout.SOUTH);
		
		JLabel l1=new JLabel("수십입력");
		JTextField tf1=new JTextField(10);
		pn.add(l1);
		pn.add(tf1);
		
		JLabel l2=new JLabel("계산결과");
		JTextField tf2=new JTextField(10);
		ps.add(l2);
		ps.add(tf2);
		
		for(int i=0; i<16; i++) {
			JButton b=new JButton();
			String[] str= {"CE","Enter","+","-","x","/"};
			pc.add(b);
			if(i<10) {
				b.setText(i+"");
			}else { 
				b.setText(str[i-10]);
			}
			if(i>11) {
				//b.setBackground(Color.CYAN);
				b.setOpaque(true);
			}
		}
		setVisible(true);
			}	
	
	public static void main(String[] args) {
		new h0907();
	}
}

 

※ 입출력도 되는 계산기 (10장에서 이벤트를 배우면 만들 수 있다.)

package test09;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.StringTokenizer;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class h0907 extends JFrame implements ActionListener{
	String[] str = {"CE", "계산", "+", "-", "x", "%"};
	JTextField tf1, tf2;
	String numStr="";

	public h0907() {
		setTitle("계산기프레임");
		setSize(300, 300);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		Container c = getContentPane();
		JPanel pn = new JPanel();
		JPanel ps = new JPanel();
		JPanel pc = new JPanel();

		pn.setBackground(Color.LIGHT_GRAY);
		ps.setBackground(Color.LIGHT_GRAY);
		pc.setLayout(new GridLayout(4, 4, 5, 5));

		JLabel label1 = new JLabel("수식입력");
		tf1 = new JTextField(10);
		pn.add(label1);
		pn.add(tf1);

		JLabel label2 = new JLabel("계산결과");
		tf2 = new JTextField(10);
		ps.add(label2);
		ps.add(tf2);

		for (int i = 0; i < 16; i++) {
			JButton b = new JButton();
			if (i < 10) {
				b.setText(i + ""); // 문자열. Integer.toString(i);
				b.setBackground(Color.WHITE); // 0~10까지
			} else {
				b.setText(str[i - 10]); // ce, 계산
				b.setBackground(Color.WHITE);
			}
			if (i > 11)
				b.setBackground(Color.WHITE); // 연산기호
			pc.add(b);
			b.addActionListener(this);
		}
		c.add(pc);
		c.add(pn, BorderLayout.NORTH);
		c.add(ps, BorderLayout.SOUTH);
		setVisible(true);
	}

	public static void main(String[] args) {
		new h0907();
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		String str=e.getActionCommand();
		
		if(str.equals("CE")) {
			numStr="";
			tf1.setText(numStr);
			tf2.setText("");
		}else if(str.equals("계산")) {
			StringTokenizer st=new StringTokenizer(numStr, "+-x%", true);  //구분자를 넣는다.
			int num1=Integer.parseInt(st.nextToken());
			String op=st.nextToken();
			int num2=Integer.parseInt(st.nextToken());
			switch(op) {
			case "+" : tf2.setText(num1+num2+""); break;
			case "-" : tf2.setText(num1-num2+""); break;
			case "x" : tf2.setText(num1*num2+""); break;
			case "%" : tf2.setText(num1/num2+""); break;
				default: tf2.setText("오류"); break;
			}
			numStr="";
			tf1.setText(numStr);
		}else {
			numStr+=str;
			tf1.setText(numStr);
					}
		}
}

 

 

 

8. 다음과 같은 GUI 모양을 가진 스윙프레임을 작성하라. Open Challenge의 힌트나 정답을 참고하라. 10개의 *문자는 0개의 JLabel을 이용하여 랜덤한 위치에 출력하라. #9장실습문제8번

※ 여러 개의 컴포넌트와 패널을 가진 스윙 프레임 만들기

package Luxuryjava09;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.TextField;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


	class NorthPanel extends JPanel{
		public NorthPanel() {
			setBackground(Color.LIGHT_GRAY);
		//	setLayout(new FlowLayout());
			add(new JButton("Open"));
			add(new JButton("Close"));
			add(new JButton("Exit"));
		}
	}
	class CenterPanel extends JPanel{
		public CenterPanel() {
			setLayout(null);
			for (int i = 0; i < 20; i++) {
				int x = (int)(Math.random()*250);
				int y = (int)(Math.random()*250);
				JLabel label=new JLabel("*");
                label.setForeground(Color.GREEN);
				label.setLocation(x,y);
				label.setSize(20, 20);
				label.setOpaque(true);
				add(label);
				}
		}
	}
	class SouthPanel extends JPanel{
			public SouthPanel() {
			setBackground(Color.YELLOW);
			add(new JButton("Integer Input"));
			add(new TextField(15));
		}
	}
	
public class h0908 extends JFrame{
		h0908(){
			setTitle("여러 개의 패널을 가진 프레임");
			setSize(300, 300);
			setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			
	NorthPanel nP=new NorthPanel();
    CenterPanel nC=new CenterPanel();
	SouthPanel nS=new SouthPanel();
	add(nP, BorderLayout.NORTH);
	add(nS, BorderLayout.SOUTH);
	add(nC);
	setVisible(true);
	}	

	public static void main(String[] args) {
		new h0908();
	}
}

※ 역시 책 9장에는 나오지 않지만, 입력한 숫자만큼 별을 랜덤으로 찍어서 출력하는 스윙 프레임 윈도우는 어떻게 만들까? (10장 내용이다.)

package exam;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Exam08 extends JFrame {
	
	Exam08(){
		setTitle("이벤트 처리");
		setSize(300, 300);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		Container c=getContentPane();
		JPanel pn=new JPanel();
		JPanel pc=new JPanel();
		JPanel ps=new JPanel();
		JButton openBtn=new JButton("열기");
		JButton closeBtn=new JButton("닫기");
		JButton exitBtn=new JButton("나가기");
		pn.add(openBtn);
		pn.add(closeBtn);
		pn.add(exitBtn);
		JTextField charTf=new JTextField(5);
		JTextField numTf=new JTextField(5);
		JButton okBtn=new JButton("OK");
		ps.add(charTf);
		ps.add(numTf);
		ps.add(okBtn);
		pc.setLayout(null);
		pc.setBackground(Color.WHITE);
		pn.setBackground(Color.GRAY);
		ps.setBackground(Color.YELLOW);
		
		c.add(pn, BorderLayout.NORTH);
		c.add(pc);
		c.add(ps,BorderLayout.SOUTH);
		
		okBtn.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				String str=charTf.getText();
				int num=Integer.parseInt(numTf.getText());
				for(int i=0; i<num;i++) {
					int x=(int)(Math.random()*200)+10;
					int y=(int)(Math.random()*150)+10;
					JLabel la=new JLabel(str);
					la.setBounds(x, y, 10,10);
					pc.add(la);
				}
				pc.revalidate();
				pc.repaint();
			}
		});
		setVisible(true);
	}
	public static void main(String[] args) {
		new Exam08();
	}
}
// [출처] 9장 연습문제|작성자 솔라 >>> https://blog.naver.com/miya_2009
728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

 

명품자바 9장 연습문제

LuxuryJava Chapter 09. (실습문제는 다음 글에 있습니다.)

 

| 연습문제 9-1 |  자바에서는 AWT 컴포넌트와 스윙 컴포넌트를 제공한다. 이들 중 어떤 것이 경량 컴포넌트이고, 어떤 것이 중량 컴포넌트인가? 그리고 차이점은?  #명품자바9장연습문제1번

swing 컴포넌트가 경량 컴포넌트이고, AWT 컴포넌트가 중량 컴포넌트이다. 경량 컴포넌트인 스윙은 자바언어로만 구성되어 있고 속도가 느리다. 운영체제의 자원을 빌리지 않고 직접 화면에 그리므로 이질적인 운영체제간에 발생한 버그를 자동적으로 해결한다. 실행 속도가 AWT 보다 느린 편이다. 중량 컴포넌트인 AWT는 해당 운영체제의 GUI를 빌려쓰는 형식이라 운영체제에 따라 다른 모양과 배치가 나타나며 속도가 빠르다. 그러나 운영체제에 따른 미묘한 버그가 발생하며 불규칙한 컴포넌트의 모양과 레이아웃 설정 문제가 발생한다.

 

 

| 연습문제 9-2 | 데스크톱에서 실행되는 GUI 응용프로그램 작성 시 AWT보다 스윙 사용을 권장하는 이유는? #명품자바9장연습문제2번

스윙 컴포넌트는 운영체제와 관계없이 항상 동일하게 작동하고 동일한 모양으로 나타나며 AWT 보다 나중에 개발되어 기능이 다양하고 모양도 화려하다. 또한 컴포넌트 코드를 모두 자바로 구현하여 운영체제에 부담을 주지 않기 때문이다.

 

 

| 연습문제 9-3 | 다음 중 스윙컴포넌트가 아닌 것은? #명품자바9장연습문제3번

1. JPanel     2. JTextField      3. JLabel      4. Button

 

 

| 연습문제 9-4 | 다음 중 컴포넌트는? #명품자바9장연습문제4번

1. JFrame      2. Font       3. Color      4. Graphics

 

 

| 연습문제 9-5 | 컴포넌트와 컨테이너에 대해 잘못 말한 것은? #명품자바9장연습문제5번

1. 컨테이너는 컴포넌트를 담을 수 있는 컴포넌트이다.
2. JPanel은 컨테이너로서 여러 개의 JButton 컴포넌트를 가진다.
3. JFrame은 최상위 컨테이너다.
4. 컴포넌트들은 컨테이너 없이도 출력된다.​

 

 

| 연습문제 9-6 | 컴포넌트와 컨테이너에 대해 잘못 말한 것을 모두 찾아라.

1. 배치관리자를 가지는 것은 컨테이너만의 고유 기능이며, 컴포넌트는 가질 수 없다.
2. 배치관리자는 자신이 소속된 컨테이너의 크기를 조절한다.
3. 컨테이너가 생성될 때 배치관리자가 없는 상태이므로 배치관리자를 설정해야 한다.
4. 한 컨테이너는 여러 개의 배치관리자를 가질 수 있다.
5. 배치관리자의 기능은 컨테이너에 포함된 컴포넌트들의 위치와 크기를 설정하는 것
6. 개발자는 자바에서 주어진 것 외 새로운 배치관리자를 만들어 사용할 수 있다.
7. 컨테이너가 배치관리자를 가지지 않도록 할 수 없다.

 

 

| 연습문제 9-7 | 200*300크기의 스윙프레임을 만든 코드이다. 빈칸에 필요한 코드를 채워라.

 

 

| 연습문제 9-8 | 스윙프레임을 작성한 코드이다. 빈칸에 필요한 코드를 채워라.#명품자바9장연습문제8번

 

 

| 연습문제 9-9 | 다음 지시에 따라 컨테이너 c에 배치관리자를 설정하는 코드를 작성하라. #명품자바9장연습문제9번

container c;
c.____________________

 

(1) 컴포넌트 사이의 수평수직 간격이 각각 3, 4픽셀인 BorderLayout
setLayout(new BorderLayout(3,4));

(2) 컴포넌트 사이의 수평수직 간격이 각각 5, 6픽셀이고 우측정렬하는 FlowLayout
setLayout(new FlowLayout(5,6));

(3) 컴포넌트 사이의 수평수직 간격이 각각 7, 8픽셀이고 행수 5, 열수 2인 GridLayout
setLayout(new GridLayout(7,8,5,2));

(4) 현재 등록된 배치관리자 삭제
setLayout(null);

 

 

| 연습문제 9-10 | 버튼 컴포넌트를 절대 위치에 배치하고자 한다. 주석을 참고해 빈칸을 완성하라. #명품자바9장연습문제10번

___________________________ // import 문

___________________________ // import 문

public class MyFrame ___________________________ {

public MyFrame(){

___________________________ ; // 컨텐트팬 알아내기

___________________________ ; // 컨텐트팬 배치관리자 제거

___________________________ ; // "click" 문자열의 버튼 컴포넌트 생성

___________________________ ; // 버튼 크기를 100*30으로 설정

___________________________ ; // 버튼 위치를 50,70으로 설정

___________________________ ; // 컨텐트팬에 버튼달기

setSize(300,300);

setVisible(true);

}

public static void main(String [] args){

new MyFrame();

}

}

728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

참고하면 좋을 오픈소스 프로젝트

 

한국 오픈소스 프로젝트 랭킹 Top 100 - Supple 블로그 - Medium

한국의 대표 오픈소스 프로젝트, 그리고 이를 만드는 사람과 회사

medium.com

 

우분투 프로그램을 켜서 깃을 실행한다.

lee@DESKTOP-LQUFETQ:~$ git
usage: git [--version] [--help] [-C <path>] [-c <name>=<value>]
           [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
           [-p | --paginate | --no-pager] [--no-replace-objects] [--bare]
           [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
           <command> [<args>]

These are common Git commands used in various situations:

start a working area (see also: git help tutorial)
   clone      Clone a repository into a new directory
   init       Create an empty Git repository or reinitialize an existing one

work on the current change (see also: git help everyday)
   add        Add file contents to the index
   mv         Move or rename a file, a directory, or a symlink
   reset      Reset current HEAD to the specified state
   rm         Remove files from the working tree and from the index

examine the history and state (see also: git help revisions)
   bisect     Use binary search to find the commit that introduced a bug
   grep       Print lines matching a pattern
   log        Show commit logs
   show       Show various types of objects
   status     Show the working tree status

grow, mark and tweak your common history
   branch     List, create, or delete branches
   checkout   Switch branches or restore working tree files
   commit     Record changes to the repository
   diff       Show changes between commits, commit and working tree, etc
   merge      Join two or more development histories together
   rebase     Reapply commits on top of another base tip
   tag        Create, list, delete or verify a tag object signed with GPG

collaborate (see also: git help workflows)
   fetch      Download objects and refs from another repository
   pull       Fetch from and integrate with another repository or a local branch
   push       Update remote refs along with associated objects

'git help -a' and 'git help -g' list available subcommands and some
concept guides. See 'git help <command>' or 'git help <concept>'
to read about a specific subcommand or concept.

 

오픈 소스 중 1위 fzf 프로젝트를 설치해보자.

 

 

Clone or download를 눌러 URL을 복사 후 붙여넣기한다. 문법은 git clone url

 

lee@DESKTOP-LQUFETQ:~$ git clone https://github.com/junegunn/fzf.git fzf_project_sc
Cloning into 'fzf_project_sc'...
remote: Enumerating objects: 24, done.
remote: Counting objects: 100% (24/24), done.
remote: Compressing objects: 100% (23/23), done.
remote: Total 7872 (delta 7), reused 3 (delta 1), pack-reused 7848
Receiving objects: 100% (7872/7872), 2.73 MiB | 484.00 KiB/s, done.
Resolving deltas: 100% (4924/4924), done.
lee@DESKTOP-LQUFETQ:~$ cd fzf_project_sc/
lee@DESKTOP-LQUFETQ:~/fzf_project_sc$ ls -l
total 100
-rw-rw-rw- 1 lee lee  1157 Jul 19 15:57 BUILD.md
-rw-rw-rw- 1 lee lee 22076 Jul 19 15:57 CHANGELOG.md
-rw-rw-rw- 1 lee lee   475 Jul 19 15:57 Dockerfile
-rw-rw-rw- 1 lee lee  1080 Jul 19 15:57 LICENSE
-rw-rw-rw- 1 lee lee  4315 Jul 19 15:57 Makefile
-rw-rw-rw- 1 lee lee  8857 Jul 19 15:57 README-VIM.md
-rw-rw-rw- 1 lee lee 19043 Jul 19 15:57 README.md
drwxrwxrwx 1 lee lee  4096 Jul 19 15:57 bin
drwxrwxrwx 1 lee lee  4096 Jul 19 15:57 doc
-rw-rw-rw- 1 lee lee   917 Jul 19 15:57 go.mod
-rw-rw-rw- 1 lee lee  2867 Jul 19 15:57 go.sum
-rwxrwxrwx 1 lee lee 10632 Jul 19 15:57 install
-rw-rw-rw- 1 lee lee   128 Jul 19 15:57 main.go
drwxrwxrwx 1 lee lee  4096 Jul 19 15:57 man
drwxrwxrwx 1 lee lee  4096 Jul 19 15:57 plugin
drwxrwxrwx 1 lee lee  4096 Jul 19 15:57 shell
drwxrwxrwx 1 lee lee  4096 Jul 19 15:57 src
drwxrwxrwx 1 lee lee  4096 Jul 19 15:57 test
-rwxrwxrwx 1 lee lee  2530 Jul 19 15:57 uninstall
lee@DESKTOP-LQUFETQ:~/fzf_project_sc$
728x90
728x90

'OS > Linux' 카테고리의 다른 글

리눅스 기본 문법 (우분투 프로그램 사용)  (0) 2019.07.19
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

파일 복사 / 폴더복사

cp   /dev/test.html
cp   -r   /dev/aaa

 

파일 이름 변경하기

mv /home/user/Files/filename1.ext /home/user/Files/filename2.ext

 

 

To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

lee@DESKTOP-LQUFETQ:~$ pwd
/home/lee
lee@DESKTOP-LQUFETQ:~$ ls
lee@DESKTOP-LQUFETQ:~$ ls -al
total 8
drwxr-xr-x 1 lee  lee  4096 Jul 17 16:30 .
drwxr-xr-x 1 root root 4096 Jul 17 16:20 ..
-rw------- 1 lee  lee    27 Jul 17 16:30 .bash_history
-rw-r--r-- 1 lee  lee   220 Jul 17 16:20 .bash_logout
-rw-r--r-- 1 lee  lee  3771 Jul 17 16:20 .bashrc
-rw-r--r-- 1 lee  lee   807 Jul 17 16:20 .profile
lee@DESKTOP-LQUFETQ:~$ cd ..
lee@DESKTOP-LQUFETQ:/home$ ls -l
total 0
drwxr-xr-x 1 lee lee 4096 Jul 17 16:30 lee
lee@DESKTOP-LQUFETQ:/home$ cd lee
lee@DESKTOP-LQUFETQ:~$ pwd
/home/lee
lee@DESKTOP-LQUFETQ:~$ mkdir
mkdir: missing operand
Try 'mkdir --help' for more information.
lee@DESKTOP-LQUFETQ:~$ mkdir hello_linux
lee@DESKTOP-LQUFETQ:~$ ls -l
total 0
drwxrwxrwx 1 lee lee 4096 Jul 19 09:17 hello_linux
lee@DESKTOP-LQUFETQ:~$ cd hello_linux/
lee@DESKTOP-LQUFETQ:~/hello_linux$ cd /
lee@DESKTOP-LQUFETQ:/$ ls -l
total 88
drwxr-xr-x  1 root root  4096 Jul 17 16:06 bin
drwxr-xr-x  1 root root  4096 May 21 23:42 boot
drwxr-xr-x  1 root root  4096 Jul 19 09:11 dev
drwxr-xr-x  1 root root  4096 Jul 17 16:20 etc
drwxr-xr-x  1 root root  4096 Jul 17 16:20 home
-rwxr-xr-x  1 root root 87944 Jan  1  1970 init
drwxr-xr-x  1 root root  4096 May 21 23:41 lib
drwxr-xr-x  1 root root  4096 May 21 23:39 lib64
drwxr-xr-x  1 root root  4096 May 21 23:39 media
drwxr-xr-x  1 root root  4096 Jul 17 16:06 mnt
drwxr-xr-x  1 root root  4096 May 21 23:39 opt
dr-xr-xr-x  9 root root     0 Jul 19 09:11 proc
drwx------  1 root root  4096 May 21 23:42 root
drwxr-xr-x  1 root root  4096 Jul 19 09:11 run
drwxr-xr-x  1 root root  4096 May 21 23:42 sbin
drwxr-xr-x  1 root root  4096 Mar 21 18:55 snap
drwxr-xr-x  1 root root  4096 May 21 23:39 srv
dr-xr-xr-x 12 root root     0 Jul 19 09:11 sys
drwxrwxrwt  1 root root  4096 Jul 19 09:19 tmp
drwxr-xr-x  1 root root  4096 May 21 23:39 usr
drwxr-xr-x  1 root root  4096 May 21 23:42 var
lee@DESKTOP-LQUFETQ:/$ cd /home /lee
-bash: cd: too many arguments
lee@DESKTOP-LQUFETQ:/$ cd/home/lee
-bash: cd/home/lee: No such file or directory
lee@DESKTOP-LQUFETQ:/$ cd /home/lee
lee@DESKTOP-LQUFETQ:~$ touch empty_file.txt
lee@DESKTOP-LQUFETQ:~$ ls -l
total 0
-rw-rw-rw- 1 lee lee    0 Jul 19 09:22 empty_file.txt
drwxrwxrwx 1 lee lee 4096 Jul 19 09:17 hello_linux
lee@DESKTOP-LQUFETQ:~$ ls --help
Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.

Mandatory arguments to long options are mandatory for short options too.
  -a, --all                  do not ignore entries starting with .
  -A, --almost-all           do not list implied . and ..
      --author               with -l, print the author of each file
  -b, --escape               print C-style escapes for nongraphic characters
      --block-size=SIZE      scale sizes by SIZE before printing them; e.g.,
                               '--block-size=M' prints sizes in units of
                               1,048,576 bytes; see SIZE format below
  -B, --ignore-backups       do not list implied entries ending with ~
  -c                         with -lt: sort by, and show, ctime (time of last
                               modification of file status information);
                               with -l: show ctime and sort by name;
                               otherwise: sort by ctime, newest first
  -C                         list entries by columns
      --color[=WHEN]         colorize the output; WHEN can be 'always' (default
                               if omitted), 'auto', or 'never'; more info below
  -d, --directory            list directories themselves, not their contents
  -D, --dired                generate output designed for Emacs' dired mode
  -f                         do not sort, enable -aU, disable -ls --color
  -F, --classify             append indicator (one of */=>@|) to entries
      --file-type            likewise, except do not append '*'
      --format=WORD          across -x, commas -m, horizontal -x, long -l,
                               single-column -1, verbose -l, vertical -C
      --full-time            like -l --time-style=full-iso
  -g                         like -l, but do not list owner
      --group-directories-first
                             group directories before files;
                               can be augmented with a --sort option, but any
                               use of --sort=none (-U) disables grouping
  -G, --no-group             in a long listing, don't print group names
  -h, --human-readable       with -l and/or -s, print human readable sizes
                               (e.g., 1K 234M 2G)
      --si                   likewise, but use powers of 1000 not 1024
  -H, --dereference-command-line
                             follow symbolic links listed on the command line
      --dereference-command-line-symlink-to-dir
                             follow each command line symbolic link
                               that points to a directory
      --hide=PATTERN         do not list implied entries matching shell PATTERN
                               (overridden by -a or -A)
      --hyperlink[=WHEN]     hyperlink file names; WHEN can be 'always'
                               (default if omitted), 'auto', or 'never'
      --indicator-style=WORD  append indicator with style WORD to entry names:
                               none (default), slash (-p),
                               file-type (--file-type), classify (-F)
  -i, --inode                print the index number of each file
  -I, --ignore=PATTERN       do not list implied entries matching shell PATTERN
  -k, --kibibytes            default to 1024-byte blocks for disk usage
  -l                         use a long listing format
  -L, --dereference          when showing file information for a symbolic
                               link, show information for the file the link
                               references rather than for the link itself
  -m                         fill width with a comma separated list of entries
  -n, --numeric-uid-gid      like -l, but list numeric user and group IDs
  -N, --literal              print entry names without quoting
  -o                         like -l, but do not list group information
  -p, --indicator-style=slash
                             append / indicator to directories
  -q, --hide-control-chars   print ? instead of nongraphic characters
      --show-control-chars   show nongraphic characters as-is (the default,
                               unless program is 'ls' and output is a terminal)
  -Q, --quote-name           enclose entry names in double quotes
      --quoting-style=WORD   use quoting style WORD for entry names:
                               literal, locale, shell, shell-always,
                               shell-escape, shell-escape-always, c, escape
  -r, --reverse              reverse order while sorting
  -R, --recursive            list subdirectories recursively
  -s, --size                 print the allocated size of each file, in blocks
  -S                         sort by file size, largest first
      --sort=WORD            sort by WORD instead of name: none (-U), size (-S),
                               time (-t), version (-v), extension (-X)
      --time=WORD            with -l, show time as WORD instead of default
                               modification time: atime or access or use (-u);
                               ctime or status (-c); also use specified time
                               as sort key if --sort=time (newest first)
      --time-style=STYLE     with -l, show times using style STYLE:
                               full-iso, long-iso, iso, locale, or +FORMAT;
                               FORMAT is interpreted like in 'date'; if FORMAT
                               is FORMAT1<newline>FORMAT2, then FORMAT1 applies
                               to non-recent files and FORMAT2 to recent files;
                               if STYLE is prefixed with 'posix-', STYLE
                               takes effect only outside the POSIX locale
  -t                         sort by modification time, newest first
  -T, --tabsize=COLS         assume tab stops at each COLS instead of 8
  -u                         with -lt: sort by, and show, access time;
                               with -l: show access time and sort by name;
                               otherwise: sort by access time, newest first
  -U                         do not sort; list entries in directory order
  -v                         natural sort of (version) numbers within text
  -w, --width=COLS           set output width to COLS.  0 means no limit
  -x                         list entries by lines instead of by columns
  -X                         sort alphabetically by entry extension
  -Z, --context              print any security context of each file
  -1                         list one file per line.  Avoid '\n' with -q or -b
      --help     display this help and exit
      --version  output version information and exit

The SIZE argument is an integer and optional unit (example: 10K is 10*1024).
Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,... (powers of 1000).

Using color to distinguish file types is disabled both by default and
with --color=never.  With --color=auto, ls emits color codes only when
standard output is connected to a terminal.  The LS_COLORS environment
variable can change the settings.  Use the dircolors command to set it.

Exit status:
 0  if OK,
 1  if minor problems (e.g., cannot access subdirectory),
 2  if serious trouble (e.g., cannot access command-line argument).

GNU coreutils online help: <http://www.gnu.org/software/coreutils/>
Report ls translation bugs to <http://translationproject.org/team/>
Full documentation at: <http://www.gnu.org/software/coreutils/ls>
or available locally via: info '(coreutils) ls invocation'
lee@DESKTOP-LQUFETQ:~$ rm empty_file.txt
lee@DESKTOP-LQUFETQ:~$ ls
hello_linux
lee@DESKTOP-LQUFETQ:~$ rm -r hello_linux
lee@DESKTOP-LQUFETQ:~$ ls
lee@DESKTOP-LQUFETQ:~$ touch cp.txt
lee@DESKTOP-LQUFETQ:~$ ls -l
total 0
-rw-rw-rw- 1 lee lee 0 Jul 19 09:29 cp.txt
lee@DESKTOP-LQUFETQ:~$ mkdir cpdir
lee@DESKTOP-LQUFETQ:~$ ls -l
total 0
-rw-rw-rw- 1 lee lee    0 Jul 19 09:29 cp.txt
drwxrwxrwx 1 lee lee 4096 Jul 19 09:30 cpdir
lee@DESKTOP-LQUFETQ:~$ cp cp.txt /home/lee/cpdir/cp.txt
lee@DESKTOP-LQUFETQ:~$ ls -l
total 0
-rw-rw-rw- 1 lee lee    0 Jul 19 09:29 cp.txt
drwxrwxrwx 1 lee lee 4096 Jul 19 09:31 cpdir
lee@DESKTOP-LQUFETQ:~$ cd cpdir
lee@DESKTOP-LQUFETQ:~/cpdir$ ls -l
total 0
-rw-rw-rw- 1 lee lee 0 Jul 19 09:31 cp.txt
lee@DESKTOP-LQUFETQ:~/cpdir$ cd ..
lee@DESKTOP-LQUFETQ:~$ rm cp.txt
lee@DESKTOP-LQUFETQ:~$ mv /home/lee/cpdir/cp.txt cp.txt
lee@DESKTOP-LQUFETQ:~$ ls -l
total 0
-rw-rw-rw- 1 lee lee    0 Jul 19 09:31 cp.txt
drwxrwxrwx 1 lee lee 4096 Jul 19 09:36 cpdir
lee@DESKTOP-LQUFETQ:~$ cd cpdir/
lee@DESKTOP-LQUFETQ:~/cpdir$ ls -l
total 0
lee@DESKTOP-LQUFETQ:~/cpdir$ cd..

cd..: command not found
lee@DESKTOP-LQUFETQ:~/cpdir$
lee@DESKTOP-LQUFETQ:~/cpdir$ cd ..
lee@DESKTOP-LQUFETQ:~$ touch name.txt
lee@DESKTOP-LQUFETQ:~$ rename name.txt name2.txt

Command 'rename' not found, but can be installed with:

sudo apt install rename

lee@DESKTOP-LQUFETQ:~$ mv name.txt name2.txt
lee@DESKTOP-LQUFETQ:~$ ls -l
total 0
-rw-rw-rw- 1 lee lee    0 Jul 19 09:31 cp.txt
drwxrwxrwx 1 lee lee 4096 Jul 19 09:36 cpdir
-rw-rw-rw- 1 lee lee    0 Jul 19 09:42 name2.txt
lee@DESKTOP-LQUFETQ:~$ apt-get install git
E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?
lee@DESKTOP-LQUFETQ:~$ sudo apt-get install git
[sudo] password for lee:
Reading package lists... Done
Building dependency tree
Reading state information... Done
git is already the newest version (1:2.17.1-1ubuntu0.4).
git set to manually installed.
The following package was automatically installed and is no longer required:
  libfreetype6
Use 'sudo apt autoremove' to remove it.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
lee@DESKTOP-LQUFETQ:~$ nano
lee@DESKTOP-LQUFETQ:~$ ls - l
ls: cannot access '-': No such file or directory
ls: cannot access 'l': No such file or directory
lee@DESKTOP-LQUFETQ:~$ ls -l
total 0
-rw-rw-rw- 1 lee lee    0 Jul 19 09:31 cp.txt
drwxrwxrwx 1 lee lee 4096 Jul 19 09:36 cpdir
-rw-rw-rw- 1 lee lee   15 Jul 19 10:10 hello.html
-rw-rw-rw- 1 lee lee    0 Jul 19 09:42 name2.txt
lee@DESKTOP-LQUFETQ:~$ cat hello.html
<html>
</html>
lee@DESKTOP-LQUFETQ:~$ nano hello.html
Use "fg" to return to nano.

[1]+  Stopped                 nano hello.html
lee@DESKTOP-LQUFETQ:~$ nano hello.html
lee@DESKTOP-LQUFETQ:~$ cat hello.html
<html>
<body>
        nano
        hello
        hello
</body>
</html>
lee@DESKTOP-LQUFETQ:~$ apt-get update
Reading package lists... Done
E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)
E: Unable to lock directory /var/lib/apt/lists/
W: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied)
W: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied)
lee@DESKTOP-LQUFETQ:~$ sudo apt-get update
lee@DESKTOP-LQUFETQ:~$ sudo apt-cache search htop
htop - interactive processes viewer
aha - ANSI color to HTML converter
libauthen-oath-perl - Perl module for OATH One Time Passwords
pftools - build and search protein and DNA generalized profiles
lee@DESKTOP-LQUFETQ:~$ sudo apt-get install htop
Reading package lists... Done
Building dependency tree
Reading state information... Done
htop is already the newest version (2.1.0-3).
htop set to manually installed.
The following package was automatically installed and is no longer required:
  libfreetype6
Use 'sudo apt autoremove' to remove it.
0 upgraded, 0 newly installed, 0 to remove and 87 not upgraded.
lee@DESKTOP-LQUFETQ:~$ htop
lee@DESKTOP-LQUFETQ:~$ sudo apt-get upgrade
728x90
728x90

'OS > Linux' 카테고리의 다른 글

리눅스(우분투) 깃 설치하기  (0) 2019.07.19
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

chart.js 로 차트 그리기

getting-started 에 들어가서 script 링크를 헤더에 붙여넣는다.

 

Getting Started · Chart.js documentation

No results matching ""

www.chartjs.org

 <!-- 차트 링크 -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
// 자바스크립트로 다음중 하나를 사용합니다.
var ctx = document.getElementById('myChart'); 
var ctx = document.getElementById('myChart').getContext('2d'); 
var ctx = $('#myChart');    // jQuery 사용
var ctx = 'myChart';

 


 

바타입 HTML

<!DOCTYPE html>
<html lang="en">
<!-- <html lang="en" style="height: 100%"> -->

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>부트스트랩 차트그리기</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <!-- 차트 링크 -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
</head>

<body>
  <div class="container">
    <canvas id="myChart"></canvas>
  </div>

  <!-- 부트스트랩 -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
    integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
    crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
    integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
    crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
    integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
    crossorigin="anonymous"></script>
  <!-- 차트 -->
  <script>
    var ctx = document.getElementById('myChart');
    var myChart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
        datasets: [{
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3],
          backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)'
          ],
          borderColor: [
            'rgba(255, 99, 132, 1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)'
          ],
          borderWidth: 1
        }]
      },
      options: {
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
      }
    });

  </script>
</body>

</html>

 


 

라인타입 HTML

 

<!DOCTYPE html>
<html lang="en">
<!-- <html lang="en" style="height: 100%"> -->

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>부트스트랩 차트그리기</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <!-- 차트 링크 -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
</head>

<body>
  <div class="container">
    <canvas id="myChart"></canvas>
  </div>

  <!-- 부트스트랩 -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
    integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
    crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
    integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
    crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
    integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
    crossorigin="anonymous"></script>
  <!-- 차트 -->
  <script>
    var ctx = document.getElementById('myChart').getContext('2d');
    var chart = new Chart(ctx, {
      // 챠트 종류를 선택
      type: 'line',

      // 챠트를 그릴 데이타
      data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
          label: 'My First dataset',
          backgroundColor: 'transparent',
          borderColor: 'red',
          data: [0, 10, 5, 2, 20, 30, 45]
        }]
      },
      // 옵션
      options: {}
    });
  </script>
</body>

</html>

 

 

 data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
          label: 'My First dataset',
          backgroundColor: 'transparent',
          borderColor: 'red',
          data: [0, 10, 5, 2, 20, 30, 45]
        }]
      },
      // 옵션
      options: {
        legend: {
          display: false
        },
        title: {
          display : true,
          text: '라인차트 제목'
        }
      }
    });

 

 

 

그래프 카드 안에 넣기

<div class="container">
      <div class="row my-3">
          <div class="col">
              <h4>Bootstrap 4 Chart.js - Line Chart</h4>
          </div>
      </div>
      <div class="row my-2">
          <div class="col">
              <div class="card">
                  <div class="card-body">
                      <canvas id="myChart" height="100"></canvas>
                  </div>
              </div>
          </div>
      </div>
  </div>

 

 


 

다중 차트

const colors = ['red','yellow','blue','#c3e6cb','#dc3545','#6c757d'];
var chBar = document.getElementById("myChart");
  var chartData = {
    labels: ["S", "M", "T", "W", "T", "F", "S"],
    datasets: [{
    data: [589, 445, 483, 503, 689, 692, 634],
    backgroundColor: colors[0]
    },
    {
      data: [209, 245, 383, 403, 589, 692, 580],
      backgroundColor: colors[1]
    },
    {
      data: [489, 135, 483, 290, 189, 603, 600],
      backgroundColor: colors[2]
    },
    {
      data: [639, 465, 493, 478, 589, 632, 674],
      backgroundColor: colors[4]
    }]
  };
  var myChart = new Chart(chBar, {
    // 챠트 종류를 선택
    type: 'bar',

    // 챠트를 그릴 데이타
    data: chartData,

    // 옵션
    options: {
      legend: {
        display: false
      }
    }
  });

 

// chart colors
const colors = ['red','yellow','blue','#c3e6cb','#dc3545','#6c757d'];
// const datas = [589, 445, ...] 선언하고 아래서 datas 변수만 써줘도 된다.

var ctx = document.getElementById('myChart');

var chartData = {
  labels: ["S", "M", "T", "W", "T", "F", "S"],
  datasets: [{
    data: [589, 445, 483, 503, 689, 692, 634],
    backgroundColor: 'transparent',
    borderColor: colors[2],
    borderWidth: 3,
    pointBackgroundColor: colors[0]
  },
  {
    data: [346, 503, 609, 503, 589, 483, 445],
    backgroundColor: colors[1],
    borderColor: colors[0],
    borderWidth: 3,
    pointBackgroundColor: colors[0]
  }
  ]
};

var myChart = new Chart(ctx, {
    // 챠트 종류를 선택
    type: 'line',

    // 챠트를 그릴 데이타
    data: chartData,

    // 옵션
    options: {
      legend: {
        display: false
      }
    }
});

 

 

<!DOCTYPE html>
<html lang="en">
<!-- <html lang="en" style="height: 100%"> -->

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>부트스트랩 차트그리기</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <!-- 차트 링크 -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
</head>

<body>
  <div class="container">
      <div class="row my-3">
          <div class="col">
              <h4>Bootstrap 4 Chart.js - Chart</h4>
          </div>
      </div>
      <div class="row my-2">
          <div class="col-md-6">
              <div class="card">
                  <div class="card-body">
                      <canvas class="myChart"></canvas>
                  </div>
                  <div class="card-body text-center text-align-center">
                    <h3>Multi</h3>
                  </div>
              </div>
          </div>
      </div>
      <div class="row my-2">
          <div class="col-md-6">
              <div class="card">
                  <div class="card-body">
                      <canvas class="myChart"></canvas>
                  </div>
                  <div class="card-body text- text-">
                    <h3>Pie</h3>
                  </div>
              </div>
          </div>
      </div>
  </div>
  <!-- 부트스트랩 -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
    integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
    crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
    integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
    crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
    integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
    crossorigin="anonymous"></script>
  <!-- 차트 -->
  <script>
  const mydata = [10, 20, 30, 40];
  const mydataHalf = [5, 10, 20, 7];
  // var ctx = document.getElementById("myChart");
  var ctx = document.getElementsByClassName("myChart");

  var mixedChart = {
    type: 'bar',
    labels: ['1', '2', '3', '4'],
    datasets : [
      {
        label: 'Bar Dataset',
        data : mydata,
        backgroundColor: 'rgba(256, 0, 0, 0.1)'
      },
      {
        label: 'Line Dataset',
        data: mydataHalf,
        backgroundColor: 'transparent',
        borderColor: 'skyblue',
        type: 'line'
      }
    ]
    };
    var myChart = new Chart(ctx, {
      type: 'bar',
      data: mixedChart,
      options: {
        legend: {
          display: true
        }
      }
    });  
    // var myChart = new Chart(ctx, {
    //   type: 'bar',
    //   data: mixedChart,
    //   options: {
    //     legend: {
    //       display: true
    //     }
    //   }
    // });
  </script>
</body>
</html>

 

 


 

도넛 그래프, 원형 그래프 (차트)

<!DOCTYPE html>
<html lang="en">
<!-- <html lang="en" style="height: 100%"> -->

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>부트스트랩 차트그리기</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <!-- 차트 링크 -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
</head>

<body>
    <div class="container">
        <div class="row my-3">
            <div class="col-12">
                <h4>Bootstrap 4 Chart.js - Chart</h4>
            </div>
        </div>
        <div class="row my-2">
            <div class="col-lg-6">
                <div class="card">
                    <div class="card-body">
                        <canvas id="myChart1"></canvas>
                    </div>
                    <div class="card-footer text-center text-dark">
                      <h3>Pie</h3>
                    </div>
                </div>
            </div>
            <div class="col-lg-6">
                <div class="card">
                    <div class="card-body">
                        <canvas id="myChart2"></canvas>
                    </div>
                    <div class="card card-body text-center bg-primary">
                      <h3>Doughnut</h3>
                    </div>
                </div>
            </div>
        </div>
    </div>
  <!-- 부트스트랩 -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
    integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
    crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
    integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
    crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
    integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
    crossorigin="anonymous"></script>
  <!-- 차트 -->
  <script>
  data = {
        datasets: [{
            backgroundColor: ['red','yellow','blue'],
            data: [10, 20, 30]
        }],       
        // 라벨의 이름이 툴팁처럼 마우스가 근처에 오면 나타남
        labels: ['red','yellow','blue'] 
    };

  // 가운데 구멍이 없는 파이형 차트
  var ctx1 = document.getElementById("myChart1");
  var myPieChart = new Chart(ctx1, {
      type: 'pie',
      data: data,
      options: {}
  });
  // 도넛형 차트
  var ctx2 = document.getElementById("myChart2");
  var myDoughnutChart = new Chart(ctx2, {
      type: 'doughnut',
      data: data,
      options: {}
  });
  </script>
</body>

</html>

 

 

도넛 형태의 그래프 두께 조절하기

파이 타입으로 만든 뒤 cutoutPercentage 옵션에서 숫자로 조절한다.

 

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>부트스트랩 차트그리기</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
    integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <!-- 차트 링크 -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
</head>
<body>
    <div class="container">
        <div class="row my-3">
            <div class="col">
                <h4>Bootstrap 4 Chart.js - pie to donut</h4>
            </div>
        </div>
        <div class="row py-2">
            <div class="col-md-4 py-1">
                <div class="card">
                    <div class="card-body">
                        <canvas id="chDonut1"></canvas>
                    </div>
                </div>
            </div>
            <div class="col-md-4 py-1">
                <div class="card">
                    <div class="card-body">
                        <canvas id="chDonut2"></canvas>
                    </div>
                </div>
            </div>
            <div class="col-md-4 py-1">
                <div class="card">
                    <div class="card-body">
                        <canvas id="chDonut3"></canvas>
                    </div>
                </div>
            </div>
        </div>
      </div>
  <!-- 부트스트랩 -->
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
    integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
    crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
    integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
    crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
    integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
    crossorigin="anonymous"></script>
  <!-- 차트 -->
  <script>
 // chart colors
var colors = ['red','skyblue','yellowgreen','#c3e6cb','#dc3545','#6c757d'];

/* 3 donut charts */
var donutOptions = {
  cutoutPercentage: 30, //도넛두께 : 값이 클수록 얇아짐
  legend: {position:'bottom', padding:5, labels: {pointStyle:'circle', usePointStyle:true}}
};

// donut 1
var chDonutData1 = {
    labels: ['Bootstrap', 'Popper', 'Other'],
    datasets: [
      {
        backgroundColor: colors.slice(0,3),
        borderWidth: 0,
        data: [74, 11, 40]
      }
    ]
};

var chDonut1 = document.getElementById("chDonut1");
  if (chDonut1) {
    new Chart(chDonut1, {
      type: 'pie',
      data: chDonutData1,
      options: donutOptions
  });
}

// donut 2
var chDonutData2 = {
    labels: ['Wips', 'Pops', 'Dags'],
    datasets: [
      {
        backgroundColor: colors.slice(0,3),
        borderWidth: 0,
        data: [40, 45, 30]
      }
    ]
};
var chDonut2 = document.getElementById("chDonut2");
  if (chDonut2) {
    new Chart(chDonut2, {
      type: 'pie',
      data: chDonutData2,
      options: donutOptions
  });
}

// donut 3
var chDonutData3 = {
    labels: ['Angular', 'React', 'Other'],
    datasets: [
      {
        backgroundColor: colors.slice(0,3),
        borderWidth: 0,
        data: [21, 45, 55, 33]
      }
    ]
};
var chDonut3 = document.getElementById("chDonut3");
  if (chDonut3) {
    new Chart(chDonut3, {
      type: 'pie',
      data: chDonutData3,
      options: donutOptions
  });
} 
  </script>
</body>
</html>

 

728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

이번에는 파일업로드를 구현해볼 것이다. 아래는 Servlet 페이지의 Download에 들어가서 cos-20.08.zip을 다운받는다. 

https://servlets.com/cos

 

그리고 lib 폴더 안의 jar 파일을 빼서 WEB-INF > lib 위치에 cos.jar 파일을 복붙.

 

 

 

일반 사이트에서 파일을 업로드할 때를 기억해보면, 이름이 같을 경우 덮어쓰기 할 것이냐고 물어본다.
_copy나 1, 2 등 원본파일명 뒤에 숫자를 붙이기도 한다. 혹은, defaultrenamepolish...메소드 등을 사용해서 해결한다.

 

fileSelect.jsp

 

 


 

fileSelect.jsp

파일을 서버로 보내기 위해서는 방식이 무조건 post 여야 한다. get방식은 절대 쓸 수 없다.
그리고 enctype=... 부분도 꼭 필요하다.

<!-- fileSelect.jsp -->
<%@page contentType="text/html; charset=EUC-KR" %>
<!-- enctype 속성:  form을 전송할때 사용할 인코딩 방법 지정-->
<form method="post" action="viewPage.jsp" enctype="multipart/form-data">
user : <input name="user" value="홍길동"><br/>
title : <input name="title" value="파일업로드"><br/>
file : <input type="file" name="uploadFile"><br/>
<input type="submit" value="UPLOAD">
</form>

 

 

 

viewPage.jsp

<%@page import="java.io.File"%>
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@page contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<% 
	request.setCharacterEncoding("EUC-KR"); 
	final String saveFolder = "C:/Jsp/myapp/WebContent/fileupload/filestorage";
	final String encoding = "EUC-KR";
	final int maxSize = 10*1024*1024; //10mb
	try{
		//파일이 서버에 업로드되는 시점은 MultipartRequest 객체 생성 순간이다. 
		MultipartRequest multi = 
				new MultipartRequest(request, saveFolder, maxSize, encoding, 
						new DefaultFileRenamePolicy());
		//request가 되는 순간 null로 변한다.
		//out.print("성공");
		String fileName = multi.getFilesystemName("uploadFile");
		String original = multi.getOriginalFileName("uploadFile");
		//filename은 중복이름이 들어올 경우 자동으로 index가 붙는데, index되기 전의 원본명
		String type = multi.getContentType("uploadFile");
		File f =  multi.getFile("uploadFile");
		int len = 0;
		if(f!=null) {
			len = (int)f.length();
		}
		String user = multi.getParameter("user");
		String title = multi.getParameter("title");
%>
저장된 파일 : <%=fileName%><br/>
실제 파일 : <%=original%><br/>
파일 타입: <%=type%><br/>
파일 크기 : <%=len%><br/>
user : <%=user%><br/>
title : <%=title%><br/>
<a href="fileSelect.jsp">파일선택</a>
<%
	}catch (Exception e) {
		e.printStackTrace();
	}
%>

 

 

 

fileSelect.jsp

이어서 작성 예정
728x90
728x90

'Java Friends > JSP' 카테고리의 다른 글

jsp로 투표 프로그램 만들기  (0) 2019.07.22
JSP 방명록 구현하기  (0) 2019.07.15
JSP 회원가입, 로그인, 로그아웃 기능 구현  (1) 2019.07.11
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,
728x90
728x90

 

 

 

 

오늘은 방명록을 구현해볼 것이다. 기능은 로그인, 글쓰기, 수정과 삭제, 그리고 비밀글 작성이 들어가며 관리자의 경우 회원의 비밀글도 조회 및 삭제가 가능하다. 당연히 타 회원이 쓴 비밀글은 일반 회원이 볼 수 없다. 그럼 GO!

 

 

 

 


 

1. 테이블 생성

로그인과 회원가입의 상세한 기능은 이전 글을 참고. 회원 부분은 만들어 둔 기능을 활용한다.
그럼 첫 번째 작업 순서로 먼저 Mysql에 접속하여 쿼리문을 돌리면 테이블들이 생성된다.

 

 

 

table.sql

create table tblJoin(
	id char(20) primary key,
	pwd char(20) not null,
	name char(20) not null,
	email char(30),
	hp char(40),
	grade char(2) default '0'
)COLLATE='euckr_korean_ci';

create table tblGuestBook(
	num int primary key auto_increment,
	id char(20) not null,
	contents text,
	ip char(15) not null,
	regdate date,
	regtime datetime,
	secret char(2) default '0'
)COLLATE='euckr_korean_ci';

create table tblComment(
 	cnum int primary key auto_increment,
 	num int not null,
 	cid char(20) not null,
 	comment text,
 	cip char(15) not null,
 	cregDate date
)COLLATE='euckr_korean_ci';

 

 


 

 

2. 자바 파일 생성

guestbook 패키지를 만든 후 beans 파일들을 생성한다. 총 세 개가 필요하다. 
CommentBean.java, GuestBookBean.java, JoinBean.java.
그리고 DBConnectionMgr.java 파일을 전 패키지에서 가져와 복사한다.

 

 

DBConnectionMgr.java

package guestbook;

import java.sql.*;
import java.util.Properties;
import java.util.Vector;

public class DBConnectionMgr {
    private Vector connections = new Vector(10);
    private String _driver = "org.gjt.mm.mysql.Driver",
    _url = "jdbc:mysql://127.0.0.1:3306/mydb?useUnicode=true&characterEncoding=EUC_KR",
    _user = "root",
    _password = "1234";
    
    private boolean _traceOn = false;
    private boolean initialized = false;
    private int _openConnections = 50;
    private static DBConnectionMgr instance = null;

    public DBConnectionMgr() {
    }

    /** Use this method to set the maximum number of open connections before
     unused connections are closed.
     */

    public static DBConnectionMgr getInstance() {
        if (instance == null) {
            synchronized (DBConnectionMgr.class) {
                if (instance == null) {
                    instance = new DBConnectionMgr();
                }
            }
        }

        return instance;
    }

    public void setOpenConnectionCount(int count) {
        _openConnections = count;
    }


    public void setEnableTrace(boolean enable) {
        _traceOn = enable;
    }


    /** Returns a Vector of java.sql.Connection objects */
    public Vector getConnectionList() {
        return connections;
    }


    /** Opens specified "count" of connections and adds them to the existing pool */
    public synchronized void setInitOpenConnections(int count)
            throws SQLException {
        Connection c = null;
        ConnectionObject co = null;

        for (int i = 0; i < count; i++) {
            c = createConnection();
            co = new ConnectionObject(c, false);

            connections.addElement(co);
            trace("ConnectionPoolManager: Adding new DB connection to pool (" + connections.size() + ")");
        }
    }


    /** Returns a count of open connections */
    public int getConnectionCount() {
        return connections.size();
    }


    /** Returns an unused existing or new connection.  */
    public synchronized Connection getConnection()
            throws Exception {
        if (!initialized) {
            Class c = Class.forName(_driver);
            DriverManager.registerDriver((Driver) c.newInstance());

            initialized = true;
        }


        Connection c = null;
        ConnectionObject co = null;
        boolean badConnection = false;


        for (int i = 0; i < connections.size(); i++) {
            co = (ConnectionObject) connections.elementAt(i);

            // If connection is not in use, test to ensure it's still valid!
            if (!co.inUse) {
                try {
                    badConnection = co.connection.isClosed();
                    if (!badConnection)
                        badConnection = (co.connection.getWarnings() != null);
                } catch (Exception e) {
                    badConnection = true;
                    e.printStackTrace();
                }

                // Connection is bad, remove from pool
                if (badConnection) {
                    connections.removeElementAt(i);
                    trace("ConnectionPoolManager: Remove disconnected DB connection #" + i);
                    continue;
                }

                c = co.connection;
                co.inUse = true;

                trace("ConnectionPoolManager: Using existing DB connection #" + (i + 1));
                break;
            }
        }

        if (c == null) {
            c = createConnection();
            co = new ConnectionObject(c, true);
            connections.addElement(co);

            trace("ConnectionPoolManager: Creating new DB connection #" + connections.size());
        }

        return c;
    }


    /** Marks a flag in the ConnectionObject to indicate this connection is no longer in use */
    public synchronized void freeConnection(Connection c) {
        if (c == null)
            return;

        ConnectionObject co = null;

        for (int i = 0; i < connections.size(); i++) {
            co = (ConnectionObject) connections.elementAt(i);
            if (c == co.connection) {
                co.inUse = false;
                break;
            }
        }

        for (int i = 0; i < connections.size(); i++) {
            co = (ConnectionObject) connections.elementAt(i);
            if ((i + 1) > _openConnections && !co.inUse)
                removeConnection(co.connection);
        }
    }

    public void freeConnection(Connection c, PreparedStatement p, ResultSet r) {
        try {
            if (r != null) r.close();
            if (p != null) p.close();
            freeConnection(c);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void freeConnection(Connection c, Statement s, ResultSet r) {
        try {
            if (r != null) r.close();
            if (s != null) s.close();
            freeConnection(c);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void freeConnection(Connection c, PreparedStatement p) {
        try {
            if (p != null) p.close();
            freeConnection(c);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void freeConnection(Connection c, Statement s) {
        try {
            if (s != null) s.close();
            freeConnection(c);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    /** Marks a flag in the ConnectionObject to indicate this connection is no longer in use */
    public synchronized void removeConnection(Connection c) {
        if (c == null)
            return;

        ConnectionObject co = null;
        for (int i = 0; i < connections.size(); i++) {
            co = (ConnectionObject) connections.elementAt(i);
            if (c == co.connection) {
                try {
                    c.close();
                    connections.removeElementAt(i);
                    trace("Removed " + c.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            }
        }
    }


    private Connection createConnection()
            throws SQLException {
        Connection con = null;

        try {
            if (_user == null)
                _user = "";
            if (_password == null)
                _password = "";

            Properties props = new Properties();
            props.put("user", _user);
            props.put("password", _password);

            con = DriverManager.getConnection(_url, props);
        } catch (Throwable t) {
            throw new SQLException(t.getMessage());
        }

        return con;
    }


    /** Closes all connections and clears out the connection pool */
    public void releaseFreeConnections() {
        trace("ConnectionPoolManager.releaseFreeConnections()");

        Connection c = null;
        ConnectionObject co = null;

        for (int i = 0; i < connections.size(); i++) {
            co = (ConnectionObject) connections.elementAt(i);
            if (!co.inUse)
                removeConnection(co.connection);
        }
    }


    /** Closes all connections and clears out the connection pool */
    public void finalize() {
        trace("ConnectionPoolManager.finalize()");

        Connection c = null;
        ConnectionObject co = null;

        for (int i = 0; i < connections.size(); i++) {
            co = (ConnectionObject) connections.elementAt(i);
            try {
                co.connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            co = null;
        }

        connections.removeAllElements();
    }


    private void trace(String s) {
        if (_traceOn)
            System.err.println(s);
    }

}


class ConnectionObject {
    public java.sql.Connection connection = null;
    public boolean inUse = false;

    public ConnectionObject(Connection c, boolean useFlag) {
        connection = c;
        inUse = useFlag;
    }
}

 

 

 

CommentBean.java

package guestbook;

public class CommentBean {
	private int cnum;
	private int num;
	private String cid;
	private String comment;
	private String cip;
	private String cregDate;
	public int getCnum() {
		return cnum;
	}
	public void setCnum(int cnum) {
		this.cnum = cnum;
	}
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public String getCid() {
		return cid;
	}
	public void setCid(String cid) {
		this.cid = cid;
	}
	public String getComment() {
		return comment;
	}
	public void setComment(String comment) {
		this.comment = comment;
	}
	public String getCip() {
		return cip;
	}
	public void setCip(String cip) {
		this.cip = cip;
	}
	public String getCregDate() {
		return cregDate;
	}
	public void setCregDate(String cregDate) {
		this.cregDate = cregDate;
	}
}

 

 

 

GuestBookBean.java

package guestbook;

public class GuestBookBean {
	private int num;
	private String id;
	private String contents;
	private String ip;
	private String regdate;
	private String regtime;
	private String secret;
	
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getContents() {
		return contents;
	}
	public void setContents(String contents) {
		this.contents = contents;
	}
	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public String getRegdate() {
		return regdate;
	}
	public void setRegdate(String regdate) {
		this.regdate = regdate;
	}
	public String getRegtime() {
		return regtime;
	}
	public void setRegtime(String regtime) {
		this.regtime = regtime;
	}
	public String getSecret() {
		return secret;
	}
	public void setSecret(String secret) {
		this.secret = secret;
	}
	
}

 

 

 

JoinBean.java.

package guestbook;

public class JoinBean {
	private String id;
	private String pwd;
	private String name;
	private String email;
	private String hp;
	private String grade;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getHp() {
		return hp;
	}
	public void setHp(String hp) {
		this.hp = hp;
	}
	public String getGrade() {
		return grade;
	}
	public void setGrade(String grade) {
		this.grade = grade;
	}
}

 

 

 

GuestBookMgr.java

package guestbook;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Vector;

public class GuestBookMgr {
	
	private DBConnectionMgr pool;
	private final SimpleDateFormat SDF_DATE =
			new SimpleDateFormat("yyyy'년'  M'월' d'일' (E)");
	private final SimpleDateFormat SDF_TIME =
			new SimpleDateFormat("H:mm:ss");
	
	public GuestBookMgr() {
		pool = DBConnectionMgr.getInstance();
	}

	//Join Login
	public boolean loginJoin(String id, String pwd) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		boolean flag = false;
		try {
			con = pool.getConnection();
			sql = "select * from tblJoin where id=? and pwd =?";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			pstmt.setString(2, pwd);
			if(pstmt.executeQuery().next())
				flag = true;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return flag;
	}
	
	//Join Information
	public JoinBean getJoin(String id) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		JoinBean bean = new JoinBean();
		try {
			con = pool.getConnection();
			sql = "select * from tblJoin where id=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, id);
			rs = pstmt.executeQuery();
			if(rs.next()){
				bean.setId(rs.getString(1));
				bean.setPwd(rs.getString(2));
				bean.setName(rs.getString(3));
				bean.setEmail(rs.getString(4));
				bean.setHp(rs.getString(5));
				bean.setGrade(rs.getString(6));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return bean;
	}
	
	//GuestBook Insert
	public void insertGuestBook(GuestBookBean bean) {
		Connection con = null;
		PreparedStatement pstmt = null;
		String sql = null;
		try {
			con = pool.getConnection();
			sql = "insert tblGuestBook(id, contents, ip, regdate, regtime, secret) "
					+ "values (?,?,?, now(), now(), ?)";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, bean.getId());
			pstmt.setString(2, bean.getContents());
			pstmt.setString(3, bean.getIp());
			pstmt.setString(4, bean.getSecret());
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt);
		}
		return;
	}
	
	//GuestBook List : 비밀글은 본인 및 관리자만 볼 수 있다.
	public Vector<GuestBookBean> listGuestBook(String id, String grade){
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		Vector<GuestBookBean> vlist = new Vector<GuestBookBean>();		
		try {
			con = pool.getConnection();
			if(grade.equals("1"/*admin*/)) {
				sql = "select * from tblGuestBook order by num desc";
				pstmt = con.prepareStatement(sql);
			} else /*일반로그인*/ {
				sql = "select * from tblGuestBook where id=? or secret=? order by num desc";
				pstmt = con.prepareStatement(sql);
				pstmt.setString(1, id);
				pstmt.setString(2, "0"); //비밀글이 아닌 글	
			}
			rs = pstmt.executeQuery();
			while (rs.next()) {
				GuestBookBean bean = new GuestBookBean();
				bean.setNum(rs.getInt(1));
				bean.setId(rs.getString(2));
				bean.setContents(rs.getString(3));
				bean.setIp(rs.getString(4));
				String tempDate = SDF_DATE.format(rs.getDate(5));
				bean.setRegdate(tempDate);
				String tempTime = SDF_TIME.format(rs.getTime(6));
				bean.setRegtime(tempTime);
				bean.setSecret(rs.getString(7));
				vlist.addElement(bean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return vlist;
	}
	
	//GuestBook Read
	public GuestBookBean getGuestBook(int num) { 
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		GuestBookBean bean = new GuestBookBean();
		try {
			con = pool.getConnection();
			sql = " select * from tblGuestBook where num=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			rs = pstmt.executeQuery();  
			if(rs.next()) { // num이 pk 라 while 대신 if문
				bean.setNum(rs.getInt(1));
				bean.setId(rs.getString(2));
				bean.setContents(rs.getString(3));
				bean.setIp(rs.getString(4));
				String tempDate = SDF_DATE.format(rs.getDate(5));
				bean.setRegdate(tempDate);
				String tempTime = SDF_TIME.format(rs.getTime(6));
				bean.setRegtime(tempTime);
				bean.setSecret(rs.getString(7));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return bean;
	}
	
	//GuestBook Update : contents, ip, secret
	public void updateGuestBook (GuestBookBean bean) {  //rs x
		Connection con = null;
		PreparedStatement pstmt = null;
		String sql = null;
		try {
			con = pool.getConnection();
			sql = "update tblGuestBook set contents=?, ip=?, secret=? "
					+ "where num=?";
			pstmt = con.prepareStatement(sql);
			
			pstmt.setString(1, bean.getContents());
			pstmt.setString(2, bean.getIp());
			pstmt.setString(3, bean.getSecret());
			pstmt.setInt(4, bean.getNum());
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt);
		}
		return;
	}
	
	//GuestBook Delete
	public void deleteGuestBook (int num) { // num : pk
		Connection con = null;
		PreparedStatement pstmt = null;
		String sql = null;
		try {
			con = pool.getConnection();
			sql = "delete from tblGuestBook where num = ?";
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt);
		}
		return;
	}
	
	//Comment Insert
		public void insertComment(CommentBean bean) {
			Connection con = null;
			PreparedStatement pstmt = null;
			String sql = null;
			try {
				con = pool.getConnection();
				sql = "insert tblComment(num, cid, comment, cip, cregDate values (?,?,?,?,now())";
				pstmt = con.prepareStatement(sql);
				pstmt.setInt(1, bean.getNum());
				pstmt.setString(2, bean.getCid());
				pstmt.setString(3, bean.getComment());
				pstmt.setString(4, bean.getCip());				
				pstmt.executeUpdate();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				pool.freeConnection(con, pstmt);
			}
		}
		
	//Comment List
	public Vector<CommentBean> listComment(int num){
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		Vector<CommentBean> vlist = new Vector<CommentBean>();
		try {
			con = pool.getConnection();
			sql = " select * from tblComment where num=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			rs = pstmt.executeQuery();
			while(rs.next()) {
				CommentBean bean = new CommentBean();
				bean.setCnum(rs.getInt(1));
				bean.setNum(rs.getInt(2));
				bean.setCid(rs.getString(3));
				bean.setComment(rs.getString(4));
				bean.setCip(rs.getString(5));
				String tempDate = SDF_DATE.format(rs.getDate(6));
				bean.setCregDate(tempDate);
				vlist.addElement(bean);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
		return vlist;
	}
	
	//Comment Delete
	public void deleteComment(int cnum) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		try {
			con = pool.getConnection();
			sql = "delete from tblComment where cnum=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, cnum);
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
	}
	
	//Comment All Delete (원글이 삭제되면 댓글도 삭제)
	public void deleteAllComment(int num) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = null;
		try {
			con = pool.getConnection();
			sql = "delete from tblComment where cnum=?";
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, num);
			pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pool.freeConnection(con, pstmt, rs);
		}
	}
	
}

 

 


 

 

3. JSP 파일

 

login.jsp

<%@page contentType="text/html;charset=EUC_KR"%>
<jsp:useBean id="login" class="guestbook.JoinBean" scope="session"/>
<%
	request.setCharacterEncoding("EUC-KR");
	String id = (String)session.getAttribute("idKey");
	String url = request.getParameter("url");
%>
<title>로그인</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<body bgcolor="#996600">
<br><br>
<div align="center">
<%
		if(id!=null){
			%>
				<b><%=login.getName()%></b>님 환영합니다.<br>
				<a href="showGuestBook.jsp" >방명록 </a>&nbsp;
				<a href="logout.jsp" >로그아웃</a>
			<%
		}else{
%>
<h2>GuestBook 로그인</h2>
<FORM METHOD="POST" ACTION="loginProc.jsp?url=<%=url%>"><!-- get방식과 post방식 동시에 -->
<table border="1">
	<tr>
		<td>id</td>
		<td> <input name="id" value="aaa">
		</td>
	</tr>
	<tr>
		<td>pwd</td>
		<td><input name="pwd" value="1234"></td>
	</tr>
	<tr>
		<td align="center" colspan="2">
		<INPUT TYPE="submit" value="로그인">
		</td>
	</tr>
</table>
<input type="hidden" name="url" value="<%=url%>">
</FORM>
<%}%>
</div>
</body>

 

 

 

logout.jsp

<%@page contentType="text/html;charset=EUC-KR"%>
<%
    session.invalidate();
%>
<script>
   alert('로그아웃 되었습니다.');
   location.href="login.jsp"; 
</script>

 

 

 

loginProc.jsp

<%@page contentType="text/html;charset=EUC-KR"%>
<%request.setCharacterEncoding("EUC-KR");%>
<jsp:useBean id="mgr" class="guestbook.GuestBookMgr"/>
<jsp:useBean id="login" class="guestbook.JoinBean" scope="session"/>
<jsp:setProperty name="login" property="*"/>
<%
		String url="login.jsp";
		if(request.getParameter("url")!=null&&
				!request.getParameter("url").equals("null")){
			url=request.getParameter("url");
		}
		boolean flag = mgr.loginJoin(login.getId(), login.getPwd());
		String msg = "로그인 실패";
		if(flag){
			msg = "로그인 성공";
			login = mgr.getJoin(login.getId());
			session.setAttribute("idKey", login.getId());
			session.setAttribute("login", login);
		}
%>
<script>
	alert("<%=msg%>");	
	location.href="<%=url%>";
</script>

 

 

 

getSession.jsp

<%@page contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<% request.setCharacterEncoding("EUC-KR"); %> 
<%
	String id=(String)session.getAttribute("idKey");
	if(id==null){
		StringBuffer url = request.getRequestURL();
		response.sendRedirect("login.jsp?url="+url);
	}else {
		//닫는 중괄호는 이 페이지를 include하는 페이지에 구현
%> 

 

 

 

postGuestBook.jsp

<%@page pageEncoding="EUC-KR"%>
<jsp:useBean id="login" class="guestbook.JoinBean"  scope="session"/>
<html>
<head>
<title>GuestBook</title>
<script type="text/javascript">
	function checkInputs() {
		frm = document.postFrm;
		if(frm.contents.value==""){
			alert("내용을 입력해 주세요.");
			frm.contents.focus();
			return;
		}
		frm.submit();
	}
</script>
</head>
<body>
	<div align="center">
		<table cellspacing="0" cellpadding="3">
			<tr>
				<td bgcolor="#F5F5F5"><font size="4"><b>글올리기</b></font></td>
			</tr>
		</table>
		<form name="postFrm" method="post" action="processGuestBook.jsp">
			<table border="1" bordercolor="#000000" cellspacing="0" cellpadding="0">
				<tr>
					<td>
						<table>
							<tr>
								<td height="40" align="center">
								<img src="img/face.bmp" border="0" alt="성명"> 
								<input title="이름을 적어주세요" name="name" size="9" maxlength="20" value="<%=login.getName() %>" readonly>
								<img src="img/email.bmp" border="0" alt="메일">
								<input title="전자메일 주소를 적는 곳이군요" name="email" size="20"
									maxlength="80" value="<%=login.getEmail() %>"> 
								<img src="img/hp.bmp" border="0" alt="홈페이지"> 
								<input title="홈페이지도 있으면 알려주세요." name="hp" size="25"
									maxlength="80" value="<%=login.getHp()%>">
									</td>
							</tr>
							<tr>
								<td align="center">
									<textarea title="좋은 글 남겨주세요"
										name="contents" cols="60" rows="6">하이~~~</textarea>
								</td>
							</tr>
							<tr>
								<td width="500" height="30" colspan="3" align="center">
									<!-- table start -->
									<input type="hidden" name="id" value="<%=login.getId().trim()%>">
									<input type="button" value="글올리기" onclick="javascript:checkInputs()"> 
									<input type="reset" value="고치기">
									<input type="checkbox" name="secret" value="1">비밀글
									<!--table end  -->
								</td>
							</tr>
						</table>
					</td>
				</tr>
			</table>
		</form>
	</div>
</body>
</html>

 

 

 

 

postGuestBook.jsp

<%@page contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<% 
	request.setCharacterEncoding("EUC-KR"); 
%> 
<jsp:useBean id="mgr" class="guestbook.GuestBookMgr"></jsp:useBean>
<jsp:useBean id="bean" class="guestbook.GuestBookBean"></jsp:useBean>
<jsp:setProperty property="*" name="bean" />
<%
	// 방명록 ip값
	bean.setIp(request.getRemoteAddr());
	// 비밀글 체크를 안 한 상태
	if(bean.getSecret()==null){
		bean.setSecret("0");
	}
	mgr.insertGuestBook(bean);
	response.sendRedirect("showGuestBook.jsp");
%>

 

 

 

 

showGuestBook.jsp

<%@page import="guestbook.JoinBean"%>
<%@page import="guestbook.GuestBookBean"%>
<%@page import="guestbook.GuestBookMgr"%>
<%@page import="java.util.Vector"%>
<%@page contentType="text/html; charset=EUC-KR"%>
<%request.setCharacterEncoding("EUC-KR"); %>
<%@include file="getSession.jsp"%>
<%
	//GuestBookMgr mgr = new GuestBookMgr();
	//Vector<GuestBookBean> vlist = mgr.listGuestBook(login.getId(), login.getGrade());
%>

<html>
<head>
<title>GuestBook</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<script type="text/javascript"></script>
</head>
<body bgcolor="#996600">
	<div align="center">
<%@include file="postGuestBook.jsp"%>
<%
	GuestBookMgr mgr = new GuestBookMgr();
	Vector<GuestBookBean> vlist = mgr.listGuestBook(login.getId(), login.getGrade());
%>
		<table width="520" cellspacing="0" cellpadding="3">
			<tr bgcolor="#F5F5F5">
				<td><font size="2"> <b><%=login.getName()%></b>님 환영합니다.
				</font></td>
				<td align="right"><a href="logout.jsp">로그아웃</a></td>
			</tr>
		</table>
		<!-- GuestBook List Start -->
		<%
			if(vlist.isEmpty()){
		%>
		<table width="520" cellspacing="0" cellpadding="7">
			<tr>
				<td>등록된 글이 없습니다.</td>
			</tr>
		</table>
		<% } else {%>
		<%
			for(int i=0; i<vlist.size(); i++){
				GuestBookBean bean = vlist.get(i);
				//방명록 쓴 사람의 정보
				JoinBean writer = mgr.getJoin(bean.getId());
		%>
		<table width="520" border="1" bordercolor="#000000" cellspacing="0"
			cellpadding="0">
			<tr>
				<td>
					<table bgcolor="#F5F5F5">
						<tr>
							<td width="225">NO : <%=vlist.size()-i%></td>
							<td width="225"><img src="img/face.bmp" border="0" alt="이름">
								<a href="mailto:<%=writer.getEmail()%>"> <%=writer.getName() %></a>
							</td>
							<td width="150" align="center">
								<%if(writer.getHp()==null||writer.getHp().equals("")){
							out.print("홈페이지가 없네요.");
						}else{
						%> <a href="http://<%=writer.getHp()%>"> <img alt="홈페이지 "
									src="img/hp.bmp" border="0">
							</a> <%}%>
							</td>
						</tr>
						<tr>
							<td colspan="3"><%=bean.getContents() %></td>
						</tr>
						<tr>
							<td>IP : <%=bean.getIp()%></td>
							<td><%=bean.getRegdate()+" "+bean.getRegtime()%></td>
							<%
								//로그인 id랑 방명록 쓴 사람의 id가 동일하면 수정, 삭제, 비밀글 모드 활성화
								boolean chk = login.getId().equals(writer.getId());
								if (chk||login.getGrade().equals("1")){  //동일하거나 grade가 1이든지 (관리자)
									if(chk){
							%>
							<a href="">[수정]</a>
							<% } //관리자가 수정은 못하게 한다. %> 
							<a href="">[삭제]</a>
								<%=bean.getSecret().equals("1")?"비밀글":""	%>					
							<%}	%>
							<td>[수정][삭제][비밀글]</td>
						</tr>
					</table>
				</td>
			</tr>
		</table>
		<%} //--for%>
		<%}%>
		<!-- GuestBook List End -->
	</div>
</body>
</html>
<%}%>

 

 

 

 


 

기타. 이클립스에서 tomcat 연동시 getRemoteAddr 메소드에서 0:0:0:0:0:0:0:1 를 리턴하는 오류

Run -> Run Configurations" 메뉴 > 연동하는 Tomcat 서버를 선택 > "Arguments" 탭 > VM arguments 에 아래의 항목을 추가한 후, "Apply" 버튼을 클릭하고 "Close" 버튼을 클릭.

 

-Djava.net.preferIPv4Stack=true

 

 

이클립스에서 tomcat 연동시 getRemoteAddr 메소드에서 0:0:0:0:0:0:0:1 를 리턴하는 오류 해결하는 방법

이클립스에서 tomcat 연동하여서 tomcat 을 실행한 후, 웹 접속하면 웹 브라우저의 IP 주소를 가벼오는 g...

blog.naver.com

 

 

 

https://servlet.com/

728x90
728x90
블로그 이미지

coding-restaurant

코딩 맛집에 방문해주셔서 감사합니다.

,

v