본문 바로가기
JAVA(프로그래밍)

java 메모장 노트패드 만들기

by 켈리113 2018. 7. 31.

java 메모장 노트패드  만들기

 

안녕하세요. 예전에 2002년도에 java로 만들었던 메모장 노드패드입니다.

지금 실행시켜보니 기본 작동은 됩니다.

 

버그가 있을수 있으나 필요하신분은 참고하세요..

 

총 3개의 java파일이 필요하며 그밖에 이미지 파일이 필요합니다.

 

소스참고하세요.

 

-----------------------------------------------------------------------------------------------------

/*
BIT - 197기 이세진
Windows homework Notepad
2002년 4월 3일 email:djusti@hanmail.net
*/

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.PrintJob;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;

public class Notepad extends JFrame implements ActionListener, TextListener, ClipboardOwner, WindowListener
{
 private JMenu fileMenu;
 private JMenu editMenu;
 private JMenu formMenu;
 private JMenu helpMenu;
 private JMenuItem newFileItem;
 private JMenuItem openItem;
 private JMenuItem saveItem;
 private JMenuItem saveAsItem;
 private JMenuItem printItem;
 private JMenuItem exitItem;
 private JMenuItem cutItem;
 private JMenuItem copyItem;
 private JMenuItem pasteItem;
 private JMenuItem findItem;
 private JMenuItem allSelectItem;
 private JMenuItem lineChangeItem;
 private JMenuItem fontItem;
 private JMenuItem infoItem;
 private JMenuBar menuBar = new JMenuBar();
 private JToolBar toolbar;
 private JButton newTool, openTool, saveTool , cutTool, pasteTool, copyTool;
 public static JTextArea jta;
 public static boolean editState = false;
 private JFileChooser chooser;
 Clipboard cb = getToolkit().getSystemClipboard();
 private Container cp;
 
// -------------------------- Notepad 생성자 (메뉴 구성) --------------------------------------------
 public Notepad()
 {

  cp=getContentPane();
  cp.setLayout(new BorderLayout());

  setJMenuBar(menuBar);
   
  jta = new JTextArea();
  jta.requestFocus();
  jta.setFont(new Font("Courier", Font.PLAIN, 16));
  JScrollPane scroller= new JScrollPane(jta);
  cp.add(scroller);
  fileMenu = new JMenu("파일(F)");
  newFileItem = new JMenuItem("새로만들기");
 
  openItem = new JMenuItem("파일열기");
  saveItem = new JMenuItem("저장");
  saveAsItem = new JMenuItem("다른이름으로저장(A)");
  printItem = new JMenuItem("프린터출력");
  exitItem = new JMenuItem("종료");
  
  fileMenu.setMnemonic('F');
  saveAsItem.setMnemonic('A');
  
  newFileItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
  saveItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
  openItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
  printItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
  exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));

  fileMenu.add(newFileItem);
  fileMenu.add(openItem);
  fileMenu.add(saveItem);
  fileMenu.add(saveAsItem);
  fileMenu.addSeparator();
  fileMenu.add(printItem);
  fileMenu.addSeparator();
  fileMenu.add(exitItem);
  
  editMenu = new JMenu("편집(E)");
  cutItem = new JMenuItem("잘라내기");
  copyItem = new JMenuItem("복사하기");
  pasteItem = new JMenuItem("붙여넣기");
  findItem = new JMenuItem("찾기");
  allSelectItem = new JMenuItem("모두선택하기");
       
  editMenu.setMnemonic('E');
  
  cutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
  copyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK));
  pasteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK));
  findItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, ActionEvent.CTRL_MASK));
  allSelectItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK));

  editMenu.add(cutItem);
  editMenu.add(copyItem);
  editMenu.add(pasteItem);
  editMenu.add(copyItem);
  editMenu.addSeparator();
  editMenu.add(findItem);
  editMenu.addSeparator();
  editMenu.add(allSelectItem);
  pasteItem.setEnabled(false);

  formMenu = new JMenu("서식(O)");
  lineChangeItem = new JMenuItem("자동줄바꿈");
  fontItem = new JMenuItem("글꼴(F)");
  
  formMenu.setMnemonic('O');
  lineChangeItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
  fontItem.setMnemonic('F');
  
  formMenu.add(lineChangeItem);
  formMenu.add(fontItem);

  helpMenu = new JMenu("도움말(H)");
  infoItem = new JMenuItem("프로그램정보(H)");

  helpMenu.setMnemonic('H');
  
  helpMenu.add(infoItem);

  menuBar.add(fileMenu);
  menuBar.add(editMenu);
  menuBar.add(formMenu);
  menuBar.add(helpMenu);

  toolbar = new JToolBar();
  newTool = new JButton(new ImageIcon("new.gif"));
  newTool.setToolTipText("새파일 입니다.");
  openTool = new JButton(new ImageIcon("open.gif"));
  openTool.setToolTipText("파일 열기 입니다");
  saveTool = new JButton(new ImageIcon("save.gif"));
  saveTool.setToolTipText("파일 저장입니다");
  cutTool = new JButton(new ImageIcon("cut.gif"));
  cutTool.setToolTipText("자르기");
  pasteTool = new JButton(new ImageIcon("paste.gif"));
  pasteTool.setToolTipText("붙여넣기");
  copyTool = new JButton(new ImageIcon("copy.gif"));
  copyTool.setToolTipText("복사하기");

  toolbar.add(newTool);
  toolbar.add(openTool);
  toolbar.add(saveTool);
  toolbar.add(cutTool);
  toolbar.add(pasteTool);
  toolbar.add(copyTool);

  cp.add("North",toolbar);
  newTool.setActionCommand("새로만들기");
  newTool.addActionListener(this);
  openTool.setActionCommand("파일열기");
  openTool.addActionListener(this);
  saveTool.setActionCommand("저장");
  saveTool.addActionListener(this);
  cutTool.setActionCommand("잘라내기");
  cutTool.addActionListener(this);
  pasteTool.setActionCommand("붙여넣기");
  pasteTool.addActionListener(this);
  copyTool.setActionCommand("복사하기");
  copyTool.addActionListener(this);
  
  

//************************ 이벤트핸들러***********************************
  newFileItem.addActionListener(this);
  openItem.addActionListener(this);
  saveItem.addActionListener(this);
  saveAsItem.addActionListener(this);
  printItem.addActionListener(this);
  exitItem.addActionListener(this);

  cutItem.addActionListener(this);
  copyItem.addActionListener(this);
  pasteItem.addActionListener(this);
  findItem.addActionListener(this);
  allSelectItem.addActionListener(this);

  lineChangeItem.addActionListener(this);
  fontItem.addActionListener(this);

  infoItem.addActionListener(this);

  addWindowListener( this );
 }//end of construct

 //*********************액션이벤트처리 **********************************************
 
 public void actionPerformed( ActionEvent e)
 {
  String com=e.getActionCommand();
   
  if ( com.equals("파일") )
  {
  
  }
  else if ( com.equals("새로만들기") )
  {
   newMake();    
  }
   
  
  else if ( com.equals("파일열기"))
  { 
   open();
  }
   
  else if ( com.equals("저장"))
  {
   saveView();
  }
     
  else if ( com.equals("다른이름으로저장(A)"))
  {
   saveView();
   
  }
  
  else if ( com.equals("프린터출력") )
  {
   print();
  }
  else if ( com.equals("종료") )
  {
   exitView();
  }
  else if ( com.equals("잘라내기") )
  {
   cut();
  }
  
  else if ( com.equals("복사하기") )
  {
   copy();
  }
  else if ( com.equals("붙여넣기") )
  {
   paste();
  }
  else if ( com.equals("찾기") )
  {
   Search smf=new Search();
  }
  else if ( com.equals("모두선택하기") )
  {
   jta.selectAll();
  }
  else if ( com.equals("자동줄바꿈") )
  {
   jta.setLineWrap(true);
  }
  else if ( com.equals("글꼴(F)") )
  {
   JDialog jd = new SetFont();
   
   
  }
  else if ( com.equals("프로그램정보(H)") )
  {
   JOptionPane.showMessageDialog(this, "sejin Notepad version 1.0\n 만든이: Lee se Jin ","정보"
   ,JOptionPane.INFORMATION_MESSAGE);
  }
  
 }
//------------------------------------- 텍스트 이번트 핸들러 ---------------------------------------------
 public void textValueChanged ( TextEvent e )
 {
    editState = true;   
 }

 public void lostOwnership(Clipboard db, Transferable contents)
 {}
// -----------------------------------------------------------------------------------------------------
 public void print() // 프린터 출력 메소드
 {
  try
  {
      String printer = jta.getText();
      String str;
      PrintJob pj = this.getToolkit().getPrintJob(this,"인쇄중",null);
      Graphics g = pj.getGraphics();
      BufferedReader intxt = new BufferedReader(new StringReader(printer));
      for(int i=100;(str = intxt.readLine())!=null;i=i+13)
      {
       g.drawString(str,80,i);
      }
      g.dispose();
      pj.end();
  }
  catch(Exception ex)
  {}
 }
 
 public void newMake() // 새로만들기 메소드
 {
  jta.setText("");
  Font f1 = new Font("Verdana", Font.PLAIN, 16);
  jta.setFont(f1);
 }
 public void open() // 파일 열기 메소드
 {
  try
  {
   chooser = new JFileChooser();
   int returnVal = chooser.showOpenDialog(this);
            if (returnVal == JFileChooser.APPROVE_OPTION)
   {
       File  infile = chooser.getSelectedFile();
    BufferedReader in = new BufferedReader ( new FileReader ( infile ) ) ;
    String line;
    jta.setText("");
    while ((line = in.readLine()) != null)
    {
     jta.append(line+"\r\n"); 
    }
    in.close();
   }
  }
  catch( FileNotFoundException e1) {}
  catch( IOException e2) {}
 }
 public void cut()  // 잘라내기 메소드
 {
  String data = jta.getSelectedText();
  StringSelection ss = new StringSelection(data);
  cb.setContents(ss, Notepad.this);
  pasteItem.setEnabled(true);
  jta.replaceRange("",jta.getSelectionStart(), jta.getSelectionEnd());
  pasteItem.setEnabled(true);
 }
 public void copy()  // 편집창 카피 메소드
 {
  String data = jta.getSelectedText();
  StringSelection ss = new StringSelection(data);
  cb.setContents(ss, Notepad.this);
  pasteItem.setEnabled(true);
 
 }
 public void paste() // 붙여넣기 메소드
 {
  Transferable tf = cb.getContents(DataFlavor.stringFlavor);
  if ( tf == null)
   return;
  String data = null;
  try
  {
   data = (String)tf.getTransferData(DataFlavor.stringFlavor);
   jta.insert(data, jta.getCaretPosition());
  }
  catch(Exception ex)
  {
   System.err.println("Data Paste Error");
  }
 }
 

 public void saveView()  // 저장시킬 화면 메소드
 {
  chooser = new JFileChooser(".");
  int returnVal = chooser.showSaveDialog(Notepad.this);
  if(returnVal == JFileChooser.APPROVE_OPTION)
  {
   try
   {
    File file = chooser.getSelectedFile();
    PrintWriter out=new PrintWriter(new FileWriter(file));
    out.write(jta.getText());
    setTitle(file.getName());
    out.close();
   }
   catch(Exception et){}
  }
 }
 
 public void exitView() // 저장 & 종료 창 메소드
 {
  if((jta.getText()).equals("") )
  {
      dispose();
      System.exit(0);
  }
  else
  {
   int result = JOptionPane.showConfirmDialog(this, "변경된 파일을 저장하시겠습니까?","sejin Notepad"
   ,JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
   if(result == 0)
   {
    saveView();
   }
   else
   {
    dispose();
    System.exit(0);
   }
  }
 }
//----------------------------------------------- 창을 닫을시 이벤트 처리 ------------------------------------- 
 public void windowActivated (WindowEvent  e)
    {}
 public void windowClosing (WindowEvent  e)
 {exitView();}
 public void windowDeactivated (WindowEvent  e)
 {}
 public void windowDeiconified (WindowEvent  e)
    {} 
 public void windowIconified (WindowEvent  e)
 {}
 public void windowOpened (WindowEvent  e)
 {}


 public void windowClosed( WindowEvent ev)
 {
 } 
 

//################################### 메인메소드 ####################################################
 public static void main(String[] args)
 {
  Notepad note = new Notepad();
  note.setTitle("sejin Notepad");
  note.setSize(400,500);
  note.setVisible(true);
 }
}
----------------------------------------------------------------------------------------------------------------------------------------------

 

자바프로그램을 실행시키면 사진처럼 간단한 메모장 프로그램이 실행됩니다.