본문 바로가기

   
Programming/Java

15일차!

반응형
학생정보관리
package kr.co.khta.score;

public class StudentApp {
     
      public static void main(String[] args){
            new StudentScoreMgr().displayMenu();
     }
     
}


package kr.co.khta.score;

public class StudentVO implements Comparable<StudentVO>{
      private int no;
      private String name;
      private String dept;
      private int kor;
      private int eng;
      private int math;
      private int total;
      private double avg;
     
      public StudentVO(){}


      public StudentVO( int no, String name, String dept, int kor, int eng,
                 int math) {
            super();
            this. no = no;
            this. name = name;
            this. dept = dept;
            this. kor = kor;
            this. eng = eng;
            this. math = math;
            this. total = kor + eng + math;
            this. avg = total/3;
     }


      @Override
      public String toString() {
            return "StudentVO [no=" + no + ", name=" + name + ", dept=" + dept
                     + ", kor=" + kor + ", eng=" + eng + ", math=" + math
                     + ", total=" + total + ", avg=" + avg + "]" ;
     }


      public int getNo() {
            return no;
     }


      public String getName() {
            return name;
     }


      public String getDept() {
            return dept;
     }


      public int getKor() {
            return kor;
     }


      public int getEng() {
            return eng;
     }


      public int getMath() {
            return math;
     }


      public int getTotal() {
            return total;
     }


      public double getAvg() {
            return avg;
     }


      @Override
      public int compareTo (StudentVO o ) {
            // TODO Auto-generated method stub
            int result = Integer.parseInt(String. valueOf(Math.round( o. avg - this. avg)));
            return result;
     }




     
}


package kr.co.khta.score;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

public class StudentScoreMgr {
     
      private Scanner scanner = new Scanner(System. in);
      private ArrayList<StudentVO> students = new ArrayList<StudentVO>();
     
      public void displayMenu(){
            while( true){
                 int selectMenuNo = menu();
                
                 switch (selectMenuNo ){
                 case 1:
                     inputScore();
                      break;
                 case 2:
                     displayAllStudentScore();
                      break;
                 case 3:
                     displayStudentScore();
                      break;
                 case 4:
                     displayByRanking();
                      break;
                 case 0:
                      break;
                 }
                
           }
           
     }
     
      private void inputScore(){
           System. out.println( "<< 학생 성적 입력하기 >>" );
           System. out.print( "학번을 입력하세요 : " );
            int no = scanner.nextInt();
           System. out.print( "이름을 입력하세요 : " );
           String name = scanner.next();        
           System. out.print( "학과를 입력하세요 : " );
           String dept = scanner.next();
           System. out.print( "국어점수를 입력하세요 : " );
            int kor = scanner.nextInt();
           System. out.print( "수학점수를 입력하세요 : " );
            int eng = scanner.nextInt();
           System. out.print( "영어점수를 입력하세요 : " );
            int math = scanner.nextInt();
            students.add( new StudentVO( no, name, dept, kor, eng, math));
     }
     
      private void displayAllStudentScore(){
           System. out.println( "<< 전체 학생 성적 보기 >>" );
            for(StudentVO s : students){
                print( s);
           }
     }

      private void print(StudentVO s) {
           System. out.print( " 학번 : " + s .getNo());
           System. out.print( " 이름 : " + s .getName());
           System. out.print( " 학과 : " + s .getDept());
           System. out.print( " 국어 : " + s .getKor());
           System. out.print( " 수학 : " + s .getMath());
           System. out.print( " 영어 : " + s .getEng());
           System. out.println();
     }
     
      private void displayStudentScore() {
           System. out.println();
           System. out.println( "<< 입력된 학번의 학생 성적 보기 >>");
           System. out.print( "조회할 학번이나 이름 입력 : " );
            int no  = 0;
           String name = null;
           String inputText = scanner.next();
           
            try{
                 no = Integer. parseInt( inputText);    
           } catch(NumberFormatException e){
                 name = inputText;
           }
           
            if( no != 0){
                 for(StudentVO s : students){
                      if( s.getNo() == no){
                           System. out.println( "입력된 학번의 학생의 성적입니다.");
                           print( s);
                     }
                }
           } else{
                 for(StudentVO s : students){
                 if( s.getName() == name){
                     System. out.println( "입력된 이름의 학생의 성적입니다.");
                     print( s);
                     }
                }
           }
     }
     
      private void displayByRanking(){
           System. out.println();
           System. out.println( "<< 정렬 방식을 선택하세요(학번:n, 이름:m, 학과:d, 성적:s) >>");
           String orderType = scanner.next();
           
           Collections. sort( students);
           
           ArrayList<StudentVO> copyStudents = (ArrayList<StudentVO>) students.clone();
            //Collections.sort(copyStudents);
           
            switch( orderType){
            case "n":
                Collections. sort( copyStudents, ( v1, v2) -> v1.getNo()- v2.getNo());
                 break;
            case "m":
                Collections. sort( copyStudents, ( v1, v2) -> v1.getName().compareTo( v2.getName()));
                 break;
            case "d":
                Collections. sort( copyStudents, ( v1, v2) -> v1.getDept().compareTo( v2.getDept()));
                 break;               
            case "s":
                Collections. sort( copyStudents, ( v1, v2) -> v1.getTotal()- v2.getTotal());
                 break;
           }
           
            for(StudentVO s : copyStudents){
                System. out.println( "성적순 학생 성적_________" );
                print( s);
           }
                     
           System. out.println();
     }
     
      private int menu(){
          System. out.println( "**********************************************" );
           System. out.println( "*                 성적 관리 프로그램                       *" );
          System. out.println( "**********************************************" );
           
           System. out.println( "1. 학생 성적 입력" );
           System. out.println( "2. 전체 학생 성적 보기" );
           System. out.println( "3. 지정된 학생의 성적 보기" );
           System. out.println( "4. 등수별로 보기" );
           System. out.println( "0. 종료하기" );
           
           System. out.print( "원하는 메뉴를 선택하세요 " );
            int menuNo = scanner.nextInt();
           
            return menuNo;
     }
}




AWT / SWING(AWP 개량버전과 무관)
SWT : 이클립스도 자바 SWT로 만들어짐
SWING : JAVA자체코딩 컴포넌트가 다양
package awt.basic;

import java.awt.Frame;

public class MyWindow extends Frame{

      public MyWindow() {
           setTitle( "내윈도우" );
           
            //해당 컴포넌트를 화면에 표시한다.
           setVisible( true);
           
            //setBounds(x좌표, y좌표, 너비, 높이)
           setBounds(100, 100, 300, 200);
     }
     
      public static void main(String[] args){
            new MyWindow();
     }
     
}






package awt.basic;

import java.awt.FlowLayout;

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

public class ComponentDemo extends JFrame{
      public ComponentDemo(){
           setTitle( "내 윈도우" );
           
            //setLayout(new FlowLayout());
           setLayout( null);
           
           JButton btn = new JButton( "내버튼" );
            btn.setSize(100, 30);
            btn.setLocation(50, 10);
           add( btn);
           
           JButton btn2 = new JButton( "내버튼" );
            btn2.setSize(100, 30);
            btn2.setLocation(150, 10);
           add( btn2);
           
           
           setVisible( true);
           setBounds(100, 100, 300, 200);
           
           setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE );
     }
     
      public static void main(String[] args) {
            new ComponentDemo();
     }
     
}




이벤트(GUI 프로그램 안에서의 모든행위)
- 행위시 마다 이벤트 객체가 계속 발생
- 버튼, 체크박스, 콤보박스 등 이벤트를 발생시키는놈 <- 이벤트 소스(Event Source)
-이벤트 발생시 하고싶은 일을 구현해 놓은것-> 이벤트 핸들러(Event Handler)
-이벤트가 발생하는지 안하는지 감시하는 역할 -> 이벤트 청취자(Event Listener)
-이벤트 청취자에게 이벤트 핸들러는 붙여놓는다.

-버튼을 클릭했을때 반응하는 이벤트, 텍스트 필드에서 엔터키를 입력했을 때 -> 액션이벤트
-키보드 버튼을 누를때마다 이벤트 발생 -> 키보드 이벤트
- 텍스트필드에서 변화가 있을때 발생 -> 텍스트 이벤트

ActionEvent          - ActionListener
     - button클릭
     - 메뉴선택
     - jtextfield에서 enter를 쳤을때
MouseEvent     - MouseListener
     - mouse 클릭, 포인트를 움직일때
KeyEvent     - KeyListener
     - 키보드를 눌렀을 때
ItemEvent     -ItemLister
     - 라디오버튼, 체크박스, 콤보박스의 항목을 선택/해제 할 때
TextEvent     - TextListener
     - jtextfield, jtextarea, jpasswordfield의 텍스트 내용이 변경될 때
WindowEvent     -WindowListener
     - 창을 활성화, 비활성화, 최소화, 최대화, 닫기 할때


package awt.basic;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;

public class ComponentDemo2 extends JFrame {
     
      public ComponentDemo2() {
           
           setLayout( null);
           
            //label 글자 나오게 하는것
           JLabel label1 = new JLabel( "이름" );
            label1.setBounds(50, 20, 100, 20);
           add( label1);
           
            //텍스트 입력창 만들기
           JTextField field1 = new JTextField();
            field1.setBounds(100, 20, 200, 30);
           add( field1);
           
           JLabel label2 = new JLabel( "성별" );
            label2.setBounds(50, 60, 100, 30);
           add( label2);
           
           JRadioButton radio1 = new JRadioButton( "남자" true );
            radio1.setBounds(100, 60, 100, 30);
           add( radio1);
           
           JRadioButton radio2 = new JRadioButton( "여자" true );
            radio2.setBounds(200, 60, 100, 30);
           add( radio2);
           
           ButtonGroup btnGroup = new ButtonGroup();
            btnGroup.add( radio1);
            btnGroup.add( radio2);
           
           JLabel label3 = new JLabel( "취미" );
            label3.setBounds(50, 100, 100, 30);
           add( label3);
           
           JCheckBox box1 = new JCheckBox( "게임" true );
            box1.setBounds(100, 100, 100, 30);
           add( box1);
           
           JCheckBox box2 = new JCheckBox( "운동" true );
            box2.setBounds(200, 100, 100, 30);
           add( box2);
           
           JCheckBox box3 = new JCheckBox( "등산" true );
            box3.setBounds(300, 100, 100, 30);
           add( box3);
           
           JLabel label4 = new JLabel( "학력" );
            label4.setBounds(50, 140, 100, 30);        
           add( label4);
           
           String[] arr = { "고졸" "초대졸" "대졸" "대학원졸" };
           JComboBox<String> combox = new JComboBox<String>(arr );
            combox.setBounds(100, 140, 200, 30);
           add( combox);
           
           JLabel label5 = new JLabel( "메모" );
            label5.setBounds(40, 180, 100, 30);
           add( label5);
           
           JTextArea area = new JTextArea();
           
           JScrollPane pane = new JScrollPane( area);
            pane.setBounds(100, 180, 300, 150);
           
           pane.setVerticalScrollBarPolicy(ScrollPaneConstants. VERTICAL_SCROLLBAR_AS_NEEDED );
           pane.setHorizontalScrollBarPolicy(ScrollPaneConstants. HORIZONTAL_SCROLLBAR_AS_NEEDED );
           add( pane);
           
           JButton btn1 = new JButton( "저장" );
            btn1.setBounds(100, 350, 100, 30);
           add( btn1);
           
           JButton btn2 = new JButton( "취소" );
            btn2.setBounds(250, 350, 100, 30);
           add( btn2);
           
           setVisible( true);
           setSize(600, 500);
           setLocation(200, 200);
           
           setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE );
           
     }
      public static void main(String[] args) {
            new ComponentDemo2();
           
     }

}





package awt.basic;


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

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

public class EventDemo extends JFrame {
     
      public EventDemo(){
           setLayout( null);
           
           JButton btn1 = new JButton( "버튼1" );
            btn1.setBounds(50, 30, 80, 30);
           add( btn1);
            btn1.addActionListener( e -> {System.out .println("첫번째 버튼이 클릭 되었습니다." );});
           
           JButton btn2 = new JButton( "버튼2" );
            btn2.setBounds(100, 100, 80, 30);
           add( btn2);
           
            btn2.addActionListener( new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                     System. out.println( "두번째 버튼이 클릭 되었습니다.");
                }
           });
           
           setVisible( true);
           setBounds(200, 200, 200, 100);
     }
      public static void main(String[] args) {
            new EventDemo();
     }
}





package awt.basic;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

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

public class EventDemo2 extends JFrame{

      public EventDemo2(){
           setLayout( null);
           
           JTextField field1 = new JTextField();
            field1.setBounds(20, 30, 100, 30);
           add( field1);
           
           JTextField field2 = new JTextField();
            field2.setBounds(170, 30, 100, 30);
           add( field2);
           
           JTextField field3 = new JTextField();
            field3.setBounds(20, 100, 250, 30);
           add( field3);
           
           JButton btn = new JButton( "+");
            btn.setBounds(300, 30, 50, 30);
           add( btn);
           
            btn.addActionListener( e -> {
                String txt1 = field1.getText();
                String txt2 = field2.getText();
                System. out.println( txt1 + ", " + txt2);
                
                 int num1 = Integer. parseInt( txt1);
                 int num2 = Integer. parseInt( txt2);
                
                 int sum = num1 + num2;
                
                 field3.setText( String. valueOf( sum) );
                 field1.addFocusListener( new FocusListener() {
                     
                      public void focusLost(FocusEvent e) {
                           
                     }
                     
                      public void focusGained(FocusEvent e) {
                            field1.setText( "");
                            field2.setText( "");
                            field3.setText( "");
                     }
                });
           });
           
           setVisible( true);
           setBounds(200, 200, 250, 200);
           setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE );
     }
     
      public static void main(String[] args) {
            new EventDemo2();
     }
     
     

}






반응형