본문 바로가기

   
Programming/Java

17일차!

반응형
package swing.optionPane;

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




import java.io.File;

import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFileChooser;
import javax.swing.JFrame; import javax.swing.JOptionPane;


public class OptionPaneDemo extends JFrame{
      public OptionPaneDemo(){
           setLayout( new FlowLayout());
           
           JButton btn1 = new JButton( "plain");
           JButton btn2 = new JButton( "info");
           JButton btn3 = new JButton( "waring");
           JButton btn4 = new JButton( "error");
           JButton btn5 = new JButton( "confirm1");
           JButton btn6 = new JButton( "confirm2");
           JButton btn7 = new JButton( "file");
           JButton btn8 = new JButton( "color");
           
           add( btn1);
           add( btn2);
           add( btn3);
           add( btn4);
           add( btn5);
           add( btn6);
           add( btn7);
           add( btn8);
           
            btn1.addActionListener( e->{
                JOptionPane. showMessageDialog( null, "plain");
           });
            btn2.addActionListener( e->{
                JOptionPane. showMessageDialog( null, "메세지입니다." , "제목" , JOptionPane. INFORMATION_MESSAGE);
           });
            btn3.addActionListener( e->{
                JOptionPane. showMessageDialog( null, "경고메세지입니다.." , "제목" , JOptionPane. WARNING_MESSAGE);
           });
            btn4.addActionListener( e->{
                JOptionPane. showMessageDialog( null, "주의메세지입니다.." , "제목" , JOptionPane. ERROR_MESSAGE);
           });
            btn5.addActionListener( e->{                
                 int result = JOptionPane. showConfirmDialog( null, "삭제하실래요?" );
                System. out.println( result);
                 if( result == JOptionPane. YES_OPTION){
                     System. out.println( "지워주지" );
                } else if( result == JOptionPane. NO_OPTION){
                     System. out.println( "안 지울게" );
                } else if( result == JOptionPane. CANCEL_OPTION ){
                     System. out.println( "취소" );
                }
           });
            btn6.addActionListener( e->{
                JOptionPane. showConfirmDialog( null, "삭제하세요", "제목" , JOptionPane.YES_NO_OPTION );
           });
            btn7.addActionListener( e->{
                 JFileChooser chooser = new JFileChooser();
                 int result = chooser.showOpenDialog( null);
                
                 //열기를 누른경우
                 if( result == JFileChooser. APPROVE_OPTION ){
                      File f = chooser.getSelectedFile();
                      System. out.println( f);
                 }
           });
            btn8.addActionListener( e->{
                Color c = JColorChooser. showDialog( null, "색을 고르세요", Color. red);
                 btn8.setBackground( c);
           });
           
           setVisible( true);
           setBounds(200, 200, 400, 400);
           setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE );
     }
     
      public static void main(String[] args) {
            new OptionPaneDemo();
     }
}

  




플러그인을 다운받아서 ui로 화면 구성을 하였다. 뉴파일 -> JDialog를 누르면 된다.

package swing.optionPane;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class MyDialog extends JDialog {

      private final JPanel contentPanel = new JPanel();
      private JTextField textField;
      private JTextField textField_1;
      private JTextField textField_2;

      /**
      * Launch the application.
      */
      public static void main(String[] args) {
            try {
                MyDialog dialog = new MyDialog();
                 dialog.setDefaultCloseOperation(JDialog. DISPOSE_ON_CLOSE );
                 dialog.setVisible( true);
           } catch (Exception e) {
                 e.printStackTrace();
           }
     }

      /**
      * Create the dialog.
      */
      public MyDialog() {
           setBounds(100, 100, 450, 300);
           getContentPane().setLayout( new BorderLayout());
            contentPanel.setBorder( new EmptyBorder(5, 5, 5, 5));
           getContentPane().add( contentPanel, BorderLayout.CENTER );
            contentPanel.setLayout( null);
           {
                JLabel lblNewLabel = new JLabel( "New label");
                 lblNewLabel.setBounds(12, 10, 57, 15);
                 contentPanel.add( lblNewLabel);
           }
           {
                JLabel lblNewLabel_1 = new JLabel( "New label");
                 lblNewLabel_1.setBounds(12, 35, 57, 15);
                 contentPanel.add( lblNewLabel_1);
           }
           {
                JLabel lblNewLabel_2 = new JLabel( "New label");
                 lblNewLabel_2.setBounds(12, 60, 57, 15);
                 contentPanel.add( lblNewLabel_2);
           }
           {
                 textField = new JTextField();
                 textField.setBounds(81, 7, 116, 21);
                 contentPanel.add( textField);
                 textField.setColumns(10);
           }
           {
                 textField_1 = new JTextField();
                 textField_1.setColumns(10);
                 textField_1.setBounds(81, 32, 116, 21);
                 contentPanel.add( textField_1);
           }
           {
                 textField_2 = new JTextField();
                 textField_2.setColumns(10);
                 textField_2.setBounds(81, 57, 116, 21);
                 contentPanel.add( textField_2);
           }
           {
                JPanel buttonPane = new JPanel();
                 buttonPane.setLayout( new FlowLayout(FlowLayout.RIGHT ));
                getContentPane().add( buttonPane, BorderLayout.SOUTH );
                {
                     JButton okButton = new JButton( "OK");
                      okButton.setActionCommand( "OK");
                      buttonPane.add( okButton);
                     getRootPane().setDefaultButton( okButton);
                }
                {
                     JButton cancelButton = new JButton("Cancel" );
                      cancelButton.setActionCommand( "Cancel");
                      buttonPane.add( cancelButton);
                }
           }
     }

}





연락처 관리 프로그램 만들기

1. Contact 정의 <--------- 연락처 정보 담을라고
2. ContactApp 화면 디자인 <------- 연락처정보 등록, 삭제, 표시 할라고

3. ContactTableModel 정의 <------- 테이블에 표시할 연락처 정보를 관리할라고
     - 컬럼명을 담고 있는 배열도만들고
     - 연락처 정보를 담을 ArrayList도 만들고
     - Jtable에서 테이블 표시 할 때 사용하는 기능도 만들고
4. ContactApp에 소스 추가 <-- jjtable이 내가 만든 ContactTableModel을 사용하게 할라고
ContactTableModel model = new ContectTableModel();
JTable table = new JTable(model);

5. ContactTableModel에 소스 추가 <--- 연락처 정보 저장하게 할라고
     - void addContact(Contact) {....}
5-1. CantactApp에 소스 추가 <--- 연락처 정보 저장되게 할라고
     - 5번에서 만든 코드를 사용
6. ContactTableModel에 소스 추가 <-- 이름으로 연락처 정보 삭제되게 할려고
     - void removeContact(String) {....}
6-1. ContactApp에 소스 추가 <--- 이름으로 연락처 정보 삭제되게 할라고
     - 5번에서 만든 코드를 사용
7. ContactDialog  화면 디자인 <-- 연락처정보 보여주고, 수정하게 할라고
8. ContactTableModel에 소스 추가 <--- 행번호에 해당하는 연락처 정보 제공할라고
     - Contact getContactByRowIndex(int)
8-1. ContactApp에 소스 추가 <--- 테이블의 행을 클릭하면 7번에서 만든 다얼로그 표시
     - 8번에 만든 코드를 사용해서 연락처정보 조회해서 7번 다이얼로그의 화면에 표시
9. ContactTableModel에 소스 추가 <-- 연락처 정보 수정할라고
     - void updateContact(Contact)
9-1. ContactDialog에 소스 추가 <-- 수정 버튼 누르면 연락처 정보 수정되게 할라고

     - 9번에서 만든 코드를 사용해서 연락처 정보 수정
package swing.table;
//04.28 화2
public class Contact {

      private String name;
      private String phone;
      private String email;
     
      public Contact() {}

      public Contact(String name, String phone, String email) {
            this. name = name;
            this. phone = phone;
            this. email = email;
     }

      public String getName() {
            return name ;
     }

      public void setName(String name) {
            this. name = name;
     }

      public String getPhone() {
            return phone;
     }

      public void setPhone(String phone) {
            this. phone = phone;
     }

      public String getEmail() {
            return email;
     }

      public void setEmail(String email) {
            this. email = email;
     }

      @Override
      public String toString() {
            return "Contact [name=" + name + ", phone=" + phone + ", email="
                     + email + "]";
     }
     
     
}


package swing.table;

import java.util.ArrayList;

import javax.swing.table.AbstractTableModel;

//04.28 화3 나만의 테이블 모델 만들기
public class ContactTableModel extends AbstractTableModel {

      // 컬럼의 이름을 제공하는 배열
      private String[] names = { "이름" , "전화번호" , "이메일" };
     
      // 화면에 뿌릴 연락처 정보를 담을 리스트
      private ArrayList<Contact> contacts = new ArrayList<Contact>();
     
      // column명을 제공하는 기능( ctrl + space)
      public String getColumnName( int column) {
            return names[ column];
     }
     
      // 전체 행갯수를 제공하는 기능
      public int getRowCount() {
            // 리스트안에 들어있는 연락처 정보의 갯수
            return contacts.size();
     }
     
      // 전체 column갯수를 제공하는 기능
      public int getColumnCount() {
            return names. length;
     }

      // 각각의 cell에 표시될 값을 제공하는 기능(반복해서 값을 꺼내온다)
      public Object getValueAt( int rowIndex, int columnIndex) {
           Contact c = contacts.get( rowIndex);
            if ( columnIndex == 0) {
                 return c.getName();
           
           } else if( columnIndex == 1) {
                 return c.getPhone();
                
           } else if( columnIndex == 2) {
                 return c.getEmail();
           
           } else {
                 return null;
           }
     }
     
      // 연락처를 추가하는 기능
      public void addContact(Contact c) {
            contacts.add( c);
            this.fireTableDataChanged();     // 테이블의 데이터가
                                                      // 변경됐다는 사실을 알려주는것(외울필욘 없음)
     }
     
      // 전달받은 이름과 일치하는 연락처를 삭제하는 기능
      public void removeContactByName(String name) {
            for ( int i = 0; i < contacts.size(); i++) {
                Contact c = contacts.get( i);
                 if ( c.getName().equals( name)) {
                      contacts.remove( i);
                      break;
                }
           }
            this.fireTableDataChanged();
     }
      // 행번호에 해당하는 연락처 정보를 제공한다. index째의 연락처 정보가 반환된다
      public Contact getContactByRowIndex( int index) {
           Contact c = contacts.get( index);
            return c;
     }
     
      // 연락처 정보를 변경하는 기능
      public void updateContact(Contact c){
            // 수정된 연락처 정보
           String name = c.getName();
           String phone = c.getPhone();
           String email = c.getEmail();
           
            for(Contact contact : contacts){
                 if( name.equals( contact.getName())){
                      contact.setPhone( phone);
                      contact.setEmail( email);
                      break;
                }
           }
            this.fireTableDataChanged();
     }

     
     
}


package swing.table;

import java.awt.EventQueue;

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

import java.awt.Font;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ImageIcon;


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

import javax.swing.JPanel;
import javax.swing.border.BevelBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
//04.28 화1
public class ContactApp {

      private JFrame frame;
      private JTextField emailField;
      private JTextField phoneField;
      private JTextField nameField;
      private JTable table;
     
      private ContactTableModel model;
      private JTextField delField;
      private ContactDialog dialog;
     

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

      /**
      * Create the application.
      */
      public ContactApp() {
           initialize();
     }
     
      private void addInfo() {
           
            // 입력필드의 값 가져오기 - getText()
           String name = nameField.getText();
           String phone = phoneField.getText();
           String email = emailField.getText();
           
            //생성자
           Contact c = new Contact( name, phone, email);
           
            // JTable에서 사용중인 TableModel객체에 새로운 연락처 정보 추가
            model.addContact( c);
           
            nameField.setText( "");
            phoneField.setText( "");
            emailField.setText( "");
            nameField.requestFocus();
     }

      /**
      * Initialize the contents of the frame.
      */
      private void initialize() {
            frame = new JFrame();
            frame.setBounds(100, 100, 672, 565);
            frame.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE );
            frame.getContentPane().setLayout( null);
           
           JScrollPane scrollPane = new JScrollPane();
            scrollPane.setBounds(10, 277, 634, 240);
            frame.getContentPane().add( scrollPane);
           
            model = new ContactTableModel();
           
            table = new JTable( model);
            scrollPane.setViewportView( table);
           
           JPanel panel1 = new JPanel();
            panel1.setBounds(10, 21, 634, 164);
            frame.getContentPane().add( panel1);
            panel1.setLayout( null);
            panel1.setBorder( new TitledBorder( new EtchedBorder(), "연락처 관리" ));
           
           JLabel label = new JLabel("\uC804\uD654\uBC88\uD638" );
            label.setBounds(29, 69, 52, 16);
            panel1.add( label);
            label.setFont( new Font( "굴림" , Font.PLAIN , 13));
           
           JLabel label_1 = new JLabel( "\uC774\uBA54\uC77C" );
            label_1.setBounds(32, 107, 49, 16);
            panel1.add( label_1);
            label_1.setFont( new Font( "굴림" , Font.PLAIN , 13));
           
           JLabel lblNewLabel_1 = new JLabel( "\uC774\uB984");
            lblNewLabel_1.setBounds(29, 28, 26, 16);
            panel1.add( lblNewLabel_1);
            lblNewLabel_1.setFont( new Font( "굴림" , Font.PLAIN , 13));
           
           JButton btn1 = new JButton( "\uB4F1\uB85D");
            btn1.setBounds(538, 28, 84, 98);
            panel1.add( btn1);
           
            nameField = new JTextField();
            nameField.setBounds(110, 28, 416, 21);
            panel1.add( nameField);
//         emailField.addActionListener(new ActionListener() {
//              public void actionPerformed(ActionEvent e) {
//                   addInfo();
//                   
//              }
//         });
            nameField.setColumns(10);
           
            phoneField = new JTextField();
            phoneField.setBounds(110, 67, 416, 21);
            panel1.add( phoneField);
            phoneField.setColumns(10);
           
            emailField = new JTextField();
            emailField.setBounds(110, 105, 416, 21);
            panel1.add( emailField);
            emailField.setColumns(10);
           
           JPanel panel2 = new JPanel();
            panel2.setBounds(10, 195, 634, 67);
            frame.getContentPane().add( panel2);
            panel2.setLayout( null);
            panel2.setBorder( new TitledBorder( new EtchedBorder(), "연락처 삭제" ));
           
           JLabel label_3 = new JLabel( "\uC774\uB984");
            label_3.setBounds(32, 23, 26, 16);
            panel2.add( label_3);
            label_3.setFont( new Font( "굴림" , Font.PLAIN , 13));
           
            delField = new JTextField();
            delField.setBounds(110, 21, 416, 21);
            panel2.add( delField);
            delField.setColumns(10);
           
           JButton btn2 = new JButton( "\uC0AD\uC81C");
            btn2.setBounds(540, 20, 82, 23);
            panel2.add( btn2);
            btn2.addActionListener( new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                     String name = delField.getText();
                      model.removeContactByName( name);
                      delField.setText( "");
                }
           });
            btn1.addActionListener( new ActionListener() {
                 public void actionPerformed(ActionEvent e ) {
                     addInfo();
                 }

           });
           
            dialog = new ContactDialog( model);
            //  JTable의 행을 더블클릭했을 때
            table.addMouseListener( new MouseAdapter() {
                
                 public void mouseClicked(MouseEvent e) {
                      // 마우스의 클릭횟수(더블클릭했을때 다이얼로그 창 띄우기)
                      if ( e.getClickCount() == 2) {
                            dialog.setVisible( true);
                            // JTable에서 지금 선택한 행의 번호 가져오기
                            int rowIndex = table.getSelectedRow();
                            // tablemodel 에서 선택한 행의 연락처정보 가져오기
                           Contact c = model.getContactByRowIndex( rowIndex);
                            // 다이얼로그창에 값 표시하기
                           dialog. nameField.setText( c.getName());
                           dialog. emailField.setText( c.getEmail());
                           dialog. phoneField.setText( c.getPhone());
                     }
                }
           });
     }
}


package swing.table;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
//04.28 화7
public class ContactDialog extends JDialog {

      private final JPanel contentPanel = new JPanel();
     JTextField nameField;
     JTextField phoneField;
     JTextField emailField;
     
     ContactTableModel model;

      public ContactDialog(ContactTableModel model) {
            this. model = model;
           setBounds(100, 100, 555, 265);
           getContentPane().setLayout( new BorderLayout());
            contentPanel.setBorder( new EmptyBorder(5, 5, 5, 5));
           getContentPane().add( contentPanel, BorderLayout.CENTER );
            contentPanel.setLayout( null);
           {
                JLabel lblNewLabel = new JLabel( "\uC774\uB984");
                 lblNewLabel.setBounds(29, 30, 79, 27);
                 contentPanel.add( lblNewLabel);
           }
           {
                JLabel label = new JLabel("\uC804\uD654\uBC88\uD638" );
                 label.setBounds(29, 84, 79, 27);
                 contentPanel.add( label);
           }
           {
                JLabel label = new JLabel( "\uC774\uBA54\uC77C" );
                 label.setBounds(29, 137, 79, 27);
                 contentPanel.add( label);
           }
           {
                 nameField = new JTextField();
                 nameField.setEditable( false);
                 nameField.setBounds(120, 30, 335, 27);
                 contentPanel.add( nameField);
                 nameField.setColumns(10);
           }
           {
                 phoneField = new JTextField();
                 phoneField.setColumns(10);
                 phoneField.setBounds(120, 84, 335, 27);
                 contentPanel.add( phoneField);
           }
           {
                 emailField = new JTextField();
                 emailField.setColumns(10);
                 emailField.setBounds(120, 137, 335, 27);
                 contentPanel.add( emailField);
           }
           {
                JPanel buttonPane = new JPanel();
                 buttonPane.setLayout( new FlowLayout(FlowLayout.RIGHT ));
                getContentPane().add( buttonPane, BorderLayout.SOUTH );
                {
                     JButton okButton = new JButton( "수정" );
                      okButton.setActionCommand( "OK");
                      buttonPane.add( okButton);
                     getRootPane().setDefaultButton( okButton);
                      okButton.addActionListener( e->{
                           String name = nameField.getText();
                           String phone = phoneField.getText();
                           String email = emailField.getText();
                            //수정된 연락처 정보
                           Contact c = new Contact( name, phone, email);
                           
                            model.updateContact( c);
                           
                           ContactDialog. this.setVisible( false);
                     });
                }
                {
                     JButton cancelButton = new JButton( "취소" );
                      cancelButton.setActionCommand( "Cancel");
                      buttonPane.add( cancelButton);
                      cancelButton.addActionListener( e->{
                           ContactDialog. this.setVisible( false);                           
                     });

                }
           }
     }

}






반응형