190429_Day16 복습, Swing

이벤트 처리 복습


그리고 오늘은 스윙을 배워본다!

스윙도 자바 GUI, 더 기능이 많고 자바 언어로만 쓰여있어서 다른 기기에서도 바뀌지 않는다!

스윙(Swing)

  • AWT : 내부적으로 C언어로 구성

    • 운영체제에서 지원하는 컴포넌트를 얻어 옴.
    • (동일한 class가 운영체제 OS에 따라 다른 모양으로 보일 수 있음)
    • java.awt.*;
  • Swing : 순수자바언어로 구성.( 운영체제에 상관없이 동일한 컴포넌트 지원 )

    • javax.swing.*;

    • 특징 : awt와 비교하여 첫글자가 ‘J’로 시작!

    • AWT Swing
      Button JButton
      Frame JFrame
      Checkbox JCheckBox(o)JCheckbox(x)
  • package j0429;
    
    import java.awt.FlowLayout;
    import java.awt.event.WindowAdapter;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    
    public class SwingTest extends JFrame
    {
    JButton bt,bt1;
    
    public SwingTest()
    {
        setTitle("Swing테스트");
    
        bt = new JButton("<html><font size = 20 color = red face = 궁서체>나버튼</font></html>"); //html 태그 적용 가능
        bt1 = new JButton("나버튼"); 
    
        setLayout(new FlowLayout());
        add(bt);
        add(bt1);
    
        setSize(300,500);
        setVisible(true);
        //만약 프레임 우측 상단의 X버튼 클릭시 프로그램 종료만 할 것이라면 아래의 코드 사용!
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //X버튼에 기능 부여할 것이면 addWindowListener() 사용!
    }
    
    
    public static void main(String[] args)
    {
        new SwingTest();
    }
    }
    
  • 1556503089180

  • package j0429;
    
    import java.awt.GridLayout;
    
    import javax.swing.ImageIcon;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.border.BevelBorder;
    import javax.swing.border.TitledBorder;
    
    public class JCheckBoxTest extends JFrame
    {
    JCheckBox cb1, cb2, cb3;
    JPanel panel;
    
    public JCheckBoxTest()
    {
        ImageIcon icon1 = new ImageIcon("src/image/left.gif"); // 경로는 대소문자 구분 안함
        ImageIcon icon2 = new ImageIcon("src/image/leftrollover.gif");
        ImageIcon icon3 = new ImageIcon("src/image/leftdown.gif"); 
        ImageIcon icon4 = new ImageIcon("src/image/right.gif");
        ImageIcon icon5 = new ImageIcon("src/image/rightrollover.gif");
        ImageIcon icon6 = new ImageIcon("src/image/rightdown.gif"); 
        cb1 = new JCheckBox("첫번째 체크박스",icon1);
        cb1.setRolloverIcon(icon2);
        cb1.setSelectedIcon(icon3);
    
        cb2 = new JCheckBox("두번째 체크박스",icon4);
        cb2.setRolloverIcon(icon5);
        cb2.setSelectedIcon(icon6);
    
        cb3 = new JCheckBox("세번째 체크박스");
    
        panel = new JPanel();
            panel.setLayout(new GridLayout( 3, 1 ));
            panel.add(cb1);
            panel.add(cb2);
            panel.add(cb3);
    
    //            panel.setBorder(new TitledBorder("패널타이틀"));
    //            panel.setBorder(new BevelBorder(BevelBorder.RAISED)); //양각
    //            panel.setBorder(new BevelBorder(BevelBorder.LOWERED)); //음각
            panel.setBorder(new TitledBorder(new BevelBorder(BevelBorder.LOWERED), "패널타이틀"));
    
        setTitle("체크박스테스트");
        add(panel);
        //JFrame - BorderLayout기본레이아웃 "Center"기본위치
    
            setSize(300,200);
            setVisible(true);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    
    public static void main(String[] args)
    {
        new JCheckBoxTest();
    }
    }
    
  • 1556505751843

  • package j0429;
    
    import java.awt.GridLayout;
    
    import javax.swing.ButtonGroup;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.border.BevelBorder;
    import javax.swing.border.TitledBorder;
    
    public class JRadioButtonTest extends JFrame
    {
    JRadioButton radio1, radio2, radio3;
    JPanel panel;
    
    public JRadioButtonTest()
    {
        ImageIcon icon1 = new ImageIcon("src/image/left.gif");
        ImageIcon icon2 = new ImageIcon("src/image/leftRollover.gif");
        ImageIcon icon3 = new ImageIcon("src/image/leftdown.gif");
    
        radio1 = new JRadioButton("라디오1", icon1);
        radio2 = new JRadioButton("라디오2", icon2);
        radio3 = new JRadioButton("라디오3", icon3);
    
        ButtonGroup group = new ButtonGroup();
        group.add(radio1);
        group.add(radio2);
        group.add(radio3);
    
        panel = new JPanel();
        panel.setLayout(new GridLayout( 3, 1 ) );
            panel.add(radio1);
            panel.add(radio2);
            panel.add(radio3);  
        panel.setBorder(new TitledBorder(new BevelBorder(BevelBorder.RAISED), "라디오그룹" ) );
    
        setTitle("라디오 버튼 테스트");
        add(panel);
    
        setSize(200,300);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
    
    
    public static void main(String[] args)
    {
        new JRadioButtonTest();
    }
    }
    
    
  • 1556506893675

  • //JList 안쓴것 
    
    package j0429;
    
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GridLayout;
    import java.awt.List;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    
    public class ItemMoveTest extends JFrame
    {
    
       JButton bt_right,bt_right_all, bt_left, bt_left_all;
    
    JPanel leftp, centerp, rightp;
    
    //    JList<String> left_list = new JList<String>();
    //    JList<String> right_list = new JList<String>();
    List left_list, right_list;
    
    JTextField left_tf, right_tf;
    
    public ItemMoveTest()
    {
    
    //        ImageIcon icon1 = new ImageIcon();
    //        ImageIcon icon2 = new ImageIcon();
    //        ImageIcon icon3 = new ImageIcon();
    //        ImageIcon icon4 = new ImageIcon();
    
          left_list = new List();
          right_list = new List();
    
          left_tf = new JTextField();      
          right_tf = new JTextField();
    
          bt_right = new JButton("▷");
          bt_right_all = new JButton("▶");
          bt_left = new JButton("◁");
          bt_left_all = new JButton("◀");
    
          leftp = new JPanel();
            leftp.setLayout(new BorderLayout());
            leftp.add("Center",left_list);
            leftp.add("South",left_tf);
    
          rightp = new JPanel();
            rightp.setLayout(new BorderLayout());
            rightp.add("Center",right_list);
            rightp.add("South",right_tf);
    
          centerp = new JPanel();
            centerp.setBackground(Color.YELLOW);
            centerp.setLayout(new GridLayout(6,3));
            centerp.add(new JLabel());
            centerp.add(bt_left);
            centerp.add(bt_left_all);
            centerp.add(bt_right);
            centerp.add(bt_right_all);
    
            setTitle("Item움직이기");
            setLayout(new GridLayout(1,3));
            add(leftp);
            add(centerp);
            add(rightp);
    
        setSize(300,400);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    
    }
    
    public static void main(String[] args)
    {
        new ItemMoveTest();
    }
    
    }
    
  • //=== 그냥 리스트
    package j0429;
    
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GridLayout;
    import java.awt.List;
    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.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    
    public class ItemMoveTest extends JFrame implements ActionListener
    {
    // JList<String> left_list, right_list;
    List left_list, right_list;
    
    JTextField left_tf, right_tf;
    JButton bt_right, bt_right_all, bt_left, bt_left_all;
    
    JPanel leftp, centerp, rightp;
    
    public ItemMoveTest()
    {
    //      left_list = new JList<String>();
    //      right_list = new JList<String>();
        left_list = new List();
        right_list = new List();
    
        left_tf = new JTextField();
        right_tf = new JTextField();
    
        // 'ㅁ'한글입력 - 한자키 누름
        // 확장된 부호찾기 - ▷ ▶ ◁ ◀
        bt_right = new JButton("▷");
        bt_right_all = new JButton("▶");
        bt_left = new JButton("◁");
        bt_left_all = new JButton("◀");
    
        leftp = new JPanel();
        leftp.setLayout(new BorderLayout());
        leftp.add("Center", left_list);
        leftp.add("South", left_tf);
    
        rightp = new JPanel();
        rightp.setLayout(new BorderLayout());
        rightp.add("Center", right_list);
        rightp.add("South", right_tf);
    
        centerp = new JPanel();
        centerp.setBackground(Color.YELLOW);
        centerp.setLayout(new GridLayout(6, 3, 10, 10));
        centerp.add(new JLabel());
        centerp.add(new JLabel());
        centerp.add(new JLabel());
        centerp.add(new JLabel());
        centerp.add(bt_left);
        centerp.add(new JLabel());
        centerp.add(new JLabel());
        centerp.add(bt_left_all);
        centerp.add(new JLabel());
        centerp.add(new JLabel());
        centerp.add(bt_right);
        centerp.add(new JLabel());
        centerp.add(new JLabel());
        centerp.add(bt_right_all);
        centerp.add(new JLabel());
        // centerp.add(new JLabel());centerp.add(new JLabel());centerp.add(new
        // JLabel());
    
        setTitle("Item움직이기");
        setLayout(new GridLayout(1, 3));
        add(leftp);
        add(centerp);
        add(rightp);
    
        setSize(600, 300);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    
        eventUp();
    }// 생성자
    private void eventUp() //이벤트 소스 등록
    {
        //버튼
        bt_left.addActionListener(this); // bt_left에 액션을 감지하다가 핸들러 호출.
        bt_left_all.addActionListener(this); // bt_left에 액션을 감지하다가 핸들러 호출.
        bt_right.addActionListener(this); // bt_left에 액션을 감지하다가 핸들러 호출.
        bt_right_all.addActionListener(this); // bt_left에 액션을 감지하다가 핸들러 호출.
    
        //텍스트필드
        left_tf.addActionListener(this);
        right_tf.addActionListener(this);
    
    }
    @Override
    public void actionPerformed(ActionEvent e) // 핸들러(기능추가)
    {
        //액션 : 버튼누르기 , 텍스트필드에 enter입력
    //        System.out.println("테스트");
        Object ob = e.getSource();  //이벤트 발생시킨 이벤트소스의 주소 얻기
    
        if(ob == left_tf) //주소 비교
        {
            //1. 데이터 얻기
            String str = left_tf.getText();
            if(str.trim().length()<1) //str이 공백과 같다면
            {
    
                return;
            }
            //2. 데이터 복사
            left_list.add(str);
            //3. 원본데이터 삭제
            left_tf.setText("");
        }
        else if(ob == right_tf) //주소 비교
        {
            //1. 데이터 얻기
            String str = right_tf.getText();
            if(str.trim().length()<1)
            {
                return;
            }
            //2. 데이터 복사
            right_list.add(str);
            //3. 원본데이터 삭제
            right_tf.setText("");
        }
        else if(ob == bt_left) //주소 비교 , 첫번째 버튼(bt_left) 클릭시
        {
            String str = right_list.getSelectedItem();
    
            if(str == null)
            {
    //                JOptionPane.showMessageDialog(Component parentComponent, Objectmessage);
    //                parentComponent : 대화상자가 올려지는 바탕(기준) 콤포넌트
                //messate : 전달메세지
                JOptionPane.showMessageDialog(right_list, "이동할 아이템 선택!");
                return; // 현재 메소드 종료
            }
            left_list.add(str);
            right_list.remove(str);
        }
    
        else if(ob == bt_left_all) //주소 비교
        {
            for(int i = 0; i<right_list.getItemCount(); i++)
            {
                System.out.println(" getItem ( " + i + " )  = "  +right_list.getItem(i));
                left_list.add(right_list.getItem(i));
            }
            right_list.removeAll(); // 복사가 전체 끝난 후 원본 리스트 전체 데이터 지우기
        }
        else if(ob == bt_right) //주소 비교
        {
            String str = left_list.getSelectedItem();
            if(str == null)
            {
    //                JOptionPane.showMessageDialog(Component parentComponent, Objectmessage);
    //                parentComponent : 대화상자가 올려지는 바탕(기준) 콤포넌트
                //messate : 전달메세지
                JOptionPane.showMessageDialog(right_list, "이동할 아이템 선택!");
                return; // 현재 메소드 종료
            }
            right_list.add(str);
            left_list.remove(str);
        }
        else //주소 비교
        {
            for(int i = 0; i<left_list.getItemCount(); i++)
            {
                System.out.println(" getItem ( " + i + " )  = "  +left_list.getItem(i));
                right_list.add(left_list.getItem(i));
            }
            left_list.removeAll(); // 복사가 전체 끝난 후 원본 리스트 전체 데이터 지우기
        }
    
    }//actionPerformed
    
    public static void main(String[] args)
    {
        new ItemMoveTest();
    }
    
    }
    
  • //JList 사용
    
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GridLayout;
    import java.awt.List;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Vector;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    
    public class ItemMoveTest2 extends JFrame implements ActionListener{
     JList<String> left_list, right_list;
    
     JTextField left_tf, right_tf;
     JButton bt_right,bt_right_all, bt_left, bt_left_all;
    
     JPanel leftp, centerp, rightp;
    
     JScrollPane left_scrol, right_scrol;
     //스크롤바가 지원되는 패널 --->  보통 JList, JTextArea, JTable과 함께 사용
    
     //JList는 데이터를 String[] 또는 Vector로 따로 분리해서 저장!!
     Vector<String> leftV;//좌측 JList가 담을 데이터를 표현   
     Vector<String> rightV;//우측 JList가 담을 데이터를 표현   
    
     public ItemMoveTest2() {
      leftV = new Vector<String>();
      rightV = new Vector<String>();
    
        left_list = new JList<String>();
        //left_scrol = new JScrollPane(스크롤바를 필요로 하는 컴포넌트);
        left_scrol = new JScrollPane(left_list);
        /*
    
        <JList에 데이터 추가방법>
        left_list.setListData(String[] listData);
        left_list.setListData(Vector listData);
    
        */
    
    //      String[] listData = {"홍길동","길라임","김주원",
    //              "홍길동","길라임","김주원",
    //              "홍길동","길라임","김주원",
    //              "홍길동","길라임","김주원",
    //              "홍길동","길라임","김주원",
    //              "홍길동","길라임","김주원",
    //              "홍길동","길라임","김주원",
    //              "홍길동","길라임","김주원"              
    //                           };
    //      left_list.setListData(listData);
    
    
    
    
        right_list = new JList<String>();
        right_scrol = new JScrollPane(right_list);
    
    //      Vector<String> v = new Vector<>();
    //       v.add("김유신");
    //       v.add("이순신");
    //       v.add("강감찬");
    //      right_list.setListData(v);  
    
    
        left_tf = new JTextField();     
        right_tf = new JTextField();
    
        //'ㅁ'한글입력 - 한자키 누름
        //확장된 부호찾기 - ▷ ▶ ◁ ◀
        bt_right = new JButton("▷");
        bt_right_all = new JButton("▶");
        bt_left = new JButton("◁");
        bt_left_all = new JButton("◀");
    
        leftp = new JPanel();
          leftp.setLayout(new BorderLayout());
          //leftp.add("Center",left_list);//JList붙이기
          leftp.add("Center",left_scrol);//스크롤바가 있는 JList붙이기
          leftp.add("South",left_tf);
    
        rightp = new JPanel();
          rightp.setLayout(new BorderLayout());
          //rightp.add("Center",right_list);
          rightp.add("Center",right_scrol);
          rightp.add("South",right_tf);
    
        centerp = new JPanel();
          centerp.setBackground(Color.YELLOW);
          centerp.setLayout(new GridLayout(6,3,10,10));
          centerp.add(new JLabel());centerp.add(new JLabel());centerp.add(new JLabel());
          centerp.add(new JLabel());centerp.add(bt_right);     centerp.add(new JLabel());
          centerp.add(new JLabel());centerp.add(bt_right_all); centerp.add(new JLabel());
          centerp.add(new JLabel());centerp.add(bt_left);    centerp.add(new JLabel());
          centerp.add(new JLabel());centerp.add(bt_left_all);centerp.add(new JLabel());
          //centerp.add(new JLabel());centerp.add(new JLabel());centerp.add(new JLabel());
    
    
        setTitle("Item움직이기");
        setLayout(new GridLayout(1,3));
        add(leftp);
        add(centerp);
        add(rightp);
    
        setSize(600, 300);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    
        eventUp();
     }//생성자
    
     private void eventUp() {//이벤트 소스 등록
      //버튼
      bt_left.addActionListener(this);//bt_left에 액션을 감지하다가 핸들러 호출.
      bt_left_all.addActionListener(this);
      bt_right.addActionListener(this);
      bt_right_all.addActionListener(this);
    
      //텍스트필드
      left_tf.addActionListener(this);
      right_tf.addActionListener(this);
     }
    
    @Override
     public void actionPerformed(ActionEvent e) {//핸들러(기능추가)
        //액션: 버튼누르기, 텍스트필드에 enter입력
      //System.out.println("action");   
      Object ob = e.getSource();//이벤트 발생시킨 이벤트소스의 주소 얻기.
        if(ob==left_tf) {//좌측 텍스트필드에 엔터입력시
         //1.데이터 얻기
          String str = left_tf.getText();
    
          if(str.trim().equals("")) {//str이 공백과 같다면!!
              left_tf.setText("");
              return;
          }       
    
         //2.데이터 복사
          leftV.add(str);//벡터에 담고
          left_list.setListData(leftV);//벡터 데이터를 JList에 반영
    
         //3.원본데이터 삭제
          left_tf.setText("");
      }else if(ob==right_tf) {//우측 텍스트필드에 엔터입력시
         //1.데이터 얻기
          String str = right_tf.getText();
    
          if(str.trim().length()<1) {//str이 공백과 같다면!!
              right_tf.setText("");
              return;
          }
    
         //2.데이터 복사   
    
         //3.원본데이터 삭제
          right_tf.setText("");
      }else if(ob==bt_right) {//첫번째버튼(bt_left) 클릭시
         //1.(선택된아이템) 데이터 얻기
          String str = left_list.getSelectedValue();
                      //선택된 아이템이 없을시 null 리턴!!
    
          if(str==null) {
            //JOptionPane.showMessageDialog(Component parentComponent,Object message);
            //parentComponent: 대화상자가 올려지는 바탕(기준) 컴포넌트
            //message: 전달 메시지
              //JOptionPane.showMessageDialog(left_list,"이동할 아이템 선택!!");  
              JOptionPane.showMessageDialog(this,"이동할 아이템 선택!!");  
             return;//현재 메소드 종료!!
          }
    
         //2.데이터 복사 (우측 Vector에 전달)
            rightV.add(str);//오른쪽 벡터에 데이터 추가
            right_list.setListData(rightV);//벡터값을 오른쪽리스트에 전달(반영)
    
         //3.원본데이터 삭제
            leftV.remove(str);//왼쪽 벡터에 데이터 삭제
            left_list.setListData(leftV);//벡터값을 왼쪽리스트에 전달(반영)
    
    
      }else if(ob==bt_right_all) {//두번째버튼(bt_left_all) 클릭시
          //벡터 사이에서 데이터 전달
            //왼쪽벡터 데이터   ---------->  오른쪽벡터 데이터
          for(int i=0; i<leftV.size(); i++) {
             rightV.add(leftV.get(i));
          }
    
          //왼쪽벡터 데이터 전체 삭제
          leftV.clear();
          //--------------------------------------------
    
    
          //각 리스트는 변경된 벡터내용을 refresh!!
          left_list.setListData(leftV);
          right_list.setListData(rightV);
    
    
    
      }else if(ob==bt_left) {//세번째버튼(bt_right) 클릭시
        //1.(선택된아이템) 데이터 얻기
          String str = "";
    
          if(str==null) {//선택된 아이템이 없다면
              JOptionPane.showMessageDialog(this,"이동할 아이템 선택!!");  
              return;//현재 메소드 종료!!
          }
    
         //2.데이터 복사   
    
         //3.원본데이터 삭제
    
    
      }else {//if(ob==bt_left_all) {//네번째버튼(bt_right_all) 클릭시
    //          for(int i=0; i<right_list.getItemCount(); i++) {
    //              left_list.add(right_list.getItem(i));//1,2
    //          }       
          right_list.removeAll();//3.복사가 전체 끝난 후  원본 리스트 전체 데이터를 지우기.
    
      }
    
     }//actionPerformed
    
     public static void main(String[] args) {
      new ItemMoveTest2();
     }
    }
  • awt는 자동 스크롤바 지원, 스윙에서는 JScrollPane 사용해 주어야 한다.

궁금상자
    - 스윙 어디서 쓰이는걸까?
    - setBounds
    - GridLayout, BorderLayout

+ Recent posts