본문 바로가기

   
Programming/Java

16일차!

반응형

 SWING

1. Container
     - JFrame     : titlebar, 기본 버튼이 제공, JFrame은 JFrame을 포함할 수 없다.
     - JPanel     : titlebar와 기본버튼이 제공되지 않는다.
                    JPanel은 다른 JPanel을 포함할 수 있다.
                    JFrame이나 다른 JPanel에 부속품으로 사용될 수 있다.
                    JPanel을 활용하면 복잡한 화면의 구성이 가능하다.
     - JDialog     : 알림창을 만들 때 사용한다.

2. Layout     : 컨테이너에 포함된 컴포넌트들의 배치방법을 관리한다.
     - BorderLayout : 컨테이너의 영역을 north, south, west, east, center로 나눈다. 나누어진 각각의 영역에는 컴포넌트 하나만 붙일 수 있다. center영역은 주위영역을
                          차지한다. JFrame과 JDialog의 기본 레이아웃이다.
     - FlowLayout : 컨테이너에 포함된 컴포넌트들이 순서대로 왼쪽에서 오른쪽으로 이어져서 배치된다. 컨테이너의 사이즈가 변화면 컴포넌트들의 위치도 변할 수 있다.
                    JPanel의 기본 레이아웃이다.
     - GridLayout : 컨테이너를 행과 열로 나누어서 컴포넌트를 배치한다. 나누어진 영역의 크기가 전부 동일하다. 나누어진 각 영역에는 컴포넌트 하나만 담을 수 있다.
     - CardLayout : 컨테이너에 여러 개의 컴포넌트를 카드처럼 겹쳐놓는다.
     - GridBagLayout : GridLayou과 비슷하다.
                       크기가 다른 Grid를 만들 수 있다.
                       사용법이 엄청 복잡하다.
     - AbsoluteLayout : 레이아웃을 사용하지않는 것이다. 오직 x,y 좌표로만 위치를 지정할 수 있다.
package awtLayout;

import java.awt.BorderLayout;
import java.awt.Color;

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

public class BorderLayoutDemo extends JFrame{

      public BorderLayoutDemo(){

     JButton btn1 = new JButton( "1");
     JButton btn2 = new JButton( "2");
     JButton btn3 = new JButton( "3");
     JButton btn4 = new JButton( "4");
     JButton btn5 = new JButton( "5");
     
     JPanel panel = new JPanel();
      //panel.setBackground(Color.red);
     
      panel.add( new JButton( "저장"));
      panel.add( new JButton( "취소"));
      panel.add( new JButton( "닫기"));
     
     JDialog dialog = new JDialog();
      //각각의 컴포넌트가 위치할 영역을 지정할수 있다.
      //add(btn1, BorderLayout.NORTH);
      //add(btn2, BorderLayout.SOUTH);
      //add(btn3, BorderLayout.WEST);
      //add(btn4, BorderLayout.EAST);
     add( btn5, BorderLayout. CENTER);
     add( panel, BorderLayout. SOUTH);
     
     setBounds(200, 200, 200, 200);
     setVisible( true);
     setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE );
     }
     
      public static void main(String[] args) {
            new BorderLayoutDemo();
     }
     
}




package awtLayout;

import java.awt.FlowLayout;

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

public class FloutLayoutDemo extends JFrame {
     
      public FloutLayoutDemo() {
            //레이아웃 변경하기 Jframe의 레이아웃을
            //JFRAME의 레이아웃을 fLOWlAYOUT으로 변경하기
           setLayout( new FlowLayout(FlowLayout. RIGHT));

           add( new JButton( "1"));
           add( new JButton( "2"));
           add( new JButton( "3"));
           add( new JButton( "4"));
           
           setVisible( true);
           setBounds(200, 200, 200, 100);
           setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE );
           
     }
     
      public static void main(String[] args) {
            new FloutLayoutDemo();
     }

}




package awtLayout;

import java.awt.GridLayout;

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

public class GridLayoutDemo extends JFrame{
      public GridLayoutDemo(){
            //수평 수직 간격
           setLayout( new GridLayout(2,3, 20, 5));
           
           add( new JButton( "1"));
           add( new JButton( "2"));
           add( new JButton( "3"));
           add( new JButton( "4"));
           add( new JButton( "5"));
           add( new JButton( "6"));
           
           setVisible( true);
           setBounds(200, 200, 200, 200);
           setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE );
     }
     
      public static void main(String[] args) {
            new GridLayoutDemo();
     }
}




package awtLayout;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Panel;

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

public class CardLayoutDemo extends JFrame {

      public CardLayoutDemo(){
           
           JButton btn1 = new JButton( "빨강" );
           JButton btn2 = new JButton( "노랑" );
           
           JPanel topPanel = new JPanel();
            topPanel.add( btn1);
            topPanel.add( btn2);
           
           CardLayout card = new CardLayout();
           JPanel centerFanel = new JPanel( card);
            //setLayout(card);
           
           JPanel redFanel = new JPanel();      
           JPanel yellowPanel = new JPanel();
           
            redFanel. setBackground(Color. red);
            yellowPanel. setBackground(Color. yellow);
            centerFanel.add( redFanel"red");
            centerFanel.add( yellowPanel"yellow");
           
           add( topPanel, BorderLayout. NORTH);
           add( centerFanel, BorderLayout. CENTER);
           
            btn1.addActionListener( e->{
                 card.show( centerFanel,  "red");
           });
           
            btn2.addActionListener( e->{
                 //card.show(centerFanel, "yellow");
                 card.last( centerFanel);
           });
           
           setVisible( true);
           setBounds(200, 200, 200, 200);
           setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE );
     }
     
      public static void main(String[] args) {
            new CardLayoutDemo();
     }
     
}



help -> install new software -> swing, window 관련 플러그인 다운 하면 소스가 아닌 gui를 만들수 있다.
package swing.builder;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class Sample01 {

      private JFrame frame;
      private JTextField field1;
      private JTextField field2;
      private JTextField field3;

      /**
      * Launch the application.
      */
      public static void main(String[] args) {
           EventQueue. invokeLater( new Runnable() {
                 public void run() {
                      try {
                           Sample01 window = new Sample01();
                            window. frame.setVisible( true);
                     } catch (Exception e) {
                            e.printStackTrace();
                     }
                }
           });
     }

      /**
      * Create the application.
      */
      public Sample01() {
           initialize();
     }

      /**
      * Initialize the contents of the frame.
      */
      private void initialize() {
            frame = new JFrame();
            frame.setBounds(100, 100, 450, 300);
            frame.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE );
            frame.getContentPane().setLayout( null);
           
            field1 = new JTextField();
            field1.setBounds(12, 78, 116, 21);
            frame.getContentPane().add( field1);
            field1.setColumns(10);
           
            field2 = new JTextField();
            field2.setBounds(160, 78, 116, 21);
            frame.getContentPane().add( field2);
            field2.setColumns(10);
           
            field3 = new JTextField();
            field3.setBounds(12, 109, 264, 21);
            frame.getContentPane().add( field3);
            field3.setColumns(10);
           
            JButton btnNum = new JButton ("\uACC4\uC0B0" );
            btnNum.addActionListener( new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                      int num1 = Integer.parseInt( field1.getText());
                      int num2 = Integer.parseInt( field2.getText());
                      int result = num1 + num2;
                      field3.setText(String. valueOf( result));
                }
           });
            btnNum.setBounds(288, 77, 116, 53);
            frame.getContentPane().add( btnNum);
           
           JLabel lblNewLabel = new JLabel( "\uAC04\uD3B8 \uACC4\uC2E0\uAE30");
            lblNewLabel.setBounds(12, 10, 392, 50);
            frame.getContentPane().add( lblNewLabel);
     }
}






package awt.event;

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

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

public class ActionEventDemo extends JFrame{
     
     JButton btn = new JButton( "btn");
     JTextField field1 = new JTextField(20);
     JTextField field2 = new JTextField(20);
     
      public ActionEventDemo(){
           setLayout( new FlowLayout());
           
           add( btn);
           add( field1);
           add( field2);
           
            btn.addActionListener( new ActionListener() {
                
                 @Override
                 public void actionPerformed(ActionEvent e) {
                     JOptionPane. showMessageDialog( null"클릭되었습니다." );
                }
           });
           
            field1.addActionListener( new ActionListener() {
                
                 @Override
                 public void actionPerformed(ActionEvent e) {
                      //JOptionPane.showMessageDialog(null, "enter키를 눌렀어요.");
                      field2.requestFocus();
                     
                }
           });

            field2.addActionListener( new ActionListener() {
     
            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane. showMessageDialog( null"enter키를 눌렀어요.");                
           }
           });
           
           setVisible( true);
           setBounds(200, 200, 300, 200);
           setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE );
     }
     
      public static void main(String[] args) {
            new ActionEventDemo();
     }
     
}





package awt.event;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class TextEventDemo extends JFrame{
     JLabel label = new JLabel( "0 글자");
     JTextArea area = new JTextArea();
     
      public TextEventDemo(){
           
           add( label, BorderLayout. NORTH);
           add( new JScrollPane( area), BorderLayout. CENTER);
           
            area.addKeyListener( new KeyListener() {
                
                 @Override
                 public void keyTyped(KeyEvent e) {
                      // TODO Auto-generated method stub
                     
                }
                
                 @Override
                 public void keyReleased(KeyEvent e) {
                      int count = area.getText().length();
                      label.setText( count+ "글자" );
                      if( count > 100){
                            label.setForeground(Color. CYAN);
                     } else if( count > 50){
                            label.setForeground(Color. red);
                     }
                }
                
                 @Override
                 public void keyPressed(KeyEvent e) {
                      // TODO Auto-generated method stub
                     
                }
           });
           
           setVisible( true);
           setBounds(200, 200, 200, 200);
           setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE );
     }
     
      public static void main(String[] args) {
            new TextEventDemo();
     }
}



이벤트
1. 대상 컴포넌트를 정한다.
2. 가장 적합한 이벤트를 선정한다.
     대상 컴포넌트가 button인 경우 -> ActionEvent, MouseEvent가 발생할 수 있다.
     대상 컴포넌트가 textfield인 경우 -> KeyEvent, TextEvente, ActionEvent가  발생

3. 선정된 이벤트의 발생여부를 청취하는 xxxListener를 구현한 객체를 대상컴포넌트에 등록 한다.

Event용 Adapter
- Listener들 중에서 메소드를 여러개 갖고 있는 것들의 구현부담을 줄여주기 위해서 사용되는 것
- Listener의 추상메소드를 모두 멍텅구리(인터페이스에서 정의된 기능이 여러개 있다면) 구현을 해놓은것
interfaceKeyListener{
void keyPressed(KeyEvent e);
void keyTyped(KeyEvent e);
void keyReleased(KeyEvent e);
}


abstract class KeyAdapter implements KeyListener{

void keyPressed(KeyEvent e){}

void keyTyped(KeyEvent e){}

void keyReleased(KeyEvent e){}

}



package swing.table;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane; import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class TableDemo extends JFrame{

     
      public TableDemo(){
            //mvc -> model(화면에 표시할데이타)가방들 값을 담는객체, view(진열장), control(이벤트와 관련된것)
            //3가지영역으로 나누어서 개발 한다.
           DefaultTableModel model = new DefaultTableModel();
            model.addColumn( "순번" );
            model.addColumn( "이름" );
            model.addColumn( "전화번호" );
           
            model.addRow( new String[]{ "1", "홍길동" , "010-1234-5678" });
            model.addRow( new String[]{ "2", "김유신" , "010-1111-1111" });
            model.addRow( new String[]{ "4", "강감찬" , "010-2222-2222" });
            model.addRow( new String[]{ "9", "이순신" , "010-3333-3333" });
           
           JTable table = new JTable( model);
           add( new JScrollPane( table));
           setVisible( true);
           setBounds(200, 200, 400, 400);
           setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE );
     }
     
      public static void main(String[] args) {
            new TableDemo();
     }
}


package awt.event;

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

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class MouseEventDemo extends JFrame{
     
     JTextArea area = new JTextArea();
     
      public MouseEventDemo(){
           add( new JScrollPane( area));
           
            area.addMouseListener( new MouseAdapter() {
                
                 public void mouseClicked(MouseEvent e){
                 //public void mouseExited(MouseEvent e){
                      int x = e.getX();
                      int y = e.getY();
                     
                      area.setText( "["+ x+ ","+ y+ "]");
                }
           });
           
           setVisible( true);
           setBounds(200, 200, 400, 400);
     }
     
      public static void main(String[] args) {
            new MouseEventDemo();
     }
}



package swing.table;

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

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

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

public class TableDemo2 {

      private JFrame frame;
      private JTextField name;
      private JTextField tel;
      private JTextField email;
      private JTable content;
      private DefaultTableModel model;

      /**
      * Launch the application.
      */
      public static void main(String[] args) {
           EventQueue. invokeLater( new Runnable() {
                 public void run() {
                      try {
                           TableDemo2 window = new TableDemo2();
                            window. frame.setVisible( true);
                     } catch (Exception e) {
                            e.printStackTrace();
                     }
                }
           });
     }

      /**
      * Create the application.
      */
      public TableDemo2() {
           initialize();
     }

      /**
      * Initialize the contents of the frame.
      */
      private void initialize() {
            frame = new JFrame();
            frame.setBounds(100, 100, 356, 331);
            frame.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE );
            frame.getContentPane().setLayout( null);
           
           JLabel label = new JLabel( "\uC774\uB984");
            label.setBounds(12, 55, 37, 29);
            frame.getContentPane().add( label);
           
           JLabel label_1 = new JLabel("\uC804\uD654\uBC88\uD638" );
            label_1.setBounds(12, 88, 70, 29);
            frame.getContentPane().add( label_1);
           
           JLabel label_2 = new JLabel( "\uC774\uBA54\uC77C" );
            label_2.setBounds(12, 123, 58, 29);
            frame.getContentPane().add( label_2);
           
            name = new JTextField();

            name.setBounds(82, 59, 116, 21);
            frame.getContentPane().add( name);
            name.setColumns(10);
           
            tel = new JTextField();
            tel.setBounds(82, 92, 116, 21);
            frame.getContentPane().add( tel);
            tel.setColumns(10);
           
            email = new JTextField();
            email.setBounds(82, 127, 116, 21);
            frame.getContentPane().add( email);
            email.setColumns(10);
           
            tel.addActionListener( new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                      email.requestFocus();
                }
           });
           
            name.addActionListener( new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                      tel.requestFocus();
                }
           });
           
            email.addActionListener( new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                     print();
                }
           });
           
           
           JButton btnNewButton = new JButton( "\uC785\uB825");
            btnNewButton.addActionListener( new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                     print();
                }
           });
           
            btnNewButton.setBounds(210, 55, 97, 97);
            frame.getContentPane().add( btnNewButton);
           
           JLabel label_3 = new JLabel( "\uACE0\uAC1D\uC815\uBCF4 \uC785\uB825\uB780");
            label_3.setBounds(74, 10, 97, 50);
            frame.getContentPane().add( label_3);
           
           JScrollPane scrollPane = new JScrollPane();
            scrollPane.setBounds(12, 175, 284, 108);
            frame.getContentPane().add( scrollPane);
           
            model = new DefaultTableModel();
            model.addColumn( "이름" );
            model.addColumn( "전화번호" );
            model.addColumn( "이메일" );

           
            content = new JTable( model);
            scrollPane.setViewportView( content);
           
     }
     
      private void print() {
            if( name.getText().isEmpty()){
                JOptionPane. showMessageDialog( null, "제목을 입력하세요");
                 name.requestFocus();
                 return;
           }
           
            if( tel.getText().isEmpty()){
                JOptionPane. showMessageDialog( null, "전화번호를 입력하세요");
                 tel.requestFocus();
                 return;
           }
           
            if( email.getText().isEmpty()){
                JOptionPane. showMessageDialog( null, "이메일을 입력하세요");
                 email.requestFocus();
                 return;
           }
           
            model.addRow( new String[] { name.getText(), tel.getText(), email.getText()});
            name.setText( "");
            tel.setText( "");
            email.setText( "");
           
            name.requestFocus();
     }
}






package awt.event;

import java.awt.EventQueue;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

public class TableDemo3 {

      private JFrame frame;
      private JTextField namefield;
      private JTextField phonefield;
      private JTextField delfield;
      private JTable table;

      /**
      * Launch the application.
      */
      public static void main(String [] args ) {
           EventQueue. invokeLater( new Runnable() {
                 public void run() {
                      try {
                           TableDemo3 window = new TableDemo3();
                            window. frame.setVisible( true);
                     } catch (Exception e) {
                            e.printStackTrace();
                     }
                }
           });
     }

      /**
      * Create the application.
      */
      public TableDemo3() {
           initialize();
     }

      /**
      * Initialize the contents of the frame.
      */
      private void initialize() {
            frame = new JFrame();
            frame.setBounds(100, 100, 450, 300);
            frame.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE );
            frame.getContentPane().setLayout( null);
           
           JLabel lblNewLabel = new JLabel( "\uC774\uB984");
            lblNewLabel.setBounds(12, 10, 34, 31);
            frame.getContentPane().add( lblNewLabel);
           
           JLabel lblNewLabel_1 = new JLabel("\uC804\uD654\uBC88\uD638" );
            lblNewLabel_1.setBounds(12, 46, 60, 31);
            frame.getContentPane().add( lblNewLabel_1);
           
            namefield = new JTextField();
            namefield.setBounds(68, 15, 222, 21);
            frame.getContentPane().add( namefield);
            namefield.setColumns(10);
           
            phonefield = new JTextField();
            phonefield.setColumns(10);
            phonefield.setBounds(68, 51, 222, 21);
            frame.getContentPane().add( phonefield);
           
            delfield = new JTextField();
            delfield.setColumns(10);
            delfield.setBounds(68, 87, 222, 21);
            frame.getContentPane().add( delfield);
           
           JLabel lblNewLabel_2 = new JLabel( "\uC774\uB984");
            lblNewLabel_2.setBounds(12, 82, 34, 31);
            frame.getContentPane().add( lblNewLabel_2);
           
           JScrollPane scrollPane = new JScrollPane();
            scrollPane.setBounds(12, 118, 281, 120);
            frame.getContentPane().add( scrollPane);
           
           MyTableModel model = new MyTableModel();
           
            table = new JTable( model);
            scrollPane.setViewportView( table);
           
           JButton addbtn = new JButton( "\uC800\uC7A5");
            addbtn.setBounds(302, 14, 97, 63);
            frame.getContentPane().add( addbtn);
           
           JButton delbtn = new JButton( "\uC0AD\uC81C");
            delbtn.setBounds(302, 86, 97, 23);
            frame.getContentPane().add( delbtn);
     }
     
      //api에 따르면 AbstractTableModel 을통해 메소드 재정의하면 나만의 테이블을 만들수 있다고 한다.내부클래스
      public class MyTableModel extends AbstractTableModel{//나만의 테이블을 만들고싶다.
            String[] columnNames = { "이름", "전화번호" };
           ArrayList< String[]> rowData = new ArrayList<String[]>();
           
            public MyTableModel() {
                 rowData.add( new String[]{ "이순신", "010-1111-1111" });
                 rowData.add( new String[]{ "김유신", "010-2222-2222" });
                 rowData.add( new String[]{ "강감찬", "010-3333-3333" });
                 rowData.add( new String[]{ "홍길동", "010-4444-4444" });
           }
           
            @Override
            public String getColumnName( int column) {
                 return super.getColumnName( column);
           }
           
            // jtable에게 열의 갯수를 제공하는 기능
            @Override
            public int getColumnCount() {
                 return columnNames. length;
           } @Override
           
            //jtable에게 행의 갯수를 제공하는 기능
            public int getRowCount() {
                 return rowData.size();
           } @Override
           
            //jtable에게 특정 cell의 값을 제공 하는 기능
            public Object getValueAt( int rowIndex, int columnIndex) {
                 //ArrayList에서 0,1,2번째 요소를 꺼낸다.
                 String[] row = rowData.get( rowIndex);
                 String data = row[ columnIndex];
                 return data;
           }
           
     }
}


계산기 기능을 구현하여 만들어봐라~

반응형