1. 程式人生 > >Java仿windows記事本較完整版

Java仿windows記事本較完整版

package org.mfy.notepad;

import java.awt.*;

import javax.swing.* ;

import java.awt.event.* ;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.swing.event.*;
import javax.swing.text.BadLocationException;
import javax.swing.undo.*;
public class MyNotepad extends JFrame{
	
	//檔案的標題
	private String title = "無標題" ;
	//選單欄
	private JPanel mp = new JPanel() ;
	private JMenuBar mb = new JMenuBar() ;
	private JMenu
		file = new JMenu("檔案(F)"),
		edit = new JMenu("編輯(E)"),
		format = new JMenu("格式(V)"),
		view = new JMenu("檢視(O)"),
		help = new JMenu("幫助(H)");
	//檔案
	private JMenuItem 
		newFile = new JMenuItem("新建(N)") ,
		open = new JMenuItem("開啟(O)") ,
		save = new JMenuItem("儲存(S)") ,
		exit = new JMenuItem("退出(X)") ;
	//編輯
	private JMenuItem 
		undo = new JMenuItem("撤銷(U)") ,
		cut = new JMenuItem("剪下(T)") ,
		copy = new JMenuItem("複製(C)") ,
		paste = new JMenuItem("貼上(P)") ,
		delete = new JMenuItem("刪除(L)") ,
		find = new JMenuItem("查詢(F)") ,
		replace = new JMenuItem("替換(R)") ,
		goTo = new JMenuItem("轉到(G)") ,
		selectAll = new JMenuItem("全選(A)") ,
		time = new JMenuItem("時間/日期(D)") ;
	//格式
	private JMenuItem font = new JMenuItem("字型(F)") ;
	private JCheckBox autoLineWrap = new JCheckBox("自動換行(W)") ;
	//檢視
	private JMenuItem state = new JMenuItem("狀態(S)") ;
	//幫助
	private JMenuItem
		checkHelp = new JMenuItem("檢視幫助(H)") ,
		about = new JMenuItem("關於記事本(A)") ;
	//文字域
	private JTextArea txt = new JTextArea() ;
	//彈出選單
	private JPopupMenu jpm = new JPopupMenu() ;
	//定義彈出視窗的開啟狀態
	private static boolean isOpen = false ;
	//獲取螢幕的尺寸
	private int x = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth() ;
	private int y = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight() ;
	public MyNotepad(){
		//新建
		newFile.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				String text = txt.getText() ;
				if(!text.equals("")){
					String str[] = text.split("\n") ;
					int result = JOptionPane.showConfirmDialog(null, "是否將更改儲存到 "+
					title+"?", "記事本",  JOptionPane.YES_NO_CANCEL_OPTION) ;
					if(result == JOptionPane.NO_OPTION){		//不儲存
						txt.setText("");
					}else if(result == JOptionPane.CANCEL_OPTION){}		//取消儲存
					else if(result == 0){			//儲存
						JFileChooser jfc = new JFileChooser() ;
						jfc.setDialogTitle("儲存");
						int ssd = jfc.showSaveDialog(MyNotepad.this) ;
						if(ssd == jfc.APPROVE_OPTION){
							File file = jfc.getSelectedFile() ;
							PrintStream out = null ;
							try {
								out = new PrintStream(new FileOutputStream(file)) ;
							} catch (FileNotFoundException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
							for(String s:str){
								out.print(s + "\r\n");
							}
							out.close();
							txt.setText(""); ;
						}
					}
				}
			}
		});
		//開啟
		open.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				JFileChooser jfc = new JFileChooser() ;
				jfc.setDialogTitle("開啟");
				int result = jfc.showOpenDialog(MyNotepad.this) ;
				if(result == JFileChooser.CANCEL_OPTION){}
				else if(result == JFileChooser.APPROVE_OPTION){
					File file = jfc.getSelectedFile() ;
					BufferedReader input = null ;
					try {
						input = new BufferedReader(new InputStreamReader(new FileInputStream(file))) ;
					} catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					String temp = null ;
					try {
						while((temp = input.readLine())!=null){
							txt.append(temp +"\n");
						}
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					try {
						input.close() ;
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			} 
		});
		//儲存
		save.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				String str[] = txt.getText().split("\n") ;
				JFileChooser jfc = new JFileChooser() ;
				jfc.setDialogTitle("儲存");
				int ssd = jfc.showSaveDialog(MyNotepad.this) ;
				if(ssd == jfc.APPROVE_OPTION){
					File file = jfc.getSelectedFile() ;
					PrintStream out = null ;
					try {
						out = new PrintStream(new FileOutputStream(file)) ;
					} catch (FileNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
					for(String s:str){
						out.print(s + "\r\n");
					}
					out.close();
				}
			}
		});
		//退出
		exit.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				String str = txt.getText() ;
				if(!str.equals("")){
					int result = JOptionPane.showConfirmDialog(null, "退出前是否儲存?", "退出", 
							JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE) ;
					if(result == JOptionPane.YES_OPTION){}
					if(result == JOptionPane.NO_OPTION){
						dispose() ;
					}
					if(result == JOptionPane.CANCEL_OPTION){}
				}else{
					dispose() ;
				}
			}
		});
		/*
		 * 撤銷功能
		 */
		final UndoManager undom = new UndoManager() ;
		txt.getDocument().addUndoableEditListener(new UndoableEditListener(){
			@Override
			public void undoableEditHappened(UndoableEditEvent e) {
				undom.addEdit(e.getEdit()) ;
				}
			});
		undo.addActionListener(new ActionListener(){
			@Override
			public void actionPerformed(ActionEvent e) {
				if(undom.canUndo()){
					undom.undo();
				}
			}
		});
		//剪下
		cut.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				txt.cut() ;
			}
		});
		//貼上
		paste.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				txt.paste();
			}
		});
		//刪除
		delete.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				int start = txt.getSelectionStart() ;
				int end = txt.getSelectionEnd() ;
				txt.replaceRange("", start, end);
			}
		});
		/*
		 * 為了更好地訪問本類中的屬性,所以查詢使用內部類
		 */
		//定義查詢內部類
		
		class FindDialog extends JDialog{
		    private JPanel pan = new JPanel() ;
			private JLabel label = new JLabel("查詢內容(N):") ;
			private JTextField txtf = new JTextField(20) ;
			private JButton btnf = new JButton("查詢下一個(F)") ;
			private JButton btnc = new JButton("取消") ;
			private JCheckBox jcb = new JCheckBox("區分大小寫(C)") ;
			private JRadioButton jrb1 = new JRadioButton("向上(U)") ;
			private JRadioButton jrb2 = new JRadioButton("向下(D)",true) ;
			public FindDialog(){
				super(MyNotepad.this, "查詢") ;
				//當文字框中有內容時按鈕才起作用
				txtf.getDocument().addDocumentListener(new DocumentListener(){

					@Override
					public void insertUpdate(DocumentEvent e) {
							btnf.setEnabled(true);
					}
					@Override
					public void removeUpdate(DocumentEvent e) {
						if(txtf.getText().length() == 0){
							btnf.setEnabled(false);
						}
					}
					@Override
					public void changedUpdate(DocumentEvent e) {
					}
				});
				btnf.addActionListener(new ActionListener(){
					public void actionPerformed(ActionEvent e){
						String str = txtf.getText() ;
						String texta = txt.getText() ;
						int start = 0 ;				
						int end = 0 ;
						int caretPosition = txt.getCaretPosition() ;			//記錄游標的起始位置
						if(jcb.isSelected()){		//區分大小寫
							if(jrb2.isSelected()){		//向下查詢,如果有游標就從游標的位置開始查詢,否則就從選中的文字之後的位置開始查詢
								start = (txt.getSelectedText()==null ? caretPosition : txt.getSelectionEnd()) ;
								start = texta.indexOf(str, start) ;
								if(start == -1){			//如果沒有找到
									JOptionPane.showMessageDialog(null, "找不到"+str);
								}else{		//如果找到了
									end = start + str.length() ;
									txt.select(start, end);
								}
							}else if(jrb1.isSelected()){	//向上查詢,如果有游標就從游標的位置開始查詢,否則就從選中的文字之前的位置開始查詢
								end = (txt.getSelectedText()==null ? caretPosition : txt.getSelectionStart()) ;
								String subtext = texta.substring(0, end) ;
								start = subtext.lastIndexOf(str, end-1) ;
								if(start == -1){
									JOptionPane.showMessageDialog(null, "找不到"+str) ;
								}else{
									end = start + str.length()  ;
									txt.select(start, end);
								}
							}
						}
						if(!jcb.isSelected()){		//不區分大小寫
							texta = texta.toLowerCase() ;
							if(jrb2.isSelected()){		//向下查詢,如果有游標就從游標的位置開始查詢,否則就從選中的文字之後的位置開始查詢
								start = (txt.getSelectedText()==null ? caretPosition : txt.getSelectionEnd()) ;
								start = texta.indexOf(str.toLowerCase(), start) ;
								if(start == -1){			//如果沒有找到
									JOptionPane.showMessageDialog(null, "找不到"+str) ;
								}else{		//如果找到了
									end = start + str.length() ;
									txt.select(start, end);
								}
							}else if(jrb1.isSelected()){	//向上查詢,如果有游標就從游標的位置開始查詢,否則就從選中的文字之前的位置開始查詢
								end = (txt.getSelectedText() == null ? caretPosition : txt.getSelectionStart()) ;
								String subtext = texta.substring(0, end) ;
								start = subtext.lastIndexOf(str.toLowerCase(), end-1) ;
								if(start == -1){
									JOptionPane.showMessageDialog(null, "找不到"+str) ;
								}else{
									end = start + str.length() ;
									txt.select(start, end);
								}
							}
						}
					}
				});
				btnc.addActionListener(new ActionListener(){
					public void actionPerformed(ActionEvent e){
						dispose() ;
						isOpen = false ;
					}
				});
				
				this.setLayout(null) ;
				label.setBounds(12,10,80,20) ;
				txtf.setBounds(100,10,170,20) ;
				btnf.setBounds(280,10,90,20) ;
				btnf.setMargin(new Insets(0, 0,0, 0)) ;
				btnf.setEnabled(false);					//初始化查詢下一個按鈕不可選
				jcb.setBounds(12,70,110,20) ;
				jrb1.setMargin(new Insets(0,0,0,0)) ;
				jrb2.setMargin(new Insets(0,0,0,0)) ;
				ButtonGroup group = new ButtonGroup() ;
				group.add(jrb1);
				group.add(jrb2);
				pan.add(jrb1) ;
				pan.add(jrb2) ;
				pan.setBorder(BorderFactory.createTitledBorder("方向")) ;
				pan.setBounds(120,40,150,55) ;
				btnc.setBounds(280,40,90,20) ;
				btnc.setMargin(new Insets(0,0,0,0)) ;
				add(btnf) ;
				add(label) ;
				add(txtf) ;
				add(jcb) ;
				add(pan) ;
				add(btnc) ;
				setSize(380,130) ;
				setLocation(x/2-190,y/2-65) ;
				setResizable(false) ;
				setVisible(true) ;
				setDefaultCloseOperation(DISPOSE_ON_CLOSE) ;
				//每次只能顯示一個視窗
				addWindowListener(new WindowAdapter(){
					public void windowOpened(WindowEvent e){
						isOpen = true ;
					}
				}) ;
				addWindowListener(new WindowAdapter(){
					public void windowClosing(WindowEvent e){
						isOpen = false ;
					}
				}) ;
			}
		}
		//查詢的監聽事件
		find.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				if(!isOpen){
					new FindDialog() ;
				}
			}
		});
		
		
		//替換內部類
		class ReplaceDialog extends JDialog{
			private JLabel label1 = new JLabel("查詢內容(N)") ;
			private JLabel label2 = new JLabel("替換為(P)") ;
			private JTextField field1 = new JTextField(20) ;
			private JTextField field2 = new JTextField(20) ;
			private JButton find = new JButton("查詢下一個(F)") ;
			private JButton replace = new JButton("替換(R)") ;
			private JButton replaceAll = new JButton("全部替換(A)") ;
			private JButton canc = new JButton("取消") ;
			private JCheckBox jcb = new JCheckBox("區分大小寫(C)") ;
			public ReplaceDialog(){
				super(MyNotepad.this,"查詢") ;
				this.setLayout(null) ;
				label1.setBounds(12,5,80,20) ;
				label2.setBounds(12,30,80,20) ;
				field1.setBounds(100,5,170,20) ;
				field2.setBounds(100,30,170,20) ;
				find.setBounds(280,5,90,20) ;
				find.setMargin(new Insets(0, 0,0, 0)) ;
				replace.setBounds(280,30,90,20) ;
				replace.setMargin(new Insets(0,0,0,0)) ;
				replaceAll.setBounds(280,55,90,20) ;
				replaceAll.setMargin(new Insets(0,0,0,0)) ;
				jcb.setBounds(12,70,105,20) ;
				jcb.setMargin(new Insets(0,0,0,0)) ;
				canc.setBounds(280,80,90,20) ;
				field1.getDocument().addDocumentListener(new DocumentListener(){
					//當文字框中有內容時按鈕才起作用
						@Override
						public void insertUpdate(DocumentEvent e) {
								find.setEnabled(true);
								replace.setEnabled(true);
								replaceAll.setEnabled(true);
						}
						@Override
						public void removeUpdate(DocumentEvent e) {
							if(field1.getText().length() == 0){
								find.setEnabled(false);
								replace.setEnabled(false);
								replaceAll.setEnabled(false);
							}
						}
						@Override
						public void changedUpdate(DocumentEvent e) {
						}
					});
				//查詢下一個按鈕
				find.addActionListener(new ActionListener(){
					public void actionPerformed(ActionEvent e){
						new findFunction() ;
					}
				});
				//替換按鈕
				replace.addActionListener(new ActionListener(){
					public void actionPerformed(ActionEvent e){
						//如果有選中的內容就替換,然後選中下一個要替換的內容,否則先查詢要替換的內容
						if(txt.getSelectedText()!=null){				
							txt.replaceSelection(field2.getText());
						}
						new findFunction() ;
					}
				});
				//替換所有按鈕
				replaceAll.addActionListener(new ActionListener(){
					public void actionPerformed(ActionEvent e){
						String str = txt.getText() ;
						if(jcb.isSelected()){
							str = str.replaceAll(field1.getText(), field2.getText()) ;
						}else{
							str = str.replaceAll("(?i)" + field1.getText(), field2.getText()) ;
						}
						txt.setText(str);
					}
				});
				//取消按鈕
				canc.addActionListener(new ActionListener(){
					public void actionPerformed(ActionEvent e){
						dispose() ;
						isOpen = false ;
					}
				});
				add(label1) ;
				add(label2) ;
				add(field1) ;
				add(field2) ;
				find.setEnabled(false);
				replace.setEnabled(false);
				replaceAll.setEnabled(false);
				add(find) ;
				add(replace) ;
				add(replaceAll) ;
				add(jcb) ;
				add(canc) ;
				setSize(380,130) ;
				setLocation(x/2-190,y/2-65) ;
				setResizable(false) ;
				setVisible(true) ;
				setDefaultCloseOperation(DISPOSE_ON_CLOSE) ;
				addWindowListener(new WindowAdapter(){
					public void windowOpened(WindowEvent e){
						isOpen = true ;
					}
				}) ;
				addWindowListener(new WindowAdapter(){
					public void windowClosing(WindowEvent e){
						isOpen = false ;
					}
				}) ;
			}
			//替換對話方塊中查詢功能類
			/*
			 * 為了簡化程式碼,將替換對話方塊裡面的查詢功能提取出來,成為一個內部類
			 */
			class findFunction {
				
				public findFunction(){				//要替換的字串的位置
					int start = 0 ;
					int end = 0 ;
					int caretPosition = txt.getCaretPosition() ;
					String str = field1.getText() ;
					String texta = txt.getText() ;
					//區分大小寫,向下查詢,如果有游標就從游標的位置開始查詢,否則就從選中的文字之後的位置開始查詢
					if(jcb.isSelected()){		
						start = (txt.getSelectedText()==null ? caretPosition : txt.getSelectionEnd()) ;
						start = texta.indexOf(str.toLowerCase(), start) ;
						if(start == -1){			//如果沒有找到
							JOptionPane.showMessageDialog(null, "找不到"+str) ;
						}else{		//如果找到了
							end = start + str.length() ;
							txt.select(start, end);
						}
					}else if(!jcb.isSelected()){		//不區分大小寫
						texta = texta.toLowerCase() ;
						//向下查詢,如果有游標就從游標的位置開始查詢,否則就從選中的文字之後的位置開始查詢
						start = (txt.getSelectedText()==null ? caretPosition : txt.getSelectionEnd()) ;
						start = texta.indexOf(str.toLowerCase(), start) ;
						if(start == -1){			//如果沒有找到
							JOptionPane.showMessageDialog(null, "找不到"+str) ;
						}else{		//如果找到了
							end = start + str.length() ;
							txt.select(start, end);
						}
					}
				}
			}
		}
		replace.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				if(!isOpen){
					new ReplaceDialog() ;
				}
			}
		});
		//轉到內部類
		class GoToDialog extends JDialog{
			private JLabel label = new JLabel("行號(L):") ;
			private JTextField field = new JTextField() ;
			private JButton goToBtn = new JButton("轉到") ;
			private JButton canBtn = new JButton("取消") ;
			private int rowNum = 0 ;//行號 
			public GoToDialog(){
				field.addKeyListener(new KeyAdapter(){
					public void keyTyped(KeyEvent e){
						if(!(e.getKeyChar()>='0' && e.getKeyChar()<='9' )){
							e.consume();
						}
					}
				});
				//轉到
				goToBtn.addActionListener(new ActionListener(){
					public void actionPerformed(ActionEvent e){
						rowNum = Integer.parseInt(field.getText()) ;
						if(rowNum>txt.getLineCount()){
							JOptionPane.showMessageDialog(null, "行數超過了總行數", "記事本-跳行",JOptionPane.INFORMATION_MESSAGE);
							field.setText(txt.getLineCount() +"") ;
							field.requestFocus() ;			//獲取文字域的焦點
							field.selectAll();
						}else{
							int position = 0 ;
							try {
								position = txt.getLineStartOffset(rowNum-1) ;
							} catch (BadLocationException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
							GoToDialog.this.dispose();
							txt.requestFocus();
							txt.setCaretPosition(position);
						}
					}
				});
				//取消
				canBtn.addActionListener(new ActionListener(){
					public void actionPerformed(ActionEvent e){
						dispose() ;
						isOpen = false ;
					}
				});
				setLayout(null) ;
				label.setBounds(12,10,100,20) ;
				field.setBounds(12,30,230,20) ;
				goToBtn.setBounds(85,65,75,20) ;
				canBtn.setBounds(167,65,75,20) ;
				add(label) ;
				add(field) ;
				add(goToBtn) ;
				add(canBtn) ; 
				setTitle("轉到指定行") ;
				setModal(true) ;		//當對話方塊彈出時母視窗不可編輯
				setSize(270,130) ;
				setLocation(x/2-135,y/2-65) ;
				setResizable(false) ;
				setVisible(true) ;
				setDefaultCloseOperation(DISPOSE_ON_CLOSE) ;
				addWindowListener(new WindowAdapter(){
					public void windowOpened(WindowEvent e){
						isOpen = true ;
					}
				}) ;
				addWindowListener(new WindowAdapter(){
					public void windowClosing(WindowEvent e){
						isOpen = false ;
					}
				}) ;
			}
		}
		//轉到
		goTo.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				if(!isOpen){
					new GoToDialog() ;
				}
			}
		});
		//全選
		selectAll.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				txt.requestFocus();
				txt.selectAll() ;
			}
		});
		time.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				String dateTime = null ;
				int pos = txt.getCaretPosition() ;
				dateTime = new SimpleDateFormat("hh:mm yyyy/MM/dd").format(new Date()) ;
				txt.insert(dateTime, pos);
			}
		});
		//自動換行
		autoLineWrap.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				if(autoLineWrap.isSelected()){
					txt.setLineWrap(true);
				}else{
					txt.setLineWrap(false);
				}
			}
		});
		//字型內部類
		class FontDialog extends JDialog{
			private JLabel label1 = new JLabel("字型(F):") ;
			private JLabel label2 = new JLabel("字形(Y):") ;
			private JLabel label3 = new JLabel("大小(S):") ;
			private JLabel instns = new JLabel("中文示例AaBaCc",JLabel.CENTER) ;
			private JTextField field1 = new JTextField() ;
			private JTextField field2 = new JTextField() ;
			private JTextField field3 = new JTextField() ;
			private String fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames() ;
			private JScrollPane scr1 = new JScrollPane() ;
			private JScrollPane scr2 = new JScrollPane() ;
			private JScrollPane scr3 = new JScrollPane() ;
			private JList fontList = null ;
			private JList fStyleList = null ;
			private JList fSizeList = null ;
			private JButton okBtn = new JButton("確定") ;
			private JButton cancBtn = new JButton("取消") ;
			//示例的顯示
			private String selectedFont = "Fixedsys";
			private int selectedStyle = Font.PLAIN;
			private float selectedSize = 16;
			public FontDialog() {
				
				fontList = new JList(fonts) ;
				//fontStyle
				String style[] = {"常規","傾斜","粗體","傾斜 粗體"} ;
				fStyleList = new JList(style) ;
				//fontSize
				String size[] = {"8","9","10","11","12","14","16","18","20","22","24",
						"26","28","36","48","72","初號","小號","一號","小一","二號",
						"小二","三號","小三","四號","小四","五號","六號","小六","七號","八號"} ;
				fSizeList = new JList(size) ;
				//Jlist中一次只能選擇一個選項
				fontList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) ;
				fStyleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) ;
				fSizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION) ;
				scr1.add(fontList) ;
				scr2.add(fStyleList) ;
				scr3.add(fSizeList) ;
				scr1.setViewportView(fontList);
				scr2.setViewportView(fStyleList);
				scr3.setViewportView(fSizeList);
				okBtn.setBounds(250,450,80,30) ;
				cancBtn.setBounds(340,450,80,30) ;
				label1.setBounds(20,20,50,20) ;
				label2.setBounds(205,20,50,20) ;
				label3.setBounds(350,20,50,20) ;
				instns.setBounds(205,280,215,80) ;
				instns.setBorder(BorderFactory.createTitledBorder("示例")) ;
				field1.setBounds(20,40,170,20) ;
				field2.setBounds(205,40,130,20) ;
				field3.setBounds(350,40,70,20) ;
				scr1.setBounds(20,60,170,170) ;
				scr2.setBounds(205,60,130,170) ;
				scr3.setBounds(350,60,70,150) ;
				scr1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) ;
				scr2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) ;
				scr3.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) ;
				//文字框1
				field1.addKeyListener(new KeyAdapter(){
					public void keyTyped(KeyEvent e){
						int count = 0 ;			//文字框中的字元數
						String str = null ;		//儲存輸入到文字框中的字元
						int size = fontList.getModel().getSize() ;			//fontList中的文字個數
						str = field1.getText()+e.getKeyChar()+"" ;
						count = str.length() ;
						
						for(int i=0; i=count){
								//判斷輸入的是否與JList中的內容部分匹配(忽略大小寫)
								if(fontList.getModel().getElementAt(i).substring(0, count).compareToIgnoreCase(str)==0){
									fontList.ensureIndexIsVisible(size-i>=10 ? i+9 : size-1);
									if(fontList.getModel().getElementAt(i).compareToIgnoreCase(str)==0){
										fontList.setSelectedIndex(i);
									}
									break ;
								}
								else{
									fontList.ensureIndexIsVisible(0);
									fontList.clearSelection();
								}
							}
						}
					}
				});
				//文字框2
				field2.addKeyListener(new KeyAdapter(){
					public void keyTyped(KeyEvent e){
						int count = 0 ;			//文字框中的字元數
						String str = null ;		//儲存輸入到文字框中的字元
						int size = fStyleList.getModel().getSize() ;			//fontList中的文字個數
						str = field2.getText()+e.getKeyChar()+"" ;
						count = str.length() ;
						
						for(int i=0; i=count){
								//判斷輸入的是否與JList中的內容部分匹配(忽略大小寫)
								if(fStyleList.getModel().getElementAt(i).substring(0, count).compareToIgnoreCase(str)==0){
									if(fStyleList.getModel().getElementAt(i).compareToIgnoreCase(str)==0){
										fStyleList.setSelectedIndex(i);
									}
									break ;
								}
								else{
									fStyleList.clearSelection();
								}
							}
						}
					}
				});
				//文字框3
				field3.addKeyListener(new KeyAdapter(){
					public void keyTyped(KeyEvent e){
						int count = 0 ;			//文字框中的字元數
						String str = null ;		//儲存輸入到文字框中的字元
						int size = fSizeList.getModel().getSize() ;			//fontList中的文字個數
						str = field3.getText()+e.getKeyChar()+"" ;
						count = str.length() ;
						
						for(int i=0; i=count){
								//判斷輸入的是否與JList中的內容部分匹配(忽略大小寫)
								if(fSizeList.getModel().getElementAt(i).substring(0, count).compareToIgnoreCase(str)==0){
									fSizeList.ensureIndexIsVisible(size-i>=9 ? i+8 : size-1);
									if(fSizeList.getModel().getElementAt(i).compareToIgnoreCase(str)==0){
										fSizeList.setSelectedIndex(i);
									}
									break ;
								}
								else{
									fSizeList.ensureIndexIsVisible(0);
									fSizeList.clearSelection();
								}
							}
						}
					}
				});
				//設定示例中的文字字型樣式
				//設定字形與字號對照表
				final Map map = new HashMap() ;
				map.put("常規", (float) Font.PLAIN) ;
				map.put("傾斜", (float) Font.ITALIC) ;
				map.put("粗體", (float) Font.BOLD) ;
				map.put("傾斜 粗體", (float) (Font.ITALIC+Font.BOLD)) ;
				map.put("初號", 42f) ;
				map.put("小號", 36f) ;
				map.put("一號", 26f) ;
				map.put("小一", 24f) ;
				map.put("二號", 22f) ;
				map.put("小二", 18f) ;
				map.put("三號", 16f) ;
				map.put("小三", 15f) ;
				map.put("四號", 14f) ;
				map.put("小四", 12f) ;
				map.put("五號", 10.5f) ;
				map.put("六號", 7.5f) ;
				map.put("小六", 6.5f) ;
				map.put("七號", 5.5f) ;
				map.put("八號", 5f) ;
				
				//字型列表監聽事件
				fontList.addListSelectionListener(new ListSelectionListener(){
					@Override
					public void valueChanged(ListSelectionEvent e) {
						String txtFont = txt.getFont().getName() ;		//獲取文字中的字型
						selectedFont = fontList.isSelectionEmpty() ? txtFont :fontList.getSelectedValue() ;
						instns.setFont(new Font(selectedFont,selectedStyle,(int)selectedSize));
					}
				}) ;
				//字型樣式監聽事件
				fStyleList.addListSelectionListener(new ListSelectionListener(){
					@Override
					public void valueChanged(ListSelectionEvent e) {
						int txtStyle = txt.getFont().getStyle() ;		//獲取文字中的字型
						selectedStyle = (int) (fStyleList.isSelectionEmpty() ? txtStyle :map.get(fStyleList.getSelectedValue())) ;
						instns.setFont(new Font(selectedFont,selectedStyle,(int)selectedSize));
					}
				}) ;
				//字型大小監聽
				fSizeList.addListSelectionListener(new ListSelectionListener(){
					public void valueChanged(ListSelectionEvent e){
						int txtSize = txt.getFont().getSize() ;
						if(!fSizeList.isSelectionEmpty()){
							String temp = fSizeList.getSelectedValue() ;
							if(temp.matches("\\d+")){
								selectedSize = Integer.parseInt(temp) ;
							}else{
								selectedSize = map.get(fSizeList.getSelectedValue()) ;
							}
						}
						instns.setFont(new Font(selectedFont,selectedStyle,(int)selectedSize));
					}
				});
				//確定按鈕
				okBtn.addActionListener(new ActionListener(){
					public void actionPerformed(ActionEvent e){
						txt.setFont(new Font(selectedFont,selectedStyle,(int)selectedSize));
						isOpen = false ;
						dispose() ;
					}
				});
				//取消按鈕
				cancBtn.addActionListener(new ActionListener(){
					public void actionPerformed(ActionEvent e){
						dispose() ;
						isOpen = false ;
					}
				});
				/*class MyRender extends DefaultListCellRenderer{
					public Component getListCellRendererComponent(JList<?> list, Object value, 
							int index, boolean isSelected,
							boolean cellHasFocus){
						String font = value.toString() ;
						setFont(new Font(font,Font.PLAIN,12)) ;
						return this ;
					}
				}*/
				setLayout(null) ;
				add(label1) ;
				add(label2) ;
				add(label3) ;
				add(instns) ;
				add(field1) ;
				add(field2) ;
				add(field3) ;
				add(scr1) ;
				add(scr2) ;
				add(scr3) ;
				add(okBtn) ;
				add(cancBtn) ;
				setModal(true) ;		//當對話方塊彈出時母視窗不可編輯
				setSize(440,530) ;
				setLocation(x/2-220,y/2-265) ;
				setResizable(false) ;
				setVisible(true) ;
				setDefaultCloseOperation(DISPOSE_ON_CLOSE) ;
				addWindowListener(new WindowAdapter(){
					public void windowOpened(WindowEvent e){
						isOpen = true ;
					}
				}) ;
				addWindowListener(new WindowAdapter(){
					public void windowClosing(WindowEvent e){
						isOpen = false ;
					}
				}) ;
			}
		}
		//字型
		font.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				if(!isOpen){
					new FontDialog() ;
				}
			}
		});
		//檢視幫助
		checkHelp.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				JOptionPane.showMessageDialog(null, "與Windows系統下的幫助相似", "幫助", JOptionPane.CLOSED_OPTION);
			}
		});
		//關於
		about.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				JOptionPane.showMessageDialog(null, "仿Windows記事本,初學Java的練手作品", "關於", JOptionPane.CLOSED_OPTION);
			}
		});
		//右鍵彈出選單內部類
		class popupListener extends MouseAdapter{
			private JPopupMenu popup = null ;
			public popupListener(JPopupMenu popup){
				this.popup = popup ;
				
			}
			public void mouseReleased(MouseEvent e){
				showPopupMenu(e) ;
			}
			public void mouseClicked(MouseEvent e){
				showPopupMenu(e) ;
			}
			private  void showPopupMenu(MouseEvent e) {
			   if (e.isPopupTrigger()) {
			   //右鍵彈出選單
				jpm.add(undo) ;
				jpm.add(cut) ;
				jpm.add(copy) ;
				jpm.add(delete) ;
				jpm.add(find) ;
				jpm.add(replace) ;
				jpm.add(goTo) ;
				jpm.add(selectAll) ;
				jpm.add(time) ;
			    popup.show(e.getComponent(), e.getX(), e.getY());
			   }
			  }
			}
		
		//右鍵彈出選單
		txt.addMouseListener(new popupListener(jpm)) ;
		//設定快捷鍵
		newFile.setAccelerator(KeyStroke.getKeyStroke('N',java.awt.event.InputEvent.CTRL_DOWN_MASK));
		open.setAccelerator(KeyStroke.getKeyStroke('O',java.awt.event.InputEvent.CTRL_DOWN_MASK));
		save.setAccelerator(KeyStroke.getKeyStroke('S',java.awt.event.InputEvent.CTRL_DOWN_MASK));
		
		undo.setAccelerator(KeyStroke.getKeyStroke('Z',java.awt.event.InputEvent.CTRL_DOWN_MASK));
		cut.setAccelerator(KeyStroke.getKeyStroke('X',java.awt.event.InputEvent.CTRL_DOWN_MASK));
		copy.setAccelerator(KeyStroke.getKeyStroke('C',java.awt.event.InputEvent.CTRL_DOWN_MASK));
		paste.setAccelerator(KeyStroke.getKeyStroke('V',java.awt.event.InputEvent.CTRL_DOWN_MASK));
		find.setAccelerator(KeyStroke.getKeyStroke('F',java.awt.event.InputEvent.CTRL_DOWN_MASK));
		replace.setAccelerator(KeyStroke.getKeyStroke('H',java.awt.event.InputEvent.CTRL_DOWN_MASK));
		goTo.setAccelerator(KeyStroke.getKeyStroke('G',java.awt.event.InputEvent.CTRL_DOWN_MASK));
		selectAll.setAccelerator(KeyStroke.getKeyStroke('A',java.awt.event.InputEvent.CTRL_DOWN_MASK));
		time.setAccelerator((KeyStroke) KeyStroke.getAWTKeyStroke((char) KeyEvent.VK_F5));
		//設定助記鍵
		file.setMnemonic('F');
		edit.setMnemonic('E');
		format.setMnemonic('O');
		view.setMnemonic('V');
		help.setMnemonic('H');
		
		newFile.setMnemonic('N');
		open.setMnemonic('O');
		save.setMnemonic('S');
		exit.setMnemonic('X');
		
		undo.setMnemonic('U'); 
		cut.setMnemonic('T'); 
		copy.setMnemonic('C');
		paste.setMnemonic('P'); 
		delete.setMnemonic('L');
		find.setMnemonic('F');
		replace.setMnemonic('R');
		goTo.setMnemonic('G');
		selectAll.setMnemonic('A');
		time.setMnemonic('D');
		
		font.setMnemonic('F');
		autoLineWrap.setMnemonic('W');
		
		state.setMnemonic('S');
		
		checkHelp.setMnemonic('H');
		about.setMnemonic('A');
		
		txt.setFont(new Font("Fixedsys",Font.PLAIN,16));
		txt.setEditable(true);
	
		file.add(newFile) ;
		file.add(open) ;
		file.add(save) ;
		file.addSeparator();
		file.add(exit) ;
		
		edit.add(undo) ;
		edit.addSeparator();
		edit.add(cut) ;
		edit.add(copy) ;
		edit.add(paste) ;
		edit.add(delete) ;
		edit.addSeparator();
		edit.add(find) ;
		edit.add(replace) ;
		edit.add(goTo) ;
		edit.addSeparator();
		edit.add(selectAll) ;
		edit.add(time) ;
		
		format.add(autoLineWrap) ;
		format.add(font) ;
		view.add(state) ;
		help.add(checkHelp) ;
		help.addSeparator();
		help.add(about) ;
		
		mb.add(file) ;
		mb.add(edit) ;
		mb.add(format) ;
		mb.add(view) ;
		mb.add(help) ;
		setJMenuBar(mb) ;
		add(mp) ;
		add(new JScrollPane(txt)) ;
		setVisible(true) ;
		setSize(530,640) ;
		setLocation(x/2-265,y/2-320);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
	}
}


package org.mfy.notepad;

import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Notepad {

	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException | InstantiationException
				| IllegalAccessException | UnsupportedLookAndFeelException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		new MyNotepad() ;
	}

}