本文仿電腦自帶記事本,實(shí)現(xiàn)的功能有新建、新窗口、打開、保存、另存為、退出、撤銷、剪切、復(fù)制、粘貼、刪除、查找、查找下一個(gè)、查找上一個(gè)、替換、轉(zhuǎn)到、全選、時(shí)間/日期、自動換行、縮放(放大、縮小、恢復(fù)默認(rèn)大?。?,未實(shí)現(xiàn)功能有頁面設(shè)置、打印、字體、狀態(tài)欄、幫助。
僅供學(xué)習(xí)、參考,不要照搬,搬了弄懂也行,如有問題可以評論提出。
各部分內(nèi)容的實(shí)現(xiàn)我自己的見解如下,有不足之處歡迎指正:
JAVA記事本界面實(shí)現(xiàn)_云邊守望者的博客-CSDN博客
java記事本實(shí)現(xiàn)查找功能_云邊守望者的博客-CSDN博客
java記事本實(shí)現(xiàn)替換功能_云邊守望者的博客-CSDN博客
java記事本新窗口、全選、時(shí)間/日期、自動換行、縮放的實(shí)現(xiàn)_云邊守望者的博客-CSDN博客
java記事本實(shí)現(xiàn)剪切、復(fù)制、粘貼、刪除_云邊守望者的博客-CSDN博客
java記事本實(shí)現(xiàn)新建、打開、保存、另存為、退出功能_云邊守望者的博客-CSDN博客
java記事本實(shí)現(xiàn)轉(zhuǎn)到和撤銷功能_云邊守望者的博客-CSDN博客
附上幾張最終實(shí)現(xiàn)的界面圖:







另一種風(fēng)格:文章來源:http://www.zghlxwxcb.cn/news/detail-498881.html



源碼:文章來源地址http://www.zghlxwxcb.cn/news/detail-498881.html
import java.awt.BorderLayout;//邊框布局管理器
import java.awt.Dimension;//構(gòu)件屬性
import java.awt.Toolkit;//工具箱
import java.awt.Container;//容器 window panel
import java.awt.FlowLayout;//流式布局管理器
import java.awt.datatransfer.Clipboard;//獲取系統(tǒng)剪貼板
import java.awt.datatransfer.Transferable;//數(shù)據(jù)封裝
import java.awt.datatransfer.StringSelection;//創(chuàng)建能傳輸指定String的Transferable
import java.awt.datatransfer.DataFlavor;//Transferable支持的數(shù)據(jù)風(fēng)格
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;//事件監(jiān)聽
import java.awt.event.WindowAdapter;//針對窗口事件
import java.awt.event.WindowEvent;
import java.awt.event.KeyEvent;
import java.awt.GridLayout;//網(wǎng)格布局
import java.io.BufferedReader;//緩沖區(qū)讀入字符流
import java.io.BufferedWriter;//字符流寫入緩沖區(qū)
import java.io.File;
import java.io.FileNotFoundException;//找不到指定文件異常
import java.io.FileOutputStream;//文件字節(jié)輸出流
import java.io.FileReader;//文件讀取
import java.io.IOException;
import java.io.OutputStreamWriter;//字符->字節(jié)
import javax.swing.ImageIcon;//添加圖像圖標(biāo)
import javax.swing.JFileChooser;//文件選擇器
import javax.swing.JFrame;//窗體
import javax.swing.JMenu;//菜單
import javax.swing.JMenuBar;//菜單欄
import javax.swing.JMenuItem;//菜單中的項(xiàng)
import javax.swing.JLabel;
import javax.swing.JTextField;//允許編輯單行文本的組件
import javax.swing.JButton;
import javax.swing.JCheckBox;//復(fù)選框
import javax.swing.JCheckBoxMenuItem;
import javax.swing.ButtonGroup;//搭配Radiobutton
import javax.swing.JRadioButton;//單選按鈕
import javax.swing.BorderFactory;
import javax.swing.JOptionPane;//對話框
import javax.swing.JScrollPane;//滾動面板
import javax.swing.JTextArea;//文本區(qū)域組件
import javax.swing.KeyStroke;//快捷鍵
import javax.swing.event.MenuListener;//菜單監(jiān)聽
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;//接受文本文檔更改通知的接口
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;//所有可撤銷編輯監(jiān)聽器
import javax.swing.event.MenuEvent;
import javax.swing.JPanel;//面板
import javax.swing.JDialog;//對話框
import javax.swing.undo.UndoManager;//撤銷管理器
import java.text.SimpleDateFormat;
import java.util.Date;
import java.awt.Rectangle;
import javax.swing.text.BadLocationException;
import java.awt.Font;
import javax.swing.UIManager;
public class MyNotepad extends JFrame implements DocumentListener{
MenuHandler menuhandler = new MenuHandler();//事件處理
ImageIcon image;//窗口圖標(biāo)
JMenuBar jmenu;//菜單欄
JMenu jm_file,jm_edit,jm_format,jm_look,jm_help;
//文件的菜單項(xiàng)
JMenuItem file_newfile,file_newwindow,file_open,file_save,file_saveas,file_design,file_print,file_exit;
//編輯的菜單項(xiàng)
JMenuItem edit_undo,edit_cut,edit_copy,edit_paste,edit_delete,edit_find,edit_findnext,edit_findpre,edit_replace,edit_goto,edit_all,edit_time;
//格式的菜單項(xiàng)
JCheckBoxMenuItem format_linewrap;
JMenuItem format_font;
//查看的菜單項(xiàng)
JMenu look_zoom;
JMenuItem look_status;
//縮放的菜單項(xiàng)
JMenuItem increase,reduce,source;
//幫助的菜單項(xiàng)
JMenuItem help_item1,help_item2,help_item3;
JTextArea jtext;//文本區(qū)域
JScrollPane jspane;//滾動面板
private static String name;
JFileChooser jfilechoose = new JFileChooser("C:\\Users\\abc\\Desktop\\java_design");//文件選擇器(打開地址)
String filepath=null;
//系統(tǒng)剪貼板
Toolkit toolkit=Toolkit.getDefaultToolkit();
Clipboard clipBoard=toolkit.getSystemClipboard();
UndoManager undom;//撤銷管理器
//查找窗口組件
JDialog findDialog;//查找窗體
JTextField findText;//查找文本
JCheckBox matchCheckBox;//區(qū)分大小寫復(fù)選框
JRadioButton upButton;//向上按鈕
JRadioButton downButton;//向下按鈕
//替換窗口組件
JDialog replaceDialog;
JTextField findText1;
JCheckBox matchCheckBox1;
JRadioButton upButton1;
JRadioButton downButton1;
JTextField replaceText;//替換文本
//轉(zhuǎn)到窗口組件
JDialog gotoDialog;
JTextField field;
public static void main(String[] args) {
// try{
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
// }catch(Exception e){
// e.printStackTrace();
// }//添加后可改變文件選擇器的風(fēng)格
new MyNotepad().init();
}
// 初始化界面
public void init() {
// setSize(800, 600);
/*窗口顯示位置 x,y,width,height*/
setBounds(150,150,800,600);
// 設(shè)置關(guān)閉按鈕動作不執(zhí)行任何操作
setDefaultCloseOperation(0);
//指定布局管理器為BorderLayout
setLayout(new BorderLayout());
name = "新建文本文檔.txt";
// 設(shè)置標(biāo)志圖案
image = new ImageIcon("C:\\Users\\abc\\Desktop\\miao.jpg");
setIconImage(image.getImage());
// 設(shè)置文件名
setTitle(name + " - 記事本");
// 添加菜單欄
addMenu();
// 添加文本域
jtext = new JTextArea();
jtext.setFont(new Font("宋體", Font.PLAIN, 14));// 設(shè)置字體樣式
jtext.setWrapStyleWord(true);//設(shè)置單詞在一行不足容納時(shí)換行
jtext.setTabSize(2);//Tab鍵在文本框中的移動距離
undom = new UndoManager();// 創(chuàng)建撤銷管理器
UndoableEditListener undoHandler=new UndoHandler();
jtext.getDocument().addUndoableEditListener(undoHandler);// 為文本注冊監(jiān)聽器
jtext.getDocument().addDocumentListener(MyNotepad.this);
// 添加滾動面板
jspane = new JScrollPane(jtext);
jspane.setPreferredSize(new Dimension(600, 550));
add(jspane, BorderLayout.CENTER);
setResizable(true);//可改變大小
setVisible(true);// 設(shè)置窗口可見
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
int select = showSaveDialog();
if (select != JOptionPane.CANCEL_OPTION && select != JOptionPane.CLOSED_OPTION)
setDefaultCloseOperation(2);//隱藏并釋放窗體,dispose(),當(dāng)最后一個(gè)窗口被釋放后,則程序也隨之運(yùn)行結(jié)束。
}
});
}
// 添加菜單欄
private void addMenu() {
// 添加菜單欄
jmenu = new JMenuBar();
// 設(shè)置菜單欄位置在頂級窗口的頂部
setJMenuBar(jmenu);
// 菜單欄菜單
jm_file = new JMenu("文件(F)");
jm_file.setMnemonic('F');
// 給文件菜單添加菜單項(xiàng)
file_newfile = new JMenuItem("新建(N)");
file_newfile.setActionCommand("newfile");
file_newfile.addActionListener(menuhandler);
file_newfile.setAccelerator(KeyStroke.getKeyStroke("ctrl N"));
file_newwindow = new JMenuItem("新窗口(W)");
file_newwindow.setActionCommand("newwindow");
file_newwindow.addActionListener(menuhandler);
file_newwindow.setAccelerator(KeyStroke.getKeyStroke("ctrl shift N"));
file_open = new JMenuItem("打開(O)");
file_open.setActionCommand("open");
file_open.addActionListener(menuhandler);
file_open.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));
file_save = new JMenuItem("保存(S)");
file_save.setActionCommand("save");
file_save.addActionListener(menuhandler);
file_save.setAccelerator(KeyStroke.getKeyStroke("ctrl S"));
file_saveas = new JMenuItem("另存為(A)");
file_saveas.setActionCommand("saveas");
file_saveas.addActionListener(menuhandler);
file_saveas.setAccelerator(KeyStroke.getKeyStroke("ctrl shift S"));
file_design = new JMenuItem("頁面設(shè)置(U)");
file_print = new JMenuItem("打印(P)");
file_print.setAccelerator(KeyStroke.getKeyStroke("ctrl P"));
file_exit = new JMenuItem("退出(X)");
file_exit.setActionCommand("exit");
file_exit.addActionListener(menuhandler);
jm_edit = new JMenu("編輯(E)");
jm_edit.setMnemonic('E');
//給編輯菜單添加菜單項(xiàng)
edit_undo = new JMenuItem("撤銷(U)");
edit_undo.setActionCommand("undo");
edit_undo.addActionListener(menuhandler);
edit_undo.setAccelerator(KeyStroke.getKeyStroke("ctrl Z"));
edit_undo.setEnabled(false);
edit_cut = new JMenuItem("剪切(T)");
edit_cut.setActionCommand("cut");
edit_cut.addActionListener(menuhandler);
edit_cut.setAccelerator(KeyStroke.getKeyStroke("ctrl X"));
edit_copy = new JMenuItem("復(fù)制(C)");
edit_copy.setActionCommand("copy");
edit_copy.addActionListener(menuhandler);
edit_copy.setAccelerator(KeyStroke.getKeyStroke("ctrl C"));
edit_paste = new JMenuItem("粘貼(P)");
edit_paste.setActionCommand("stickup");
edit_paste.addActionListener(menuhandler);
edit_paste.setAccelerator(KeyStroke.getKeyStroke("ctrl V"));
edit_delete = new JMenuItem("刪除(L)");
edit_delete.setActionCommand("delete");
edit_delete.addActionListener(menuhandler);
edit_delete.setAccelerator(KeyStroke.getKeyStroke("DELETE"));
edit_find = new JMenuItem("查找(F)");
edit_find.setActionCommand("findwindow");
edit_find.addActionListener(menuhandler);
edit_find.setAccelerator(KeyStroke.getKeyStroke("ctrl F"));
edit_findnext = new JMenuItem("查找下一個(gè)(N)");
edit_findnext.setActionCommand("fastfindnext");
edit_findnext.addActionListener(menuhandler);
edit_findnext.setAccelerator(KeyStroke.getKeyStroke("F3"));
edit_findpre = new JMenuItem("查找上一個(gè)(V)");
edit_findpre.setActionCommand("fastfindpre");
edit_findpre.addActionListener(menuhandler);
edit_findpre.setAccelerator(KeyStroke.getKeyStroke("shift F3"));
edit_replace = new JMenuItem("替換(R)");
edit_replace.setActionCommand("replacewindow");
edit_replace.addActionListener(menuhandler);
edit_replace.setAccelerator(KeyStroke.getKeyStroke("ctrl H"));
edit_goto = new JMenuItem("轉(zhuǎn)到(G)");
edit_goto.setActionCommand("gotowindow");
edit_goto.addActionListener(menuhandler);
edit_goto.setAccelerator(KeyStroke.getKeyStroke("ctrl G"));
edit_all = new JMenuItem("全選(A)");
edit_all.setActionCommand("selectall");
edit_all.addActionListener(menuhandler);
edit_all.setAccelerator(KeyStroke.getKeyStroke("ctrl A"));
edit_time = new JMenuItem("時(shí)間/日期(D)");
edit_time.setActionCommand("time");
edit_time.addActionListener(menuhandler);
edit_time.setAccelerator(KeyStroke.getKeyStroke("F5"));
//當(dāng)選擇編輯菜單時(shí),設(shè)置剪切、復(fù)制、粘貼、刪除等功能的可用性
jm_edit.addMenuListener(new MenuListener()
{ public void menuCanceled(MenuEvent e)//取消菜單時(shí)調(diào)用
{ checkMenuItemEnabled();//設(shè)置剪切、復(fù)制、粘貼、刪除等功能的可用性
}
public void menuDeselected(MenuEvent e)//取消選擇某個(gè)菜單時(shí)調(diào)用
{ checkMenuItemEnabled();//設(shè)置剪切、復(fù)制、粘貼、刪除等功能的可用性
}
public void menuSelected(MenuEvent e)//選擇某個(gè)菜單時(shí)調(diào)用
{ checkMenuItemEnabled();//設(shè)置剪切、復(fù)制、粘貼、刪除等功能的可用性
}
});
jm_format = new JMenu("格式(O)");
jm_format.setMnemonic('O');
// 給格式菜單添加菜單項(xiàng)
format_linewrap = new JCheckBoxMenuItem("自動換行(W)");
format_linewrap.setMnemonic('W');//設(shè)置快捷鍵ALT+W
format_linewrap.setState(false);//初始狀態(tài)為不自動換行
format_linewrap.setActionCommand("linewrap");
format_linewrap.addActionListener(menuhandler);
format_font = new JMenuItem("字體(F)");
jm_look = new JMenu("查看(V)");
jm_look.setMnemonic('V');
// 給查看菜單添加菜單項(xiàng)
look_zoom = new JMenu("縮放(Z)");
look_zoom.setMnemonic('Z');
increase = new JMenuItem("放大(+)");
increase.setActionCommand("sizetobig");
increase.addActionListener(menuhandler);
increase.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS,KeyEvent.CTRL_MASK));
reduce = new JMenuItem("縮小(-)");
reduce.setActionCommand("sizetosmall");
reduce.addActionListener(menuhandler);
reduce.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_MINUS,KeyEvent.CTRL_MASK));
source = new JMenuItem("恢復(fù)默認(rèn)縮放");
source.setActionCommand("sourcesize");
source.addActionListener(menuhandler);
source.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_0,KeyEvent.CTRL_MASK));
look_status = new JMenuItem("狀態(tài)欄(S)");
jm_help = new JMenu("幫助(H)");
jm_help.setMnemonic('H');
// 給幫助菜單添加菜單項(xiàng)
help_item1 = new JMenuItem("查看幫助(H)");
help_item2 = new JMenuItem("發(fā)送反饋(F)");
help_item3 = new JMenuItem("關(guān)于記事本(A)");
jmenu.add(jm_file);
jm_file.add(file_newfile);
jm_file.add(file_newwindow);
jm_file.add(file_open);
jm_file.add(file_save);
jm_file.add(file_saveas);
jm_file.addSeparator();
jm_file.add(file_design);
jm_file.add(file_print);
jm_file.addSeparator();
jm_file.add(file_exit);
jmenu.add(jm_edit);
jm_edit.add(edit_undo);
jm_file.addSeparator();
jm_edit.add(edit_cut);
jm_edit.add(edit_copy);
jm_edit.add(edit_paste);
jm_edit.add(edit_delete);
jm_edit.addSeparator();
jm_edit.add(edit_find);
jm_edit.add(edit_findnext);
jm_edit.add(edit_findpre);
jm_edit.add(edit_replace);
jm_edit.add(edit_goto);
jm_edit.addSeparator();
jm_edit.add(edit_all);
jm_edit.add(edit_time);
jmenu.add(jm_format);
jm_format.add(format_linewrap);
jm_format.add(format_font);
jmenu.add(jm_look);
jm_look.add(look_zoom);
look_zoom.add(increase);
look_zoom.add(reduce);
look_zoom.add(source);
jm_look.add(look_status);
jmenu.add(jm_help);
jm_help.add(help_item1);
jm_help.add(help_item2);
jm_help.addSeparator();
jm_help.add(help_item3);
}
public void findwindow(){
//查找窗口
findDialog=new JDialog(this,"查找",false);//false時(shí)允許其他窗口同時(shí)處于激活狀態(tài)
Container con=findDialog.getContentPane();//獲取對話框面板
con.setLayout(new FlowLayout(FlowLayout.LEFT)); //左對齊
JLabel findContentLabel=new JLabel("查找內(nèi)容(N):");
findText=new JTextField(15);
JButton findNextButton=new JButton("查找下一個(gè)(F):");
findNextButton.setActionCommand("findnext");
findNextButton.addActionListener(menuhandler);
matchCheckBox=new JCheckBox("區(qū)分大小寫(C)");
ButtonGroup bGroup=new ButtonGroup();
upButton=new JRadioButton("向上(U)");
downButton=new JRadioButton("向下(U)");
downButton.setSelected(true);
bGroup.add(upButton);
bGroup.add(downButton);
/*ButtonGroup此類用于為一組按鈕創(chuàng)建一個(gè)多斥(multiple-exclusion)作用域。
使用相同的 ButtonGroup 對象創(chuàng)建一組按鈕意味著“開啟”其中一個(gè)按鈕時(shí),將關(guān)閉組中的其他所有按鈕。*/
/*JRadioButton此類實(shí)現(xiàn)一個(gè)單選按鈕,此按鈕項(xiàng)可被選擇或取消選擇,并可為用戶顯示其狀態(tài)。
與 ButtonGroup 對象配合使用可創(chuàng)建一組按鈕,一次只能選擇其中的一個(gè)按鈕。
(創(chuàng)建一個(gè) ButtonGroup 對象并用其 add 方法將 JRadioButton 對象包含在此組中。)*/
JButton cancel=new JButton("取消");
cancel.setActionCommand("findcancel");
cancel.addActionListener(menuhandler);
//創(chuàng)建查找對話框的界面
JPanel panel1=new JPanel();
JPanel panel2=new JPanel();
JPanel panel3=new JPanel();
JPanel directionPanel=new JPanel();
directionPanel.setBorder(BorderFactory.createTitledBorder("方向"));
//設(shè)置directionPanel組件的邊框;
//BorderFactory.createTitledBorder(String title)創(chuàng)建一個(gè)新標(biāo)題邊框,使用默認(rèn)邊框(浮雕化)、默認(rèn)文本位置(位于頂線上)、默認(rèn)調(diào)整 (leading) 以及由當(dāng)前外觀確定的默認(rèn)字體和文本顏色,并指定了標(biāo)題文本。
directionPanel.add(upButton);
directionPanel.add(downButton);
panel1.setLayout(new GridLayout(2,1));
panel1.add(findNextButton);
panel1.add(cancel);
panel2.add(findContentLabel);
panel2.add(findText);
panel2.add(panel1);
panel3.add(matchCheckBox);
panel3.add(directionPanel);
con.add(panel2);
con.add(panel3);
findDialog.setSize(410,180);
findDialog.setResizable(false);//不可調(diào)整大小
findDialog.setLocation(230,280);
findDialog.setVisible(true);
}
public void replacewindow(){
//替換窗口
replaceDialog=new JDialog(this,"替換",false);//false時(shí)允許其他窗口同時(shí)處于激活狀態(tài)(即無模式)
Container con=replaceDialog.getContentPane();//返回此對話框的contentPane對象
con.setLayout(new FlowLayout(FlowLayout.CENTER));
JLabel findContentLabel=new JLabel("查找內(nèi)容(N):");
findText1=new JTextField(15);
JButton findNextButton=new JButton("查找下一個(gè)(F):");
findNextButton.setActionCommand("findnext1");
findNextButton.addActionListener(menuhandler);
JLabel replaceLabel=new JLabel("替換為(P):");
replaceText=new JTextField(15);
JButton replaceButton=new JButton("替換(R)");
replaceButton.setActionCommand("replace");
replaceButton.addActionListener(menuhandler);
JButton replaceAllButton=new JButton("全部替換(A)");
replaceAllButton.setActionCommand("replaceall");
replaceAllButton.addActionListener(menuhandler);
JButton cancel=new JButton("取消");
cancel.setActionCommand("replacecancel");
cancel.addActionListener(menuhandler);
matchCheckBox1=new JCheckBox("區(qū)分大小寫(C)");
ButtonGroup bGroup=new ButtonGroup();
upButton1=new JRadioButton("向上(U)");
downButton1=new JRadioButton("向下(U)");
downButton1.setSelected(true);
bGroup.add(upButton1);
bGroup.add(downButton1);
//創(chuàng)建替換對話框的界面
JPanel directionPanel=new JPanel();
directionPanel.setBorder(BorderFactory.createTitledBorder("方向"));
//設(shè)置directionPanel組件的邊框;
//BorderFactory.createTitledBorder(String title)創(chuàng)建一個(gè)新標(biāo)題邊框,使用默認(rèn)邊框(浮雕化)、默認(rèn)文本位置(位于頂線上)、默認(rèn)調(diào)整 (leading) 以及由當(dāng)前外觀確定的默認(rèn)字體和文本顏色,并指定了標(biāo)題文本。
directionPanel.add(upButton1);
directionPanel.add(downButton1);
JPanel panel1=new JPanel();
JPanel panel2=new JPanel();
JPanel panel3=new JPanel();
JPanel panel4=new JPanel();
panel4.setLayout(new GridLayout(2,1));
panel1.add(findContentLabel);
panel1.add(findText1);
panel1.add(findNextButton);
panel4.add(replaceButton);
panel4.add(replaceAllButton);
panel2.add(replaceLabel);
panel2.add(replaceText);
panel2.add(panel4);
panel3.add(matchCheckBox1);
panel3.add(directionPanel);
panel3.add(cancel);
con.add(panel1);
con.add(panel2);
con.add(panel3);
replaceDialog.setSize(420,220);
replaceDialog.setResizable(false);//不可調(diào)整大小
replaceDialog.setLocation(230,280);
replaceDialog.setVisible(true);
}
public void gotowindow(){
//轉(zhuǎn)到窗口
gotoDialog = new JDialog(this,"轉(zhuǎn)到指定行",false);
Container con = gotoDialog.getContentPane();
JButton gotobutton = new JButton("轉(zhuǎn)到");
gotobutton.setActionCommand("goto");
gotobutton.addActionListener(menuhandler);
JButton cancel = new JButton("取消");
cancel.setActionCommand("gotocancel");
cancel.addActionListener(menuhandler);
gotoDialog.setLayout(null);
JLabel linenumber = new JLabel("行號(L):");
field = new JTextField();
linenumber.setBounds(10, 12, 400, 30);
field.setBounds(10, 42, 350, 28);
gotobutton.setBounds(180, 84, 80, 28);
gotobutton.setContentAreaFilled(false);
cancel.setBounds(270, 84, 80, 28);
cancel.setContentAreaFilled(false);
gotoDialog.setBounds(200, 200, 400, 160);
gotoDialog.setResizable(false);
con.add(linenumber);
con.add(field);
con.add(gotobutton);
con.add(cancel);
gotoDialog.setVisible(true);
try{
int pos = jtext.getCaretPosition();
int row = jtext.getLineOfOffset(pos)+1;//將組件文本中的偏移量轉(zhuǎn)換為行號
field.setText(String.valueOf(row));
field.requestFocus();
field.selectAll();
}catch(BadLocationException badlocation){
System.out.println("bad location");
}
}
public class MenuHandler implements ActionListener {
@Override
public void actionPerformed(ActionEvent e){
String actionCommand = e.getActionCommand();
//處理新建操作
if("newfile".equals(actionCommand)){
int select=showSaveDialog();
if (select == JOptionPane.CANCEL_OPTION||select == JOptionPane.CLOSED_OPTION)// 取消按鈕,則返回
return;
else{
jtext.replaceRange("",0,jtext.getText().length());
setTitle("無標(biāo)題 - 記事本");
filepath=null;
undom.discardAllEdits(); //撤消所有的"撤消"操作
edit_undo.setEnabled(false);
}
}
//處理新窗口操作
if("newwindow".equals(actionCommand)){
new MyNotepad().init();
}
//處理打開操作
if("open".equals(actionCommand)){
// 是否保存對原文件修改
int select = showSaveDialog();
if (select == JOptionPane.CANCEL_OPTION||select == JOptionPane.CLOSED_OPTION)// 取消、關(guān)閉按鈕,則返回
return;
// 彈出一個(gè) "Open File" 文件選擇器對話框
select = jfilechoose.showOpenDialog(MyNotepad.this);
// 選擇打開文件,則讀寫文件
if (select == JFileChooser.APPROVE_OPTION) {
jtext.setText(readFile());// 寫入文本框
jtext.setCaretPosition(0);// 定位光標(biāo)至行首
undom.discardAllEdits(); //撤消所有的"撤消"操作
edit_undo.setEnabled(false);
}
}
//處理保存操作
if("save".equals(actionCommand)){
showSaveDialog();//調(diào)用文件是否保存方法
setTitle(name + " - 記事本");
}
//處理另存為操作
if("saveas".equals(actionCommand)){
createFile();
setTitle(name + " - 記事本");
}
//處理退出操作
if("exit".equals(actionCommand)){
int select = showSaveDialog();
if (select != JOptionPane.CANCEL_OPTION &&
? ? ? ? ? ? ? ? select != JOptionPane.CLOSED_OPTION)
dispose();//釋放窗體,dispose()
}
//處理撤銷操作
if("undo".equals(actionCommand)){
if(undom.canUndo())
undom.undo();
else
edit_undo.setEnabled(false);
}
//處理剪切操作
if("cut".equals(actionCommand)){
jtext.requestFocus();
String text=jtext.getSelectedText();
//StringSelection實(shí)現(xiàn)的所有接口ClipboardOwner,Transferable
StringSelection selection=new StringSelection(text);
clipBoard.setContents(selection,null);
jtext.replaceRange("",jtext.getSelectionStart(),jtext.getSelectionEnd());
checkMenuItemEnabled();//設(shè)置剪切,復(fù)制,粘帖,刪除功能的可用性
}
//處理復(fù)制操作
if("copy".equals(actionCommand)){
jtext.requestFocus();
String text=jtext.getSelectedText();
StringSelection selection=new StringSelection(text);
clipBoard.setContents(selection,null);
checkMenuItemEnabled();//設(shè)置剪切,復(fù)制,粘帖,刪除功能的可用性
}
//處理粘貼操作
if("stickup".equals(actionCommand)){
jtext.requestFocus();
//只有一種類型的數(shù)據(jù)可以復(fù)制到剪貼板或者從剪貼板中取出,即Transferable對象。
Transferable contents=clipBoard.getContents(this);
if(contents==null)
return;
String text="";
try
{
//getTransferData返回一個(gè)對象,該對象表示將要被傳輸?shù)臄?shù)據(jù)。返回對象的類是由該 flavor 的表示類定義的
//DataFlavor.stringFlavor:The representing a Java Unicode String class
text=(String)contents.getTransferData(DataFlavor.stringFlavor);
}
catch (Exception exception)
{
}
jtext.replaceRange(text,jtext.getSelectionStart(),jtext.getSelectionEnd());
checkMenuItemEnabled();
}
//處理刪除操作
if("delete".equals(actionCommand)){
jtext.requestFocus();
jtext.replaceRange("",jtext.getSelectionStart(),jtext.getSelectionEnd());
checkMenuItemEnabled(); //設(shè)置剪切、復(fù)制、粘貼、刪除等功能的可用性
}
//處理查找窗口打開操作
if("findwindow".equals(actionCommand)){
jtext.requestFocus();
findwindow();
}
//處理查找下一個(gè)按鈕操作
if("findnext".equals(actionCommand)||"findnext1".equals(actionCommand)){
int k=0;
String str1,str2,str3,str4,strA,strB;
Boolean up,down,checkbox;
str1=jtext.getText();
if("findnext".equals(actionCommand)){//查找窗口的查找下一個(gè)按鈕事件監(jiān)聽處理
str2=findText.getText();//查找窗口的查找內(nèi)容
up=upButton.isSelected();
down=downButton.isSelected();
checkbox=matchCheckBox.isSelected();
}
else{//替換窗口的查找下一個(gè)按鈕事件監(jiān)聽處理
str2=findText1.getText();//替換窗口的查找內(nèi)容
up=upButton1.isSelected();
down=downButton1.isSelected();
checkbox=matchCheckBox1.isSelected();
}
str3=str1.toUpperCase();
str4=str2.toUpperCase();
if(checkbox)//區(qū)分大小寫的JCheckBox是否被選中
{ strA=str1;
strB=str2;
}
else//不區(qū)分大小寫,此時(shí)把所選內(nèi)容全部化成大寫(或小寫),以便于查找
{ strA=str3;
strB=str4;
}
if(up)
{
if(jtext.getSelectedText()==null)
k=strA.lastIndexOf(strB,jtext.getCaretPosition()-1);//光標(biāo)與其后一個(gè)字符位置下標(biāo)相同
else
k=strA.lastIndexOf(strB, jtext.getCaretPosition()-strB.length()-1);
if(k>-1)//查找內(nèi)容存在
{
jtext.setCaretPosition(k);//設(shè)置光標(biāo)位置
jtext.select(k,k+strB.length());//選中內(nèi)容,此時(shí)光標(biāo)位置后移了strB.length()長度
}
else
JOptionPane.showMessageDialog(null,"找不到\""+str2+"\"","記事本",JOptionPane.INFORMATION_MESSAGE);
}
else if(down)
{
k=strA.indexOf(strB,jtext.getCaretPosition());
if(k>-1)
{
jtext.setCaretPosition(k);
jtext.select(k,k+strB.length());
}
else
JOptionPane.showMessageDialog(null,"找不到\""+str2+"\"","記事本",JOptionPane.INFORMATION_MESSAGE);
}
}
//處理取消查找操作
if("findcancel".equals(actionCommand)){
findDialog.dispose();//關(guān)閉查找窗口
}
//處理快速查找下一個(gè)操作
if("fastfindnext".equals(actionCommand)){
int k=0;
String str1,str2;
str1=jtext.getText();
if(jtext.getSelectedText()==null){
JOptionPane.showMessageDialog(null,"請用光標(biāo)從左向右選中待查找內(nèi)容","提醒",JOptionPane.INFORMATION_MESSAGE);
return;
}
str2=jtext.getSelectedText();
k=str1.indexOf(str2,jtext.getCaretPosition());
if(k>-1)
{
jtext.setCaretPosition(k);
jtext.select(k,k+str2.length());
}
else
JOptionPane.showMessageDialog(null,"找不到\""+str2+"\"","記事本",JOptionPane.INFORMATION_MESSAGE);
}
//處理快速查找上一個(gè)操作
if("fastfindpre".equals(actionCommand)){
int k=0;
String str1,str2;
str1=jtext.getText();
if(jtext.getSelectedText()==null){
JOptionPane.showMessageDialog(null,"請用光標(biāo)從左向右選中待查找內(nèi)容","提醒",JOptionPane.INFORMATION_MESSAGE);
return;
}
str2=jtext.getSelectedText();
k=str1.lastIndexOf(str2, jtext.getCaretPosition()-str2.length()-1);
if(k>-1)//查找內(nèi)容存在
{
jtext.setCaretPosition(k);//設(shè)置光標(biāo)位置
jtext.select(k,k+str2.length());//選中內(nèi)容,此時(shí)光標(biāo)位置后移了strB.length()長度
}
else
JOptionPane.showMessageDialog(null,"找不到\""+str2+"\"","記事本",JOptionPane.INFORMATION_MESSAGE);
}
//處理替換窗口打開操作
if("replacewindow".equals(actionCommand)){
jtext.requestFocus();
replacewindow();
}
//處理替換操作
if("replace".equals(actionCommand)){
if(jtext.getSelectedText()!=null&&
jtext.getSelectedText().equals(findText1.getText()))
jtext.replaceSelection(replaceText.getText());
int k=0;
String str1,str2,strA,strB;
boolean up,down,checkbox;
str1=jtext.getText();
str2=findText1.getText();
up=upButton1.isSelected();
down=downButton1.isSelected();
checkbox=matchCheckBox1.isSelected();
if(checkbox){
strA=str1;
strB=str2;
}
else{
strA=str1.toUpperCase();
strB=str2.toUpperCase();
}
if(down){
k=strA.indexOf(strB,jtext.getCaretPosition());
if(k>-1)
{
jtext.setCaretPosition(k);
jtext.select(k,k+strB.length());
}
else
JOptionPane.showMessageDialog(null,"找不到\""+str2+"\"","記事本",JOptionPane.INFORMATION_MESSAGE);
}
if(up){
if(jtext.getSelectedText()==null)
k=strA.lastIndexOf(strB,jtext.getCaretPosition()-1);
else
k=strA.lastIndexOf(strB, jtext.getCaretPosition()-strB.length()-1);
if(k>-1)//查找內(nèi)容存在
{
jtext.setCaretPosition(k);//設(shè)置光標(biāo)位置
jtext.select(k,k+strB.length());//選中內(nèi)容,此時(shí)光標(biāo)位置后移了strB.length()長度
}
else
JOptionPane.showMessageDialog(null,"找不到\""+str2+"\"","記事本",JOptionPane.INFORMATION_MESSAGE);
}
}
//處理替換全部操作
if("replaceall".equals(actionCommand)){
// jtext.setCaretPosition(0); //將光標(biāo)放到編輯區(qū)開頭
String str1,str2,strA,strB;
boolean up,down,checkbox;
str1=jtext.getText();
str2=findText1.getText();
up=upButton1.isSelected();
down=downButton1.isSelected();
checkbox=matchCheckBox1.isSelected();
if(checkbox)//區(qū)分大小寫
{ strA=str1;
strB=str2;
}
else//不區(qū)分大小寫,此時(shí)把所選內(nèi)容全部化成大寫,以便于查找
{ strA=str1.toUpperCase();
strB=str2.toUpperCase();
}
int k=0,replaceCount=0;
if(findText1.getText().length()==0)
{ JOptionPane.showMessageDialog(replaceDialog,"請?zhí)顚懖檎覂?nèi)容!","提示",JOptionPane.WARNING_MESSAGE);
findText1.requestFocus(true);
return;
}
while(k>-1)//當(dāng)文本中有內(nèi)容被選中時(shí)(k>-1被選中)進(jìn)行替換,否則不進(jìn)行while循環(huán)
{
if(up)
{
if(jtext.getSelectedText()==null)
k=strA.lastIndexOf(strB,jtext.getCaretPosition()-1);
else
k=strA.lastIndexOf(strB,jtext.getCaretPosition()-strB.length()-1);
if(k>-1)
{
jtext.setCaretPosition(k);
jtext.select(k,k+strB.length());
}
else
{ if(replaceCount==0)
JOptionPane.showMessageDialog(replaceDialog, "找不到\""+str2+"\"", "記事本",JOptionPane.INFORMATION_MESSAGE);
else
JOptionPane.showMessageDialog(replaceDialog,"成功替換了"+replaceCount+"個(gè)匹配內(nèi)容!","替換成功",JOptionPane.INFORMATION_MESSAGE);
}
}
else if(down)
{
k=strA.indexOf(strB,jtext.getCaretPosition());
if(k>-1)
{
jtext.setCaretPosition(k);
jtext.select(k,k+strB.length());
}
else
{ if(replaceCount==0)
JOptionPane.showMessageDialog(replaceDialog, "找不到\""+str2+"\"", "記事本",JOptionPane.INFORMATION_MESSAGE);
else
JOptionPane.showMessageDialog(replaceDialog,"成功替換了"+replaceCount+"個(gè)匹配內(nèi)容!","替換成功",JOptionPane.INFORMATION_MESSAGE);
}
}
if(jtext.getSelectedText()!=null && jtext.getSelectedText().equals(findText1.getText()))
{ jtext.replaceSelection(replaceText.getText());
replaceCount++;
}
}//while循環(huán)結(jié)束
}
//處理取消替換操作
if("replacecancel".equals(actionCommand)){
replaceDialog.dispose();
}
//處理打開轉(zhuǎn)到窗口操作
if("gotowindow".equals(actionCommand)){
jtext.requestFocus();
gotowindow();
}
//處理轉(zhuǎn)到按鈕點(diǎn)擊事件
if("goto".equals(actionCommand)){
int row = jtext.getLineCount();// 確定行數(shù)
String str[] = jtext.getText().split("\n");
int count = 0;
try {
count = Integer.parseInt(field.getText().trim());//trim:去頭尾空白字符 parseInt:字符轉(zhuǎn)數(shù)字
} catch (Exception e2) {
JOptionPane.showMessageDialog(null, "請輸入要轉(zhuǎn)到的行數(shù)!");
}
if (count <= row) {
int sum = 0;
for (int i = 0; i < count - 1; i++) {
sum += str[i].length() + 1;
}
jtext.setCaretPosition(sum);
} else {
JOptionPane.showMessageDialog(null, "行數(shù)超過了總行數(shù)!");
}
gotoDialog.dispose();
}
//處理轉(zhuǎn)到界面取消按鈕點(diǎn)擊事件
if("gotocancel".equals(actionCommand)){
gotoDialog.dispose();
}
//處理全選操作
if("selectall".equals(actionCommand)){
jtext.selectAll();
}
//時(shí)間/日期點(diǎn)擊事件處理
if("time".equals(actionCommand)){
Date date = new Date();// 獲得當(dāng)前日期
/*
* 日期格式化SimpleDateFormat h小時(shí),m分鐘 y年份 M月份 d天數(shù)
*/
SimpleDateFormat dateformat = new SimpleDateFormat("hh:mm yyyy-MM-dd");
jtext.append(dateformat.format(date));// 追加到文本
}
//自動換行按鈕點(diǎn)擊處理
if("linewrap".equals(actionCommand)){
if(format_linewrap.getState())
jtext.setLineWrap(true);//自動換行
else
jtext.setLineWrap(false);//不自動換行
}
//字體變大
if("sizetobig".equals(actionCommand)){
String name = jtext.getFont().getFontName();// 返回字體外觀
int style = jtext.getFont().getStyle();// 獲得字體的樣式
int size = jtext.getFont().getSize();// 獲得字體的大小
jtext.setFont(new Font(name, style, size + 1));// 設(shè)置字體大小+1
}
//字體變小
if("sizetosmall".equals(actionCommand)){
String name = jtext.getFont().getFontName();
int style = jtext.getFont().getStyle();
int size = jtext.getFont().getSize();
jtext.setFont(new Font(name, style, size - 1));// 設(shè)置字體大小-1
}
//恢復(fù)默認(rèn)字體大小
if("sourcesize".equals(actionCommand)){
jtext.setFont(new Font("宋體", Font.PLAIN, 14));
}
}
}
// 讀取文件
private String readFile() {
// 聲明緩沖字符流變量
BufferedReader br = null;
//BufferedReader是從緩沖區(qū)之中讀取內(nèi)容
StringBuilder sb = null;
try {
br = new BufferedReader(new FileReader(jfilechoose.getSelectedFile()));
sb = new StringBuilder();//構(gòu)造一個(gè)字符串構(gòu)建器,其中不包含任何字符,初始容量為16個(gè)字符。
String str;
int count = 0;//控制添加換行符,與原文保持一致
while ((str = br.readLine()) != null) {//讀取一行內(nèi)容,直到換行符,但不讀取換行符
if (count == 0){
sb.append(str);
count=1;
}
else
sb.append("\n" + str);// 添加換行
}
} catch (FileNotFoundException e1) {
// 彈出“文件未找到”對話框,返回null
JOptionPane.showMessageDialog(null, "未找到該文件!");
return null;
} catch (IOException e1) {
// 彈出“文件讀取異?!睂υ捒颍祷豱ull
JOptionPane.showMessageDialog(null, "文件讀取異常");
return null;
} finally {
// 關(guān)閉字符流
if (br != null)
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
File file = jfilechoose.getSelectedFile();
name = file.getName();
filepath = file.getAbsolutePath();
setTitle(name + " - 記事本");//設(shè)置文件名
return sb.toString();
}
// 保存對話框
private int showSaveDialog() {
int select = 0;
// 判斷文件是否已存在
if (filepath == null) {
select = JOptionPane.showConfirmDialog(MyNotepad.this, "是否保存修改?");
if (select == JOptionPane.YES_OPTION)
createFile();//文件不存在,則創(chuàng)建文件
}
else {
if (!isSaved()){// 文件未保存
select = JOptionPane.showConfirmDialog(MyNotepad.this, "是否保存修改?");
if(select == JOptionPane.YES_OPTION)
saveFile(jfilechoose.getSelectedFile());
}
}
return select;// 返回選項(xiàng)
}
// 創(chuàng)建新文件
private void createFile() {
// String name = null;
File file = null;
// 選擇保存或取消
if (jfilechoose.showSaveDialog(MyNotepad.this) == JFileChooser.APPROVE_OPTION)
file = jfilechoose.getSelectedFile();// 獲取選中的文件
else
return;
name = jfilechoose.getName(file);// 獲取輸入的文件名
filepath = file.getAbsolutePath();//獲取文件的絕對路徑
if (file.exists()) { // 若選擇已有文件----詢問是否要覆蓋
int select = JOptionPane.showConfirmDialog(null, "該文件已存在,是否覆蓋原文件", "確認(rèn)", JOptionPane.YES_NO_OPTION);
if (select == JOptionPane.YES_OPTION)
saveFile(file);
else
jfilechoose.showSaveDialog(MyNotepad.this);// 重新選擇
}
else//文件不存在,則直接保存
saveFile(file);
}
// 判斷文件是否保存
private Boolean isSaved() {
// 比較內(nèi)容
if (jtext.getText().equals(readFile()))
return true;
return false;
}
// 保存文件
private void saveFile(File file) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
bw.write(jtext.getText());//寫入文件
bw.flush();
} catch (FileNotFoundException e1) {
JOptionPane.showMessageDialog(MyNotepad.this, "文件保存出錯(cuò)" + e1.getMessage());
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
} catch (IOException e1) {
}
}
}
//設(shè)置菜單項(xiàng)的可用性:剪切,復(fù)制,粘帖,刪除功能
private void checkMenuItemEnabled()
{ String selectText=jtext.getSelectedText();
if(selectText==null)
{ edit_cut.setEnabled(false);
edit_copy.setEnabled(false);
edit_delete.setEnabled(false);
}
else
{ edit_cut.setEnabled(true);
edit_copy.setEnabled(true);
edit_delete.setEnabled(true);
}
//粘帖功能可用性判斷
Transferable contents=clipBoard.getContents(MyNotepad.this);
if(contents==null)
{ edit_paste.setEnabled(false);
}
else
{ edit_paste.setEnabled(true);
}
}//方法checkMenuItemEnabled()結(jié)束
//實(shí)現(xiàn)DocumentListener接口中的方法(與撤銷操作有關(guān)),文檔發(fā)生變化時(shí)就能觸發(fā)DocumentEvent事件
public void removeUpdate(DocumentEvent e)//文檔被移除
{ edit_undo.setEnabled(true);
}
public void insertUpdate(DocumentEvent e)//文檔被插入
{ edit_undo.setEnabled(true);
}
public void changedUpdate(DocumentEvent e)//文檔被改變
{ edit_undo.setEnabled(true);
}
//實(shí)現(xiàn)接口UndoableEditListener的類UndoHandler(與撤銷操作有關(guān))
class UndoHandler implements UndoableEditListener
{ public void undoableEditHappened(UndoableEditEvent uee)
{ undom.addEdit(uee.getEdit());
}
}
}
到了這里,關(guān)于java記事本源代碼的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!