java编写的记事本源代码
我用java编写的记事本代码,分享给大家
backcolor.add(white); backcolor.addSeparator();
backcolor.add(pink); backcolor.addSeparator();
backcolor.add(morecolor);
JMenuItem red=new JMenuItem("红色");//","橙","黄","","青","蓝","紫","黑","灰","白","粉红"
JMenuItem green=new JMenuItem("绿色");
JMenuItem yellow=new JMenuItem("黄色");
clear.setFont(a); clear.setForeground(Color.MAGENTA);
paste.setFont(a); paste.setForeground(Color.MAGENTA);
cut.setFont(a); cut.setForeground(Color.MAGENTA);
JMenuItem black=new JMenuItem("黑色");
JMenuItem gray=new JMenuItem("灰色");
JMenuItem white=new JMenuItem("白色");
JMenuItem pink=new JMenuItem("粉红");
基于Swing的Mini记事本源程序
Mini 记事本源程序 目录 1.程序入口 Notepad.java ........................................................................................................ 1 2.工具栏按钮类 ToolBarButton.java ........................................................................................ 1 3.字体对话框类 JFontChooser.java ......................................................................................... 2 4.记事本核心类 FormMain.java ............................................................................................... 6 5.在项目中创建属性文件 notepad.properties ................................................................. 21 说明:本程序是学习 Swing、文件流的练习程序,部分代码没有 没有实现,发现后自己补充;如果测试出 bug,自行改正。
1.程序入口 Notepad.java package notepad; public class NotePad { public static void main(String[] args) { FormMain win = new FormMain("Mini记事本"); win.setVisible(true); } } 2.工具栏按钮类 ToolBarButton.java package notepad; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; /** * @author 孙丰伟 E‐mail: sunfengweimail@ * @version 创建时间:May 3, 2008 12:49:50 PM * @see */ public class ToolBarButton extends JButton { public ToolBarButton(Icon icon) { super(icon); setVerticalTextPosition(BOTTOM); setHorizontalTextPosition(CENTER); } public ToolBarButton(String imageFile) { this(new ImageIcon(imageFile)); // this 调用构造方法 } } // end class ToolBarButton 3.字体对话框类 JFontChooser.java package notepad; import java.awt.BorderLayout; import java.awt.Container; import java.awt.FlowLayout; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import javax.swing.*; /****************************************** * 类 名: JFontChooser * 作 者:孙丰伟 E‐mail: sunfengweimail@ * 时 间:2008‐4‐24 * 描 述:实现简单的字体设置 ******************************************/ public class JFontChooser extends JDialog implements ActionListener { private Font font; private Container contentPane; private JButton btnOK,btnCancel; private JComboBox comboFont,comboSize,comboStyle; private JTextField txtFontName,txtFontSize,txtFontStyle; private Box baseBoxV,fontBox,boxV1,boxV2,boxV3; private JPanel btnPanel,labPanel; private JLabel labFont,labStyle,labSize,labDemo; public JFontChooser(JFrame frame,String title,boolean flag,Font font) { super(frame,title,flag); this.font=font; this.initForm(); } private void initForm() { this.contentPane = this.getContentPane(); // // 取系统中支持字体 // GraphicsEnvironment gl = GraphicsEnvironment.getLocalGraphicsEnvironment(); String[] fontName = gl.getAvailableFontFamilyNames(); comboFont=new JComboBox(fontName); labFont=new JLabel("字体:"); labStyle=new JLabel("样式:"); labSize=new JLabel("大小:"); txtFontName=new JTextField(font.getFamily()); txtFontSize=new JTextField(String.valueOf(font.getSize())); txtFontStyle=new JTextField(String.valueOf(font.getStyle())); labDemo=new JLabel("Hello,这是字体样例!"); labDemo.setFont(font); labDemo.setHorizontalAlignment(JLabel.LEFT); String[] fontStyle = { "常规", "粗体", "斜体"}; comboStyle=new JComboBox(fontStyle); //大小 comboSize=new JComboBox(); for(int size=8;size<=72;size++) { comboSize.addItem(size); } // // 为组合框设置事件 // HandleItemListener itemListener=new HandleItemListener(); comboFont.addItemListener(itemListener); comboStyle.addItemListener(itemListener); comboSize.addItemListener(itemListener); boxV1=Box.createVerticalBox(); boxV1.add(labFont); boxV1.add(txtFontName); boxV1.add(comboFont); fontBox=Box.createHorizontalBox(); fontBox.add(boxV1); boxV2=Box.createVerticalBox(); boxV2.add(labStyle); boxV2.add(txtFontStyle); boxV2.add(comboStyle); boxV3=Box.createVerticalBox(); boxV3.add(labSize); boxV3.add(txtFontSize); boxV3.add(comboSize); fontBox.add(boxV2); fontBox.add(boxV3); baseBoxV=Box.createVerticalBox(); baseBoxV.add(fontBox); baseBoxV.add(Box.createVerticalStrut(20)); labPanel=new JPanel(); FlowLayout flow=new FlowLayout(); flow.setAlignment(FlowLayout.LEFT); labPanel.setLayout(flow); labPanel.add(labDemo); baseBoxV.add(labPanel); this.contentPane.add(baseBoxV); btnPanel=new JPanel(); btnOK=new JButton("确定"); btnCancel=new JButton("取消"); btnOK.addActionListener(this); btnCancel.addActionListener(this); btnPanel.add(btnOK); btnPanel.add(btnCancel); this.contentPane.add(btnPanel, BorderLayout.SOUTH); this.setLocationRelativeTo(null); this.setResizable(false); this.setSize(450, 200); this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); this.setVisible(true); } class HandleItemListener implements ItemListener { @Override public void itemStateChanged(ItemEvent e) { // TODO Auto‐generated method stub if(e.getSource()==comboFont) { txtFontName.setText(comboFont.getSelectedItem().toString()); } if(e.getSource()==comboStyle) { txtFontStyle.setText(comboStyle.getSelectedItem().toString()); } if(e.getSource()==comboSize) { txtFontSize.setText(comboSize.getSelectedItem().toString()); } //setTitle(String.valueOf(comboStyle.getSelectedIndex())); font=font=new Font(txtFontName.getText(),comboStyle.getSelectedIndex(),Integer.parseInt(txtFontSize.getT ext())); labDemo.setFont(font); } } @Override public void actionPerformed(ActionEvent e) { // TODO Auto‐generated method stub System.out.println(comboFont.getSelectedItem().toString()); System.out.println(Integer.parseInt(comboSize.getSelectedItem().toString())); if(e.getSource()==btnOK) { //font=new Font(comboFont.getSelectedItem().toString(),comboSize.getSelectedIndex(),Integer.parseInt( comboSize.getSelectedItem().toString())); this.dispose(); } else { font=null; this.dispose(); } } public static void main(String[] args) { Font font=new Font("新宋体",Font.ITALIC,20); JFontChooser fontChooser=new JFontChooser(null,"设置字体",true,font); } public Font getNoteFont() { return font; } } 4.记事本核心类 FormMain.java /****************************************** * 文件名: FormMain.java * 作 者:孙丰伟 * 时 间:2008‐4‐24 * 描 述:保存 FormMain 类,是记事本程序的核心类 * 测 试:本程序使用 Elipse 编写,JDK1.6 测试运行 ******************************************/ package notepad; import java.awt.*; import javax.swing.*; import javax.swing.border.Border; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.UndoableEditEvent; import javax.swing.event.UndoableEditListener; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import javax.swing.undo.UndoManager; import javax.swing.filechooser.*; import java.awt.event.*; import java.io.*; import java.util.Properties; /** * * 枚举类型: 用于标识视图菜单 * */ enum VIEW{ //视图菜单 STATUS, //状态栏 FOREGROUND, //前景颜色 BACKGROUND //背景颜色 } /** * * 枚举类型: 用于标识文件菜单 * */ enum FILE{ //用于文件菜单 NEW, //新建文件 OPEN, //打开文件 SAVE, //保存文件 SAVEAS, //另存为 EXIT //退出 } /** * * 枚举类型: 用于标识编辑菜单 * */ enum EDIT //用于编辑菜单 { COPY, //复制 CUT, //剪切 PASTE, //粘贴 DELETE, //删除 UNDO, //撤销 REDO //恢复 } /****************************************** * 类 名: FormMain * 作 者:孙丰伟 * 时 间:2008‐4‐24 * 描 述:记事本程序 * 内部类: * 1. TxtNoteActionListener:编辑菜单监听 * 2. FileActionListener:文件菜单监听 * 3. ViewActionListener:视图菜单监听 * 方 法: * 1. initialize() 初始窗体 * 2. saveFile() 保存文件 * 3. openFile() 打开文件 ******************************************/ class FormMain extends JFrame { private Container contentPane; // 内容面板 private JMenuBar mnuBar; // 菜单容器 private JMenu mnuFile, mnuEdit,mnuFormat, mnuView; // 主菜单 private JMenuItem mnuFileOpen, mnuFileSaveAs, mnuFileSave, mnuFileNew, mnuFileExit; //文件菜单项 private JMenuItem mnuEditCut, mnuEditPaste, mnuEditCopy, mnuEditDelete,mnuEditUndo, mnuEditRedo; //编辑菜单项 private JMenuItem mnuPCut, mnuPPaste, mnuPCopy, mnuPDelete; //编辑菜单项 ____右键弹出菜单 private JCheckBoxMenuItem mnuViewStatus; // 带复选的菜单, 控制状态栏是否出现 private JMenuItem mnuViewForeColor, mnuViewBackColor; //前景与背景颜 色项 private JMenuItem mnuFormatFont; // 字体菜单项 private JPopupMenu popupMenu; // 右键菜单 private JToolBar toolBar; // 工具栏 private ToolBarButton toolNew, toolOpen, toolSave, toolExit; //工具栏按钮 private JTextArea txtNote; // 记事本文本域 private JLabel labStatus; // 状态栏 private final UndoManager undo = new UndoManager(); // 用于撤销 private JFileChooser fileChooser; // 文件对话框 private boolean isChange = false; // 文件内容是否改变 private String fileName = null; // 保存文件名 private Font font; // 文本域字体 private FileNameExtensionFilter filter = new FileNameExtensionFilter("文本文件", "txt"); //设置文件过滤器 private Properties properties; FormMain(String title) { super(title); initialize(); } private void initialize() { /* 程序窗口居中 */ this.setLocationRelativeTo(this); this.setSize(600, 500); this.setExtendedState(JFrame.MAXIMIZED_BOTH); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // JTextArea 事件监听器 TxtNoteActionListener txtListener = new TxtNoteActionListener(); // 文件监听器 FileActionListener fileListener = new FileActionListener(); // // 设置工具栏 // toolBar = new JToolBar("记事本"); toolSave = new ToolBarButton(new ImageIcon("images\\saveHS.GIF")); toolOpen = new ToolBarButton(new ImageIcon("images\\OPENFOLD.GIF")); toolSave.setText("保存文件"); toolOpen.setText("打开文件"); toolSave.setActionCommand("保存"); toolOpen.setActionCommand("打开"); toolSave.addActionListener(fileListener); toolOpen.addActionListener(fileListener); toolBar.add(toolOpen); toolBar.addSeparator(); toolBar.add(toolSave); toolBar.addSeparator(); Border toolBorder = BorderFactory.createBevelBorder(1); toolBar.setBorder(toolBorder); // ‐‐‐‐‐设置工具栏结束‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ // // 设置状态栏 // labStatus = new JLabel("作者:孙丰伟"); labStatus.setBorder(BorderFactory.createBevelBorder(1)); this.add(bStatus, BorderLayout.SOUTH); // // 设置菜单 // JMenuBar mnuBar = new JMenuBar(); this.setJMenuBar(mnuBar); // // 文件菜单 // mnuFile = new JMenu("文件(F)"); Font mnuFont = new Font("新宋体", 0, 12); mnuFile.setFont(mnuFont); mnuFile.setMnemonic('F'); mnuFileNew = new JMenuItem("新建(N)"); mnuFileOpen = new JMenuItem("打开(O)"); mnuFileSave = new JMenuItem("保存(S)"); mnuFileSaveAs = new JMenuItem("另存为(A)"); mnuFileExit = new JMenuItem("退出(E)"); mnuFileNew.setMnemonic('N'); mnuFileOpen.setMnemonic('O'); mnuFileSave.setMnemonic('S'); mnuFileExit.setMnemonic('E'); mnuFileSaveAs.setMnemonic('A'); this.mnuFileNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK)); this.mnuFileOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK)); this.mnuFileSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK)); mnuFileNew.setActionCommand(FILE.NEW.toString()); mnuFileOpen.setActionCommand(FILE.OPEN.toString()); mnuFileSave.setActionCommand(FILE.SAVE.toString()); mnuFileSaveAs.setActionCommand(FILE.SAVEAS.toString()); mnuFileExit.setActionCommand(FILE.EXIT.toString()); mnuFileNew.addActionListener(fileListener); mnuFileOpen.addActionListener(fileListener); mnuFileSave.addActionListener(fileListener); mnuFileSaveAs.addActionListener(fileListener); mnuFileExit.addActionListener(fileListener); mnuFile.add(mnuFileNew); mnuFile.add(mnuFileOpen); mnuFile.add(mnuFileSave); mnuFile.addSeparator(); mnuFile.add(mnuFileExit); mnuBar.add(mnuFile); // 文件菜单设置结束‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ // // 编辑菜单 // mnuEdit = new JMenu("编辑(E)"); mnuEdit.setFont(mnuFont); mnuEdit.setMnemonic('E'); mnuEditCopy = new JMenuItem("复制(C)"); mnuEditCut = new JMenuItem("剪切(X)"); mnuEditPaste = new JMenuItem("粘贴(V)"); mnuEditDelete = new JMenuItem("删除(L)"); mnuEditUndo = new JMenuItem("撤销(U)"); mnuEditRedo = new JMenuItem("恢复(R)"); mnuEditCopy.setMnemonic('C'); mnuEditCut.setMnemonic('X'); mnuEditPaste.setMnemonic('V'); mnuEditDelete.setMnemonic('L'); mnuEditUndo.setMnemonic('U'); mnuEditRedo.setMnemonic('R'); mnuEditCopy.setActionCommand(EDIT.COPY.toString()); mnuEditCut.setActionCommand(EDIT.CUT.toString()); mnuEditPaste.setActionCommand(EDIT.PASTE.toString()); mnuEditDelete.setActionCommand(EDIT.DELETE.toString()); mnuEditUndo.setActionCommand(EDIT.UNDO.toString()); mnuEditRedo.setActionCommand(EDIT.REDO.toString()); mnuEditCopy.addActionListener(txtListener); mnuEditCut.addActionListener(txtListener); mnuEditPaste.addActionListener(txtListener); mnuEditDelete.addActionListener(txtListener); mnuEditUndo.addActionListener(txtListener); mnuEditRedo.addActionListener(txtListener); this.mnuEditCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK)); this.mnuEditCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK)); this.mnuEditPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK)); this.mnuEditDelete.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, InputEvent.CTRL_MASK)); this.mnuEditUndo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, InputEvent.CTRL_MASK)); this.mnuEditRedo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Y, InputEvent.CTRL_MASK)); mnuEdit.add(mnuEditUndo); mnuEdit.add(mnuEditRedo); mnuEdit.addSeparator(); mnuEdit.add(mnuEditCopy); mnuEdit.add(mnuEditCut); mnuEdit.add(mnuEditPaste); mnuEdit.addSeparator(); mnuEdit.add(mnuEditDelete); mnuBar.add(mnuEdit); // 编辑菜单设置结束‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ // // 弹出式菜单 // popupMenu = new JPopupMenu("我的记事本"); mnuPCopy = new JMenuItem("复制(C)"); mnuPCut = new JMenuItem("剪切(X)"); mnuPPaste = new JMenuItem("粘贴(V)"); mnuPDelete = new JMenuItem("删除(L)"); mnuPCopy.setActionCommand(EDIT.COPY.toString()); mnuPCut.setActionCommand(EDIT.CUT.toString()); mnuPPaste.setActionCommand(EDIT.PASTE.toString()); mnuPDelete.setActionCommand(EDIT.DELETE.toString()); mnuPCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK)); mnuPCopy.addActionListener(txtListener); mnuPCut.addActionListener(txtListener); mnuPPaste.addActionListener(txtListener); mnuPDelete.addActionListener(txtListener); mnuPCopy.setMnemonic('C'); mnuPCut.setMnemonic('X'); mnuPPaste.setMnemonic('V'); mnuPDelete.setMnemonic('L'); popupMenu.add(mnuPCopy); popupMenu.add(mnuPCut); popupMenu.add(mnuPPaste); popupMenu.addSeparator(); popupMenu.add(mnuPDelete); // 弹出式菜单设置结束‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ // // 格式菜单 // mnuFormat=new JMenu("格式(O)"); mnuFormat.setMnemonic('O'); mnuFormatFont=new JMenuItem("字体(F)"); mnuFormatFont.setMnemonic('F'); // // 字体菜单事件,调用字体窗口 JFontChooser // mnuFormatFont.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { Font tempFont=new Font(font.getFamily(),font.getStyle(),font.getSize()); JFontChooser fontChooser=new JFontChooser(FormMain.this,"设置字 体",true,tempFont); if(fontChooser.getNoteFont()!=null) { font=fontChooser.getNoteFont(); txtNote.setFont(font); // // 将字体写回属性文件 // properties=new Properties(); properties.setProperty("fontName", font.getFamily()); properties.setProperty("fontStyle", String.valueOf(font.getStyle())); properties.setProperty("fontSize", String.valueOf(font.getSize())); try { properties.store(new FileWriter("notepad.properties"), null); } catch (IOException e1) { // TODO Auto‐generated catch block e1.printStackTrace(); } } } }); mnuFormat.add(mnuFormatFont); mnuBar.add(mnuFormat); // // 视图菜单 // ViewActionListener viewAction = new ViewActionListener(); mnuView = new JMenu("视图(V)"); mnuView.setMnemonic('V'); mnuBar.add(mnuView); mnuViewStatus = new JCheckBoxMenuItem("状态栏", true); mnuViewForeColor = new JMenuItem("前景颜色"); // 设置文本颜色 mnuViewBackColor = new JMenuItem("背景颜色"); // 设置背景颜色 mnuViewStatus.setActionCommand(VIEW.STATUS.toString()); mnuViewForeColor.setActionCommand(VIEW.FOREGROUND.toString()); mnuViewBackColor.setActionCommand(VIEW.BACKGROUND.toString()); 。
Java编译和解释命令
Java编译和解释命令在对Java源文件进行编译和解释之前,需要先创建Java源文件。
而编写Java 应用程序文件非常简单,一般可以分为下面3个步骤。
1.创建Java源文件在前面已经介绍过,创建Java源文件,并依赖指定的开发工具。
通过一般的文本编辑器工具,都可以进行源代码编写工作。
例如,在【程序】|【附件】中,执行【记事本】命令,并打开【记事本】窗口,并输入Java源代码,如图1-6所示。
图1-6 记录本输入代码然后,在【记事本】窗口中,执行【文件】|【保存】命令,如图1-7所示。
并在弹出的【另存为】对话框中,输入【文件名】为“HelloWorld.java”,单击【保存】按钮,如图1-8所示。
图1-7 保存文件图1-8 输入文件名在编写源代码及保存文件时,对初学用户需要注意以下内容。
源文件的名称一定要和类的名称保持一致。
●源文件的扩展名必须是.java。
●Java语言区分大小写,如HelloWorld、Helloworld、helloworld等不是一样的名称。
●空格只能是半角空格符或是Tab字符。
2.编译源程序(生成.class文件)源程序编写好之后,执行【程序】|【附件】|【命令提示符】命令,并输入“F:”盘符,按【回车】键,如图1-9所示。
然后,再输入“cd workspace”命令,进入到workspace文件夹中,如图1-10所示。
图1-9 更改盘符图1-10 更改目录其次,在该提示下,输入“javac HelloWorld.java”命令,并按【回车】键,对源代码文件进行编译操作,如图1-11所示。
源代码被编译之后,将在workspace文件夹中,自动生成一个“HelloWorld.class”文件,如图1-12所示。
图1-11 编译源文件图1-12 生成.class文件3.解释程序文件生成字节码文件后,通过Java解释器,即可取出指令并将其翻译成计算机能执行的代码。
例如,在【命令提示符】窗口中,输入“java HelloWorld”命令,并按【回车】键,如图1-13所示。
《Java》课程设计》记事本
《Java课程设计》记事本课程设计报告书目录一、设计课题二、设计目的三、操作环境四、设计场所(机房号、机器号或自己机器)五、设计过程(设计内容及主要程序模块)六、本次设计中用到的课程知识点(列出主要知识点)七、设计过程中遇到的问题及解决办法八、程序清单五、设计过程(设计内容及主要模块,不少于3000字)1.设计要求1)界面设计2)功能实现(1)文件菜单:新建、打开、保存、另存为、退出等。
(2)其中新建菜单项可以新建一个记事本程序;打开菜单项可以打开一个用户指定的文本文件,并将其内容显示在记事本的文本区域;保存和另存为菜单项可分别实现文件的保存和另存为3)编辑菜单:复制、剪切和粘贴等4)帮助菜单:软件版本信5)右键弹出快捷菜单2.总体设计1)功能模块图:图一功能模块图2)功能描述1、打开记事本。
首先是标准型的记事本,拥有文件、编辑。
格式和帮助。
如图1所示:图1标准型记事本界面2、在标准型的记事本界面中,进行的新建一个本件名字叫新记事本。
如图2记事本文件帮助新建打开保存另存为退出复制剪切粘贴编辑关于记事本右键快捷格式字体颜色图2新建记事本功能3、用打开文件打开刚刚新建的新记事本。
如图三所示。
图3—打开文件4、点击退出即可退出,如图4所示:图4—退出记事本5、点击帮助可以看到有关记事本的相关信息,其中有作者名、版本、许可条款、隐私声明等必要信息。
如图5所示:图5—帮助相关信息6、右键可实现复制、粘贴、剪切、清除等常用功能,方便用户可以快捷方便的使用记事本。
如图6所示:图6—右键功能7、编辑也可实现制、粘贴、剪切、清除等常用功能,方便用户选择自己适合的方式,自由选择方便的快捷方式使用。
如图7:图7—编辑八、程序清单package test;import java.io.File;import java.io.*;import java.awt.event.*;import java.awt.Toolkit;import java.awt.*;import javax.swing.*;import javax.swing.filechooser.*;public class Notebook extends JFrame implements ActionListener,ItemListener{ //组件创建JButton b_save,b_close; //按钮JTextArea textArea; //文本框File tempFile; //文件JPanel jp; //面板JMenu file,edit,style,help; //菜单JMenuItemf_new,f_open,f_save,f_close,f_saveas,e_copy, e_paste,e_cut,e_clear,e_selectAll,e_find,e_rep lace,s_font,s_color,h_editor,h_help; //菜单条JMenuBar jmb;JScrollPane jsp; //滚动面板JPopupMenu popUpMenu = new JPopupMenu(); //右键弹出式菜单JLabel stateBar;//标签JLabel jl,jj;JFileChooser jfc = new JFileChooser(); //文件选择JMenuItemje_copy,je_paste,je_cut,je_clear,je_selectAll,je _find,je_replace; //弹出式菜单条public Notebook(){jfc.addChoosableFileFilter(new FileNameExtensionFilter("文本文件(*.txt)","txt"));jmb = new JMenuBar();textArea = new JTextArea();jsp = new JScrollPane(textArea);file = new JMenu("文件");edit = new JMenu("编辑");style = new JMenu("格式");help = new JMenu("帮助");je_copy = new JMenuItem("复制(C) ");je_paste = new JMenuItem("粘贴(P) ");je_cut = new JMenuItem("剪切(X) ");je_clear = new JMenuItem("清除(D) ");je_selectAll = new JMenuItem("全选(A) ");je_find = new JMenuItem("查找(F) ");je_replace = new JMenuItem("替换(R) ");je_copy.addActionListener(this); //给弹窗式的各组件添加监听器je_paste.addActionListener(this);je_cut.addActionListener(this);je_clear.addActionListener(this);je_selectAll.addActionListener(this);je_find.addActionListener(this);je_replace.addActionListener(this);//给界面上方的菜单条添加监听器f_new = new JMenuItem("新建(N)");f_new.setAccelerator(KeyStroke.getKeyS troke('N',InputEvent.CTRL_MASK,false)); //设置带修饰符快捷键f_new.addActionListener(this);f_open = new JMenuItem("打开(O)");f_open.setAccelerator(KeyStroke.getKey Stroke('O',InputEvent.CTRL_MASK,false));f_open.addActionListener(this);f_save = new JMenuItem("保存(S)");f_save.setAccelerator(KeyStroke.getKey Stroke('S',InputEvent.CTRL_MASK,false));f_save.addActionListener(this);f_saveas = new JMenuItem("另存为");f_saveas.setAccelerator(KeyStroke.getKe yStroke(KeyEvent.VK_S,InputEvent.CTRL_ MASK|InputEvent.SHIFT_MASK));f_saveas.addActionListener(this);f_close = new JMenuItem("退出(W)");f_close.setAccelerator(KeyStroke.getKey Stroke('W',InputEvent.CTRL_MASK,false));f_close.addActionListener(this);e_copy = new JMenuItem("复制(C)");e_copy.setAccelerator(KeyStroke.getKey Stroke('C',InputEvent.CTRL_MASK,false));e_copy.addActionListener(this);e_paste = new JMenuItem("粘贴(V)");e_paste.setAccelerator(KeyStroke.getKeyStro ke('V',InputEvent.CTRL_MASK,false));e_paste.addActionListener(this);e_cut = new JMenuItem("剪切(X)"); e_cut.setAccelerator(KeyStroke.getKeyStroke ('X',InputEvent.CTRL_MASK,false));e_cut.addActionListener(this);e_clear = new JMenuItem("清除(D)");e_clear.setAccelerator(KeyStroke.getKeyStrok e('D',InputEvent.CTRL_MASK,false));e_clear.addActionListener(this);e_selectAll = new JMenuItem("全选(A)");e_selectAll.setAccelerator(KeyStroke.getKey Stroke('A',InputEvent.CTRL_MASK,false));e_selectAll.addActionListener(this);e_find = new JMenuItem("查找(F)");e_find.setAccelerator(KeyStroke.getKeyStrok e('F',InputEvent.CTRL_MASK,false));e_copy.addActionListener(this);e_replace = new JMenuItem("替换(R)");e_replace.setAccelerator(KeyStroke.getK eyStroke('R',InputEvent.CTRL_MASK,false)) ;e_replace.addActionListener(this);s_font = new JMenuItem("字体(T)");s_font.setAccelerator(KeyStroke.getKeyStrok e('T',InputEvent.CTRL_MASK,false));s_font.addActionListener(this);s_color = new JMenuItem("颜色(C)...");s_color.setAccelerator(KeyStroke.getKeyStro ke(KeyEvent.VK_C,InputEvent.CTRL_MAS K | InputEvent.SHIFT_MASK));s_color.addActionListener(this);h_editor = new JMenuItem("关于记事本");h_editor.setAccelerator(KeyStroke.getKeyStro ke(KeyEvent.VK_E,InputEvent.CTRL_MAS K));h_editor.addActionListener(this);h_help = new JMenuItem("帮助信息(H)");h_help.setAccelerator(KeyStroke.getKeyStrok e(KeyEvent.VK_I,InputEvent.CTRL_MASK) );h_help.addActionListener(this);//添加右键弹出式菜单popUpMenu.add(je_copy);popUpMenu.add(je_paste);popUpMenu.add(je_cut);popUpMenu.add(je_clear);popUpMenu.addSeparator();popUpMenu.add(je_selectAll);popUpMenu.add(je_find);popUpMenu.add(je_replace);//编辑区鼠标事件,点击右键弹出"编辑"菜单textArea.addMouseListener(new MouseAdapter(){public void mouseReleased(MouseEvent e) {if(e.getButton() == MouseEvent.BUTTON3)popUpMenu.show(e.getComponent(), e.getX(), e.getY());} //e.getComponent()和textArea具有同等效果public void mouseClicked(MouseEvent e){if(e.getButton() == MouseEvent.BUTTON1)popUpMenu.setVisible(false);}});this.setJMenuBar(jmb);this.setTitle("记事本程序");file.add(f_new); //添加文件菜单组件file.add(f_open);file.addSeparator(); //加分隔线file.add(f_save);file.add(f_saveas);file.addSeparator();file.add(f_close);edit.add(e_copy); //添加编辑菜单组件edit.add(e_paste);edit.add(e_cut);edit.add(e_clear);edit.addSeparator();edit.add(e_selectAll);edit.add(e_find);edit.add(e_replace);style.addSeparator();style.add(s_font);style.add(s_color);jmb.add(file); //添加格式菜单组件jmb.add(edit);jmb.add(style);jmb.add(help);help.add(h_editor); //添加帮助菜单组件help.add(h_help);//textArea.setWrapStyleWord(true); //设置在单词过长的时候是否要把长单词移到下一行。
Java记事本源代码(完整)
/*** 作品:记事本* 作者:**** 功能:简单的文字编辑*/import java.awt.*;import java.awt.event.*;import java.io.*;import javax.swing.*;import javax.swing.event.ChangeEvent;import javax.swing.event.ChangeListener;class NotePad extends JFrame{private JMenuBar menuBar;private JMenu fielMenu,editMenu,formMenu,aboutMenu;private JMenuItemnewMenuItem,openMenuItem,saveMenuItem,exitMenuItem;private JMenuItemcutMenuItem,copyMenuItem,pasteMenuItem,foundItem,replaceItem,s electAll;private JMenuItem font,about;private JTextArea textArea;private JFrame foundFrame,replaceFrame;private JCheckBoxMenuItem wrapline;private JTextField textField1=new JTextField(15);private JTextField textField2=new JTextField(15);private JButton startButton,replaceButton,reallButton;int start=0;String value;File file=null;JFileChooser fileChooser=new JFileChooser();boolean wrap=false;public NotePad(){//创建文本域textArea=new JTextArea();add(new JScrollPane(textArea),BorderLayout.CENTER);//创建文件菜单及文件菜单项fielMenu=new JMenu("文件");fielMenu.setFont(new Font("微软雅黑",0,15));newMenuItem=new JMenuItem("新建",newImageIcon("icons\\new24.gif"));newMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));newMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent. VK_N,InputEvent.CTRL_MASK));newMenuItem.addActionListener(listener);openMenuItem=new JMenuItem("打开",newImageIcon("icons\\open24.gif"));openMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));openMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent .VK_O,InputEvent.CTRL_MASK));openMenuItem.addActionListener(listener);saveMenuItem=new JMenuItem("保存",newImageIcon("icons\\save.gif"));saveMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent .VK_S,InputEvent.CTRL_MASK));saveMenuItem.addActionListener(listener);exitMenuItem=new JMenuItem("退出",newImageIcon("icons\\exit24.gif"));exitMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));exitMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent .VK_E,InputEvent.CTRL_MASK));exitMenuItem.addActionListener(listener);//创建编辑菜单及菜单项editMenu=new JMenu("编辑");editMenu.setFont(new Font("微软雅黑",0,15));cutMenuItem=new JMenuItem("剪切",newImageIcon("icons\\cut24.gif"));cutMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));cutMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent. VK_X,InputEvent.CTRL_MASK));cutMenuItem.addActionListener(listener);copyMenuItem=new JMenuItem("复制",newImageIcon("icons\\copy24.gif"));copyMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));copyMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent .VK_C,InputEvent.CTRL_MASK));copyMenuItem.addActionListener(listener);pasteMenuItem=new JMenuItem("粘贴",newImageIcon("icons\\paste24.gif"));pasteMenuItem.setFont(new Font("微软雅黑",Font.BOLD,13));pasteMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEven t.VK_V,InputEvent.CTRL_MASK));pasteMenuItem.addActionListener(listener);foundItem=new JMenuItem("查找");foundItem.setFont(new Font("微软雅黑",Font.BOLD,13));foundItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK _F,InputEvent.CTRL_MASK));foundItem.addActionListener(listener);replaceItem=new JMenuItem("替换");replaceItem.setFont(new Font("微软雅黑",Font.BOLD,13));replaceItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent. VK_R,InputEvent.CTRL_MASK));replaceItem.addActionListener(listener);selectAll=new JMenuItem("全选");selectAll.setFont(new Font("微软雅黑",Font.BOLD,13));selectAll.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK _A,InputEvent.CTRL_MASK));selectAll.addActionListener(listener);//创建格式菜单及菜单项formMenu=new JMenu("格式");formMenu.setFont(new Font("微软雅黑",0,15));wrapline=new JCheckBoxMenuItem("自动换行");wrapline.setFont(new Font("微软雅黑",Font.BOLD,13));wrapline.addActionListener(listener);wrapline.addChangeListener(new ChangeListener() {public void stateChanged(ChangeEvent e) {if(wrapline.isSelected()){textArea.setLineWrap(true);}elsetextArea.setLineWrap(false);}});font=new JMenuItem("字体");font.setFont(new Font("微软雅黑",Font.BOLD,13)); font.addActionListener(listener);//创建关于菜单aboutMenu=new JMenu("关于");aboutMenu.setFont(new Font("微软雅黑",0,15)); about=new JMenuItem("记事本……");about.setFont(new Font("微软雅黑",Font.BOLD,13)); about.addActionListener(listener);//添加文件菜单项fielMenu.add(newMenuItem);fielMenu.add(openMenuItem);fielMenu.add(saveMenuItem);fielMenu.addSeparator();fielMenu.add(exitMenuItem);//添加编辑菜单项editMenu.add(cutMenuItem);editMenu.add(copyMenuItem);editMenu.add(pasteMenuItem);editMenu.add(foundItem);editMenu.add(replaceItem);editMenu.addSeparator();editMenu.add(selectAll);//添加格式菜单项formMenu.add(wrapline);formMenu.add(font);//添加关于菜单项aboutMenu.add(about);//添加菜单menuBar=new JMenuBar();menuBar.add(fielMenu);menuBar.add(editMenu);menuBar.add(formMenu);menuBar.add(aboutMenu);setJMenuBar(menuBar);//创建两个框架,用作查找和替换foundFrame=new JFrame();replaceFrame=new JFrame();//创建两个文本框textField1=new JTextField(15);textField2=new JTextField(15);startButton=new JButton("开始");startButton.addActionListener(listener);replaceButton=new JButton("替换为");replaceButton.addActionListener(listener);reallButton=new JButton("全部替换");reallButton.addActionListener(listener);}//创建菜单项事件监听器ActionListener listener=new ActionListener() {public void actionPerformed(ActionEvent e) {String name=e.getActionCommand();if(e.getSource() instanceof JMenuItem){if("新建".equals(name)){textArea.setText("");file=null;}if("打开".equals(name)){if(file!=null){fileChooser.setSelectedFile(file);}intreturnVal=fileChooser.showOpenDialog(NotePad.this);if(returnVal==JFileChooser.APPROVE_OPTION){file=fileChooser.getSelectedFile();}try{FileReader reader=new FileReader(file);int len=(int)file.length();char[] array=new char[len];reader.read(array,0,len);reader.close();textArea.setText(new String(array));}catch(Exception e_open){e_open.printStackTrace();}}}if("保存".equals(name)){if(file!=null){fileChooser.setSelectedFile(file);}intreturnVal=fileChooser.showSaveDialog(NotePad.this);if(returnVal==JFileChooser.APPROVE_OPTION){file=fileChooser.getSelectedFile();}try{FileWriter writer=new FileWriter(file);writer.write(textArea.getText());writer.close();}catch (Exception e_save) {e_save.getStackTrace();}}if("退出".equals(name)){System.exit(0);}if("剪切".equals(name)){textArea.cut();}if("复制".equals(name)){textArea.copy();}if("粘贴".equals(name)){textArea.paste();}if("查找".equals(name)){value=textArea.getText();foundFrame.add(textField1,BorderLayout.CENTER);foundFrame.add(startButton,BorderLayout.SOUTH);foundFrame.setLocation(300,300);foundFrame.setTitle("查找");foundFrame.pack();foundFrame.setVisible(true);foundFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE );}if("替换".equals(name)){value=textArea.getText();JLabel label1=new JLabel("查找内容:");JLabel label2=new JLabel("替换为:");JPanel panel1=new JPanel();panel1.setLayout(new GridLayout(2,2));JPanel panel2=new JPanel();panel2.setLayout(new GridLayout(1,3));replaceFrame.add(panel1,BorderLayout.NORTH);replaceFrame.add(panel2,BorderLayout.CENTER);panel1.add(label1);panel1.add(textField1);panel1.add(label2);panel1.add(textField2);panel2.add(startButton);panel2.add(replaceButton);panel2.add(reallButton);replaceFrame.setTitle("替换");replaceFrame.setLocation(300,300);replaceFrame.pack();replaceFrame.setVisible(true);replaceFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLO SE);}if("开始".equals(name)||"下一个".equals(name)){String temp=textField1.getText();int s=value.indexOf(temp,start);if(value.indexOf(temp,start)!=-1){textArea.setSelectionStart(s);textArea.setSelectionEnd(s+temp.length());textArea.setSelectedTextColor(Color.GREEN);start=s+1;startButton.setText("下一个");}else {JOptionPane.showMessageDialog(foundFrame, "查找完毕!", "提示", 0,new ImageIcon("icons\\search.gif"));foundFrame.dispose();}}if("替换为".equals(name)){String temp=textField1.getText();int s=value.indexOf(temp,start);if(value.indexOf(temp,start)!=-1){textArea.setSelectionStart(s);textArea.setSelectionEnd(s+temp.length());textArea.setSelectedTextColor(Color.GREEN);start=s+1;textArea.replaceSelection(textField2.getText());}else {JOptionPane.showMessageDialog(foundFrame, "查找完毕!", "提示", 0,new ImageIcon("icons\\search.gif"));foundFrame.dispose();}}if("全部替换".equals(name)){String temp=textArea.getText();temp=temp.replaceAll(textField1.getText(),textField2.getTex t());textArea.setText(temp);}if("全选".equals(name)){textArea.selectAll();}if("字体".equals(name)){FontDialog fontDialog=newFontDialog(NotePad.this);fontDialog.setVisible(true);if(textArea.getFont()!=fontDialog.getFont()){textArea.setFont(fontDialog.getFont());}}if("记事本……".equals(name)){AboutDialog aboutDialog=newAboutDialog(NotePad.this);aboutDialog.setVisible(true);}}};//创建字体设置对话面板,并添加相应事件监听器class FontDialog extends JDialog implements ItemListener, ActionListener, WindowListener{public JCheckBox Bold=new JCheckBox("Bold",false);public JCheckBox Italic=new JCheckBox("Italic",false);public List Size,Name;public int FontName;public int FontStyle;public int FontSize;public JButton OK=new JButton("OK");public JButton Cancel=new JButton("Cancel");public JTextArea Text=new JTextArea("字体预览文本域\n0123456789\nAaBbCcXxYyZz");public FontDialog(JFrame owner) {super(owner,"字体设置",true);GraphicsEnvironmentg=GraphicsEnvironment.getLocalGraphicsEnvironment();String name[]=g.getAvailableFontFamilyNames();Name=new List();Size=new List();FontName=0;FontStyle=0;FontSize=8;int i=0;Name.add("Default Value");for(i=0;i<name.length;i++)Name.add(name[i]);for(i=8;i<257;i++)Size.add(String.valueOf(i));this.setLayout(null);this.setBounds(250,200,480, 306);this.setResizable(false);OK.setFocusable(false);Cancel.setFocusable(false);Bold.setFocusable(false);Italic.setFocusable(false);Name.setFocusable(false);Size.setFocusable(false);Name.setBounds(10, 10, 212, 259);this.add(Name);Bold.setBounds(314, 10, 64, 22);this.add(Bold);Italic.setBounds(388, 10, 64, 22);this.add(Italic);Size.setBounds(232, 10, 64, 259);this.add(Size);Text.setBounds(306, 40, 157, 157);this.add(Text);OK.setBounds(306, 243, 74, 26);this.add(OK);Cancel.setBounds(390, 243, 74, 26);this.add(Cancel);Name.select(FontName);Size.select(FontSize);Text.setFont(getFont());Name.addItemListener(this);Size.addItemListener(this);Bold.addItemListener(this);Italic.addItemListener(this);OK.addActionListener(this);Cancel.addActionListener(this);this.addWindowListener(this);}public void itemStateChanged(ItemEvent e) {Text.setFont(getFont());}public void actionPerformed(ActionEvent e) {if(e.getSource()==OK){FontName=Name.getSelectedIndex();FontStyle=getStyle();FontSize=Size.getSelectedIndex();this.setVisible(false);}else cancel();}public void windowClosing(WindowEvent e) {cancel();}public Font getFont(){if(Name.getSelectedIndex()==0) return new Font("新宋体",getStyle(),Size.getSelectedIndex()+8);else return newFont(Name.getSelectedItem(),getStyle(),Size.getSelectedIndex() +8);}public void cancel(){Name.select(FontName);Size.select(FontSize);setStyle();Text.setFont(getFont());this.setVisible(false);}public void setStyle(){if(FontStyle==0 || FontStyle==2)Bold.setSelected(false);else Bold.setSelected(true);if(FontStyle==0 || FontStyle==1)Italic.setSelected(false);else Italic.setSelected(true);}public int getStyle(){int bold=0,italic=0;if(Bold.isSelected()) bold=1;if(Italic.isSelected()) italic=1;return bold+italic*2;}public void windowActivated(WindowEvent arg0) {}public void windowClosed(WindowEvent arg0) {}public void windowDeactivated(WindowEvent arg0) {}public void windowDeiconified(WindowEvent arg0) {}public void windowIconified(WindowEvent arg0) {}public void windowOpened(WindowEvent arg0) {} }//创建关于对话框class AboutDialog extends JDialog implements ActionListener{ public JButton OK,Icon;public JLabel Name,Version,Author,Java;public JPanel Panel;AboutDialog(JFrame owner) {super(owner,"关于",true);OK=new JButton("OK");Icon=new JButton(new ImageIcon("icons\\edit.gif"));Name=new JLabel("Notepad");Version=new JLabel("Version 1.0");Java=new JLabel("JRE Version 6.0");Author=new JLabel("Copyright (c) 11-5-2012 By Jianmin Chen");Panel=new JPanel();Color c=new Color(0,95,191);Name.setForeground(c);Version.setForeground(c);Java.setForeground(c);Author.setForeground(c);Panel.setBackground(Color.white);OK.setFocusable(false);this.setBounds(250,200,280, 180);this.setResizable(false);this.setLayout(null);Panel.setLayout(null);OK.addActionListener(this);Icon.setFocusable(false);Icon.setBorderPainted(false);Author.setFont(new Font(null,Font.PLAIN,11));Panel.add(Icon);Panel.add(Name);Panel.add(Version);Panel.add(Author);Panel.add(Java);this.add(Panel);this.add(OK);Panel.setBounds(0, 0, 280, 100);OK.setBounds(180, 114, 72, 26);Name.setBounds(80, 10, 160, 20);Version.setBounds(80, 27, 160, 20);Author.setBounds(15, 70, 250, 20);Java.setBounds(80, 44, 160, 20);Icon.setBounds(16, 14, 48, 48);}public void actionPerformed(ActionEvent e) { this.setVisible(false);}}}//创建记事本public class ChenJianmin {public static void main(String[] args){EventQueue.invokeLater(new Runnable() {public void run() {NotePad notePad=new NotePad();notePad.setTitle("记事本");notePad.setVisible(true);notePad.setBounds(100,100,800,600);notePad.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}});}}。
记事本程序源代码汇总
import java.awt.event.*;import java.awt.*;import java.io.*;import ng.String;class jsb implements ActionListener{Dialog bb;String strt;int i;FileDialog fd;File file;public Frame f;public TextArea p1;public MenuBar menubar;public Menu menu1,menu2,menu3;public MenuItem item1,item2,item3,item4,item5,item6,item7,item8,item9,item10; jsb(String s{ i=0;f=new Frame(s;p1=new TextArea("";f.setSize(500,500;f.setBackground(Color.white;f.setVisible(true;menubar=new MenuBar(;menu1=new Menu("文件";menu2=new Menu("编辑";menu3=new Menu("帮助";item1=new MenuItem("新建";item2=new MenuItem("打开";item3=new MenuItem("保存";item4=new MenuItem("另存为";item5=new MenuItem("退出";item6=new MenuItem("全选";item7=new MenuItem("复制";item8=new MenuItem("剪切";item9=new MenuItem("粘贴";item10=new MenuItem("关于";f.addWindowListener(new WindowAdapter({public void windowClosing(WindowEvent e {f.setVisible(false;System.exit(0;}};menu1.add(item1;menu1.add(item2;menu1.add(item3;menu1.add(item4;menu1.add(item5;menu2.add(item6;menu2.add(item7;menu2.add(item8;menu2.add(item9;menu3.add(item10;menubar.add(menu1;menubar.add(menu2;menubar.add(menu3;f.setMenuBar(menubar;item1.addActionListener(this;item2.addActionListener(this;item3.addActionListener(this;item4.addActionListener(this;item5.addActionListener(this;item6.addActionListener(this;item7.addActionListener(this;item8.addActionListener(this;item9.addActionListener(this;item10.addActionListener(this;f.setLayout(new GridLayout(1,1;f.add(p1;f.pack(;}public void actionPerformed(ActionEvent e { String ss;ss=p1.getText(.trim(;if (e.getSource(==item5{if (i==0 &&(ss.length(!=0{bc(;}else{System.exit(0;}}if (e.getSource(==item1{if (i==0&&(ss.length(!=0{bc(;}else{p1.setText("";i=0;f.setTitle("文件对话框"; } }if (e.getSource(==item2{fd=new FileDialog(f,"打开文件",0;fd.setVisible(true;try{file=new File(fd.getDirectory(,fd.getFile(;f.setTitle(fd.getFile(+"文件对话框"; FileReader fr=new FileReader(file; BufferedReader br=new BufferedReader(fr; String line = null;String view = "";while((line=br.readLine(!=null{view += line+"\n";}p1.setText(view;br.close(;fr.close(;}catch(IOException expIn{}}if (e.getSource(==item3{if (i==0{bc(;}else{try{file=new File(fd.getDirectory(,fd.getFile(;f.setTitle(fd.getFile(+"--记事本";FileWriter fw=new FileWriter(file; BufferedWriter bw=new BufferedWriter(fw; String s =p1.getText(;s = s.replaceAll("\n","\r\n";bw.write(s;bw.flush(;bw.close(;fw.close(;i=1;}catch(IOException expOut{i=0;}}}if (e.getSource(==item4{bc(;}if (e.getSource(==item10{bb=new Dialog(f,"关于";Label l1=new Label("本记事本的完成感谢老师和同学的帮助!!"; bb.add(l1; bb.setSize(250,150;bb.setBackground(Color.white;bb.show(;bb.addWindowListener(new WindowAdapter({public void windowClosing(WindowEvent e{bb.setVisible(false;bb.dispose(;}};}if (e.getSource(==item6{p1.setSelectionStart(0;p1.setSelectionEnd(p1.getText(.length(; }if (e.getSource(==item7{try{String str=p1.getSelectedText(;if(str.length(!=0{strt=str;}}catch(Exception ex{}}if (e.getSource(==item8{try{String str=p1.getSelectedText(;if(str.length(!=0{p1.replaceRange("",p1.getSelectionStart(,p1.getSelectionEnd(; } }catch(Exception ex{}}if (e.getSource(==item9{if(strt.length(>0{p1.insert(strt,p1.getCaretPosition(;}}}public void bc({fd=new FileDialog(f,"保存文件",1;fd.setVisible(true;try{file=new File(fd.getDirectory(,fd.getFile(;f.setTitle(fd.getFile(+"--记事本"; FileWriter fw=new FileWriter(file; BufferedWriter bw=new BufferedWriter(fw; String s =p1.getText(;s = s.replaceAll("\n","\r\n";bw.write(s;bw.flush(;bw.close(;fw.close(;i=1;}catch(IOException expOut{}} } public class EX0101 { public static void main(String args[] {jsb dd=new jsb("我的记事本";} }。
如何使用记事本编写java程序
如何使用记事本编写java程序使用记事本编写程序需要一定的技术,那么你知道该如何使用记事本编写java程序吗,下面我们一起来看看吧。
如何使用记事本编写java程序第一种方法1首先右击鼠标,新建一个文本文档。
2更改文本文档的后缀名为 .java 。
注意文件名必须和类名相同。
如果你的电脑没有显示后缀名的话需要对电脑进行一定的设置。
3打开计算机——组织——文件夹选项——查看——将隐藏文件夹选项取消勾选即可。
建议将这个选项取消勾选,有很多的恶意程序会侵入我们的电脑,取消勾选可以很好的查看病毒等文件的类型。
4右击建好的文档,选择编辑即可进行java的编写。
在编写的时候我们有一定的格式,java语言的格式是为了我们日后更改程序方便而规定的,我们一定要遵循这种格式编写。
第二种方法1直接新建一个记事本文档,然后选择保存。
注意保存时额位置,不要等到保存完却找不到文件到哪了。
2在选择保存的窗口中输入后缀“.java”,然后保存即可。
注意文件名必须和类名相同。
3同样右击文件,选择编辑即可在文件中进行编辑了。
前两个大括号之间回车,第二对大括号有一个间隔,直接按TAb 键即可。
测试运行java程序打开运行命令,也可以直接在开菜单中输入CMD调用命令窗口。
你的文件保存在哪里就将你的文件目录输入到命令提示符窗口中,例如我的是D盘根目录,所以我输入“d:”。
编译java文件,生成class文件。
在命令提示符中输入“javac 文件名.java”,我的文件名为A,所以输入javac A.java然后回车,等待编译。
运行文件。
继续输入“java 文件名”然后回车就可以运行我们写好的文件了。
java笔记4(布局管理器常用组件qq聊天界面记事本)
Java笔记4(布局管理器、常用组件、qq聊天界面、记事本)文件结构Java代码布局管理器Demo8_1.java package com.test1; import javax.swing.JButton; import javax.swing.JFrame; public classDemo8_1 extends JFrame //继承JFrame { /*** @param args */ public static voidmain(String[] args) { Demo8_1 demo8_1=new Demo8_1(); } //把需要的组件定义在这里JButton jb1=null; //定义一个按钮//构造函数public Demo8_1() { ////JFrame是一个顶层容器类(可以添加其它swing组件的类) //JFrame jf=new JFrame(); //给窗体设置标题this.setTitle("Hello world"); //设置大小,按像素this.setSize(200, 200); //设置初始位置this.setLocation(100,200); //创建一个按钮jb1=new JButton("我是一个按钮!"); //添加JButton组件this.add(jb1); //设置当关闭窗口时,保证JVM也退出this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //显示this.setVisible(true); } } 常用组件常Demo8_2.java /* * BorderLayout演示*1.继承JFrame *2.定义组件*3.创建组件(构造函数) *4.添加组件*5.对窗体设置*6.显示窗体*/ package com.test1; import java.awt.*; import javax.swing.*; public class Demo8_2 extends JFrame{ /** * @param args */ //定义组件JButton jb1,jb2,jb3,jb4,jb5; public static void main(String[] args) { // TODOAuto-generated method stub Demo8_2demo8_2=new Demo8_2(); } publicDemo8_2() { //创建组件jb1=new JButton("中部"); jb2=new JButton("北部"); jb3=new JButton("南部"); jb4=new JButton("东部");jb5=new JButton("西部"); //添加各个组件this.add(jb1,BorderLayout.CENTER);this.add(jb2,BorderLayout.NORTH);this.add(jb3,BorderLayout.SOUTH);this.add(jb4,BorderLayout.EAST);this.add(jb5,BorderLayout.WEST); //设置窗体属性this.setTitle("边界布局的案例");this.setSize(300,200); this.setLocation(200,200); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //显示窗体this.setVisible(true); } }Demo8_3.java /* * 功能:流式:流式布局案例*/ package com.test1; import java.awt.*; import javax.swing.*; public class Demo8_3 extends JFrame{ /** * @param args */ //定义需要的组件JButton jb1,jb2,jb3,jb4,jb5,jb6;public static void main(String[] args) { // TODOAuto-generated method stub Demo8_3 demo8_3=new Demo8_3(); } //构造函数public Demo8_3() { //创建组件jb1=new JButton("关羽"); jb1.setSize(100, 100); jb2=new JButton("张飞"); jb3=new JButton("赵云");jb4=new JButton("马超"); jb5=new JButton("黄忠");jb6=new JButton("魏延"); //添加组件this.add(jb1); this.add(jb2); this.add(jb3);this.add(jb4); this.add(jb5); this.add(jb6);//设置布局管理器this.setLayout(newFlowLayout(FlowLayout.LEFT)); //设置窗体属性this.setTitle("流式布局案例"); this.setSize(350,200); this.setLocation(200,200); //禁止用户改变窗体大小this.setResizable(false);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //显示this.setVisible(true); } }swing编程实战Demo8_4.java /* * 风格布局*/ package com.test1; import java.awt.*; import javax.swing.*; public class Demo8_4 extends JFrame{ int size=9; //定义组件JButton jbs[]=new JButton[size]; public static void main(String[] args) { // TODO Auto-generated method stub //创建实例Demo8_4demo8_4=new Demo8_4(); } //构造函数public Demo8_4() { //创建组件for(inti=0;ijava /* * 多种布局管理器的使用*/ package com.test1; import java.awt.*; import javax.swing.*; public class Demo8_5 extends JFrame { //定义组件JPanel jp1,jp2; JButton jb1,jb2,jb3,jb4,jb5,jb6; public static void main(String[] args) { // TODO Auto-generated method stub Demo8_5 demo8_5=new Demo8_5(); }//构造函数public Demo8_5() { //创建组件//JPanel布局默认是FlowLayout jp1=new JPanel();jp2=new JPanel(); jb1=new JButton("西瓜");jb2=new JButton("苹果"); jb3=new JButton("荔枝");jb4=new JButton("葡萄"); jb5=new JButton("桔子");jb6=new JButton("香蕉"); //设置布局//添加jp1.add(jb1); jp1.add(jb2); jp2.add(jb3);jp2.add(jb4); jp2.add(jb5); //把Panel 加入JFrame this.add(jp1,BorderLayout.NORTH); this.add(jb6,BorderLayout.CENTER);this.add(jp2,BorderLayout.SOUTH);this.setSize(300,150); this.setLocation(200,200); this.setVisible(true); } } Demo8_6.java package com.test1; import java.awt.*; import javax.swing.*; public class Demo8_6 extends JFrame{ /** * @param args */ //定义组件JPanel jp1,jp2,jp3; //三个子面板JLabeljlb1,jlb2; //标签JButton jb1,jb2; //两个按钮JTextField jtf1,jpf1; //两个文本输入框public static void main(String[] args) { // TODOAuto-generated method stub Demo8_6demo8_6=new Demo8_6(); } //构造函数public Demo8_6() { jp1=new JPanel();jp2=new JPanel(); jp3=new JPanel();jlb1=new JLabel("用户名:"); jlb2=new JLabel("密码:"); jb1=new JButton("登录"); jb2=new JButton("取消"); jtf1=new JTextField(10); //用户名文本框jpf1=new JPasswordField(10); //密码文本框//设置布局管理this.setLayout(new GridLayout(3,1));//加入各个组件jp1.add(jlb1); jp1.add(jtf1);jp2.add(jlb2); jp2.add(jpf1); jp3.add(jb1);jp3.add(jb2); //加入到JFrame this.add(jp1); this.add(jp2); this.add(jp3); this.setTitle("会员管理系统"); this.setSize(250,130);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } } Demo8_7.java/* * 复选框或单选框的案例*/ package com.test1; import java.awt.*; importjavax.swing.*; public class Demo8_7 extends JFrame{ //定义JPanel jp1,jp2,jp3;JLabel jl1,jl2; JButton jb1,jb2; JCheckBoxjcb1,jcb2,jcb3; JRadioButton jrb1,jrb2;ButtonGroup bg; public static void main(String[] args) { // TODO Auto-generated method stubDemo8_7 dmeo8_7=new Demo8_7(); } //构造函数public Demo8_7() { //创建组件jp1=new JPanel(); jp2=new JPanel(); jp3=new JPanel(); jl1=new JLabel("你喜欢的运动:");jl2=new JLabel("你的性别:"); jb1=new JButton("注册用户"); jb2=new JButton("取消注册");jcb1=new JCheckBox("足球"); jcb2=newJCheckBox("篮球"); jcb3=new JCheckBox("网球");jrb1=new JRadioButton("男"); jrb2=new JRadioButton("女"); //一定要把jrb1,jrb2放入到一个ButtonGroup ButtonGroup bg=new ButtonGroup(); bg.add(jrb1); bg.add(jrb2);//设置布局管理器this.setLayout(new GridLayout(3,1)); //添加组件jp1.add(jl1); jp1.add(jcb1);jp1.add(jcb2); jp1.add(jcb3); jp2.add(jl2);jp2.add(jrb1); jp2.add(jrb2); jp3.add(jb1);jp3.add(jb2); this.add(jp1); this.add(jp2); this.add(jp3); this.setSize(300,150);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } } Demo8_8.java/* * JCombobox/JList/JScrollPane */package com.test1; import java.awt.*; import javax.swing.*; public class Demo8_8 extends JFrame { //定义JPanel jp1,jp2;JLabel jl1,jl2; JComboBox jcb1; JList jlist; JScrollPane jsp; public static void main(String[] args) { // TODO Auto-generated method stubDemo8_8 demo8_8=new Demo8_8(); } //构造函数public Demo8_8() { jp1=new JPanel(); jp2=new JPanel(); jl1=new JLabel("你的籍贯:"); jl2=new JLabel("旅游地点:"); String []jg={"北京","上海","天津","火星"}; jcb1=new JComboBox(jg); String []dd={"九寨沟","故宫","长城","兵马俑"}; jlist=new JList(dd);jlist.setVisibleRowCount(2);//设置你希望显示多少个选项jsp=new JScrollPane(jlist); //设置布局this.setLayout(new GridLayout(3,1)); //添加组件jp1.add(jl1); //加到面板1当中jp1.add(jcb1);jp2.add(jl2); //加到面板2当中jp2.add(jsp);this.add(jp1); //把面板加入到窗体当中this.add(jp2); //设置窗体属性this.setSize(200,180);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } } Demo8_9.java /* * 词霸*/ package com.test1;import java.awt.*; import javax.swing.*;public class Demo8_9 extends JFrame{ //定义组件JSplitPane jsp; JList jList; JLabel jl1; public static void main(String[] args) { // TODOAuto-generated method stub Demo8_9demo8_9=new Demo8_9(); } publicDemo8_9() { //创建组件String []words={"迈克尔-杰克逊","中国","导游"}; jList=new JList(words); jl1=new JLabel(new ImageIcon("images/迈克尔-杰克逊2.jpg")); //拆分窗格jsp=newJSplitPane(JSplitPane.HORIZONTAL_SPLIT,jList,jl1);//设置窗格可以伸缩jsp.setOneTouchExpandable(true); //设置布局管理器//添加组件this.add(jsp);//设置大小this.setSize(550,632);this.setLocation(200,200);this.setVisible(true); } }Demo8_10.java /* * qq聊天器*/package com.test1; import java.awt.*; import javax.swing.*; public class Demo8_10 extends JFrame{ JTextArea jta=null; JScrollPane jsp=null; //滚动面板JPanel jp1=null;JComboBox jcb=null; JTextField jtf=null; JButton jb=null; public static void main(String[] args) { // TODO Auto-generated method stubDemo8_10 demo8_10=new Demo8_10(); }//构造public Demo8_10() { jta=new JTextArea(); jsp=new JScrollPane(jta); //为文本域添加滚动条jp1=new JPanel(); String []chatter={"布什","拉登"}; jcb=new JComboBox(chatter);jtf=new JTextField(10); jb=new JButton("发送");//设置布局//添加组件jp1.add(jcb);jp1.add(jtf); jp1.add(jb); //加入JFrame this.add(jsp); this.add(jp1,BorderLayout.SOUTH);//设置窗体属性this.setSize(300,200);this.setIconImage((newImageIcon("images\\rowin2.gif")).getImage());this.setTitle("简单QQ");this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } }Demo8_11.java /* * qq登录界面制作*/ package com.test1; import java.awt.*; import javax.swing.*; public class Demo8_11 extends JFrame{ //北部区域JLabel jl1; //南部区域JButton jb1,jb2,jb3; JPanel jp1;//中部区域JTabbedPane jtp;//选项卡窗格JPanel jp2,jp3,jp4;//三个子面板JLabeljl2,jl3,jl4,jl5; //号码输入文本框JTextField jtf; //密码JPasswordField jpf; //清除号码button JButton jb4; //隐身登录,记住密码JCheckBoxjcb1,jcb2; public Demo8_11() { //创建组件jl2=new JLabel("QQ号码",JLabel.CENTER);jl3=new JLabel("QQ密码",JLabel.CENTER); jl4=new JLabel("忘记密码",JLabel.CENTER);jl4.setFont(new Font("宋体",Font.PLAIN,16));//设置字体样式jl4.setForeground(Color.BLUE);//设置字体颜色jl5=new JLabel("申请密码保护");jl5.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_ CURSOR)); //输入号码框jtf=new JTextField(); //输入密码框jpf=new JPasswordField(); jb4=new JButton(newImageIcon("images\\清除号码.jpg")); //复选框jcb1=new JCheckBox("隐身登录"); jcb2=new JCheckBox("记住密码"); //北部区域jl1=new JLabel(new ImageIcon("images\\老虎.jpg"));//南部区域jp1=new JPanel(); jb1=newJButton(new ImageIcon("images\\登录.gif")); jb2=new JButton(new ImageIcon("images\\取消.gif")); jb3=new JButton(new ImageIcon("images\\向导.gif")); //中部区域jtp=new JTabbedPane(); jp2=new JPanel(); jp3=new JPanel();jp3.setBackground(Color.RED);//给面板设置背景颜色jp4=new JPanel(); jp4.setBackground(newColor(0,0,255));//用另一种方法设置背景颜色//将面板添加到选项卡窗格上jtp.add("QQ号码",jp2); //第一个参数代表选项卡的名称,第二个参数代表面板jtp.add("手机号码",jp3); jtp.add("电子邮箱",jp4);//设置布局jp2.setLayout(new GridLayout(3,3));//添加组件//南部jp1.add(jb1); jp1.add(jb2); jp1.add(jb3); //中部jp2.add(jl2);//QQ号码jp2.add(jtf);//号码框jp2.add(jb4);//清除号码按钮jp2.add(jl3);//密码jp2.add(jpf);//密码框jp2.add(jcb1);//记住密码jp2.add(jcb2);//隐身登录jp2.add(jl5);//申请密码保护this.add(jp1,BorderLayout.SOUTH);//加入南部子面板this.add(jl1,BorderLayout.NORTH);//加入北部子面板this.add(jtp,BorderLayout.CENTER);//把选项卡加入中部//展现组件ImageIcon icon=newImageIcon("images\\rowin.gif");this.setIconImage(icon.getImage());this.setSize(350,240); this.setLocation(300,400); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } public static void main(String[] args) { newDemo8_11(); } } Demo8_12.java /* * 记事本界面*/ package com.test1;import java.awt.*; import javax.swing.*; import java.awt.event.*; public class Demo8_12 extends JFrame{ JMenuBar jmb;//菜单条组件JMenu menu1,menu2,menu3,menu4,menu5;JMenuItem item2,item3,item4,item5,item6,item7;JMenu xinjian;//二级菜单JMenuItem file,project; JTextArea jta; //文本输入区域//工具条JToolBar jtb; JButton jb1,jb2,jb3,jb4,jb5,jb6;public Demo8_12() { //创建组件jtb=new JToolBar(); jb1=new JButton(newImageIcon("images\\new.jpg")); jb1.setToolTipText("新建");//设置提示信息jb2=new JButton(new ImageIcon("images\\open.jpg")); jb2.setToolTipText("打开"); jb3=new JButton(newImageIcon("images\\save.jpg")); jb4=newJButton(new ImageIcon("images\\copy.jpg"));jb5=new JButton(new ImageIcon("images\\cut.jpg"));jb6=new JButton(new ImageIcon("images\\paste.jpg")); jmb=new JMenuBar(); menu1=new JMenu("文件(F)"); menu1.setMnemonic('F');//设置助记符menu2=new JMenu("编辑(E)");menu2.setMnemonic('E'); menu3=new JMenu("格式(O)"); menu3.setMnemonic('O'); menu4=new JMenu("查看(V)"); menu4.setMnemonic('V');menu5=new JMenu("帮助(H)");menu5.setMnemonic('H'); //item1=new JMenuItem("新建"); xinjian=new JMenu("新建");file=new JMenuItem("文件"); project=new JMenuItem("工程"); item2=new JMenuItem("打开",new ImageIcon("new.gif")); item3=new JMenuItem("保存(s)"); item3.setMnemonic('s');//给菜单添加快捷方式item3.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.V K_S,InputEvent.ALT_MASK)); item4=new JMenuItem("另存为"); item5=new JMenuItem("页面设置"); item6=new JMenuItem("打印"); item7=new JMenuItem("退出"); jta=new JTextArea();//设置布局//添加组件//将按钮添加到工具条上jtb.add(jb1); jtb.add(jb2); jtb.add(jb3); jtb.add(jb4); jtb.add(jb5); jtb.add(jb6);//将菜单项添加到菜单上xinjian.add(file);xinjian.add(project); menu1.add(xinjian);menu2.add(item2); menu1.add(item3);menu1.add(item4); menu1.addSeparator();//添加分割线menu1.add(item5); menu1.add(item6);menu1.addSeparator(); menu1.add(item7);//将菜单添加到菜单条上jmb.add(menu1);jmb.add(menu2); jmb.add(menu3);jmb.add(menu4); jmb.add(menu5); //将菜单条添加到窗体上this.setJMenuBar(jmb);//将工具条添加到窗体上this.add(jtb,BorderLayout.NORTH); //给文本域添加滚动条JScrollPane jsp=new JScrollPane(jta); jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SC ROLLBAR_AS_NEEDED); this.add(jsp); //展现this.setTitle("记事本"); ImageIcon icon=new ImageIcon("images\\rowin.gif");this.setIconImage(icon.getImage());//设置窗体图标this.setSize(500,400);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } public static void main(String[] args) { Demo8_12 demo8_12=new Demo8_12(); } }。
JAVA--简单记事本源代码
JAVA--简单记事本源代码import javax.swing.JFrame;import javax.swing.JTextArea;import java.awt.*;import java.awt.event.*;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileReader;import java.io.FileWriter;import javax.swing.*;import javax.swing.plaf.FileChooserUI;public class notepad extends JFrame implements ActionListener{//定义所需要的组件JTextArea jta=null;JMenuBar jmb=null;JMenu jm=null;JMenuItem jmi1=null;JMenuItem jmi2=null;public static void main(String[]args){new notepad();}public notepad(){//把组件添加到窗体上jta=new JTextArea();jmb=new JMenuBar();this.add(jta);this.setJMenuBar(jmb);//设置窗体属性this.setTitle("简易记事本");this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setSize(400, 300);this.setVisible(true);//把菜单添加进菜单条jm=new JMenu("⽂件");jm.setMnemonic('f');jmb.add(jm);//把⼦菜单加⼊⾄菜单jmi1=new JMenuItem("打开");jmi2=new JMenuItem("保存");jmi1.setActionCommand("open");jmi2.setActionCommand("save");jm.add(jmi1);jm.add(jmi2);//为两个字菜单注册事件监听jmi1.addActionListener(this);jmi2.addActionListener(this);}public void actionPerformed(ActionEvent e){//对点击了打开进⾏处理if(e.getActionCommand().equals("open")){//创建⼀个⽂件选择组件JFileChooser jfc1=new JFileChooser();//设置⽂件选择器的名字jfc1.setDialogTitle("请选择⽂件....");//设置⽂件选择组件的类型(打开类型)jfc1.showOpenDialog(null);//显⽰该组件jfc1.setVisible(true);//获取选择⽂件的绝对路径String s;s=jfc1.getSelectedFile().getAbsolutePath();//将该⽂件显⽰到记事本上BufferedReader br=null;FileReader fr=null;try{//创建⼀个带缓冲的⽂件读取对象fr=new FileReader(s);br=new BufferedReader(fr);String text="";String m=null;//循环读取⽂件while((m=br.readLine())!=null){text+=m+"\r\n";}//将读取的结果打印到记事本上⾯this.jta.setText(text);}catch(Exception e1){e1.printStackTrace();}finally{//关掉打开的⽂件try{br.close();fr.close();}catch(Exception e2){e2.printStackTrace();}}}else if(e.getActionCommand().equals("save")){//创建⼀个⽂件选择组件JFileChooser jfc=new JFileChooser();//设置⽂件选择的名称jfc.setDialogTitle("另存为");//设置⽂件选择组件的类型(保存类型)jfc.showSaveDialog(null);//显⽰该组件jfc.setVisible(true);//获取选择⽂件的绝对路径String filename;filename=jfc.getSelectedFile().getAbsolutePath(); //将记事本内的⽂本保存⾄该路径BufferedWriter bw=null;FileWriter fw=null;try{//创建⽂件输出⽂件fw=new FileWriter(filename);bw=new BufferedWriter(fw);//获取⽂本String outtext="";outtext=this.jta.getText();//输出⽂本fw.write(outtext);}catch(Exception e2){e2.printStackTrace();}finally{//关闭打开的输出⽂件try{bw.close();fw.close();}catch(Exception e3){e3.printStackTrace();}}}}}。
记事本源代码
import java.awt.*;import java.awt.event.*;import java.io.*;import java.awt.datatransfer.*;class MyMenuBar extends MenuBar{public MyMenuBar(Frame parent){parent.setMenuBar(this);}public void addMenus(String [] menus){for(int i=0;i<menus.length;i++)add(new Menu(menus[i]));}public void addMenuItems(int menuNumber,String[] items){for(int i=0;i<items.length;i++){if(items[i]!=null)getMenu(menuNumber).add(new MenuItem(items[i]));else getMenu(menuNumber).addSeparator();}}public void addActionListener(ActionListener al){for(int i=0;i<getMenuCount();i++)for(int j=0;j<getMenu(i).getItemCount();j++)getMenu(i).getItem(j).addActionListener(al);}}class MyFile{private FileDialog fDlg;public MyFile(Frame parent){fDlg=new FileDialog(parent,"",FileDialog.LOAD);}private String getPath(){return fDlg.getDirectory()+"\\"+fDlg.getFile();}public String getData() throws IOException{fDlg.setTitle("打开");fDlg.setMode(FileDialog.LOAD);fDlg.setV isible(true);BufferedReader br=new BufferedReader(new FileReader(getPath()));StringBuffer sb=new StringBuffer();String aline;while((aline=br.readLine())!=null)sb.append(aline+'\n');br.close();return sb.toString();}public void setData(String data) throws IOException{fDlg.setTitle("保存");fDlg.setMode(FileDialog.SA VE);fDlg.setV isible(true);BufferedWriter bw=new BufferedWriter(new FileWriter(getPath()));bw.write(data);bw.close();}}class MyClipboard{private Clipboard cb;public MyClipboard(){cb=Toolkit.getDefaultToolkit().getSystemClipboard();}public void setData(String data){cb.setContents(new StringSelection(data),null);}public String getData(){Transferable content=cb.getContents(null);try{return (String) content.getTransferData(DataFlavor.stringFlavor);//DataFlavor.stringFlavor会将剪贴板中的字符串转换成Unicode码形式的String 对象。
android开发记事本实验报告,记事本实验报告(含源代码运行结果).doc
android开发记事本实验报告,记事本实验报告(含源代码运⾏结果).doc记事本实验报告(含源代码运⾏结果)嘉应学院计算机学院实验报告系/班别: 计算机学院 1203班指导⽼师: 肖**课程名称: Java语⾔程序设计实验内容: ⽤Java编写记事本学⽣学号:学⽣姓名: 曾朝阳实验地点: 锡科403实验类型: 设计实验时间: 第⼗四周⾄第⼗七周实验要求:能够通过使⽤JDK1.6安装开发windows 桌⾯应⽤程序。
实验⽬的:熟悉事件触发和事件监听以及组件和容器的界⾯安排,能够⽤java设计⼀个仿windows的标准型记事本。
实验过程描述:实验环境:⽹络实验室实验设备:PC机, ⽹络实验平台:winxp. JDK1.6过程描述:1.⾸先,安装JDK1.62.打开开始-》运⾏->输⼊cmd进⼊dos->cd 路径(原程序的路径)->javac NotepadTest.java(编绎)->java NotepadTest运⾏编写程序:import java.io.File;import .URLClassLoader;import .URL;import ng.InterruptedException;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.PrintStream;import java.util.Scanner;import java.util.Date;import java.util.Iterator;import java.util.List;import java.text.SimpleDateFormat; import javax.swing.JButton;import javax.swing.JCheckBox;import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JTextArea;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.ImageIcon;import javax.swing.JScrollPane;import javax.swing.JToolBar;import javax.swing.JMenuItem;import javax.swing.KeyStroke;import javax.swing.JPopupMenu;import javax.swing.JFileChooser;import javax.swing.JOptionPane;import javax.swing.JFileChooser;import javax.swing.JColorChooser; import javax.swing.JDialog;import javax.swing.JTextField;import javax.swing.BorderFactory;import javax.swing.JList;import javax.swing.JComboBox;import javax.swing.UIManager;import javax.swing.JRadioButton;import javax.swing.JToggleButton;import javax.swing.ButtonGroup;import javax.swing.TransferHandler;import javax.swing.border.Border; import javax.swing.border.TitledBorder; import javax.swing.text.Document; import javax.swing.undo.UndoManager; import javax.swing.undo.UndoableEdit; import。
记事本源代码
这是我自己写的一个小小的记事本源程序不足之处还望大家多多指教!希望对您有所帮助下面是代码import java.awt.*;import java.awt.event.*;import java.io.*;import javax.swing.*;public class mune extends WindowAdapter implements ActionListener{Frame f;MenuBar mb;Menu wenj,bianj,ges,bangz,zuoz,fontMI,lineMI,ziyan;MenuItem newMI,openMI,saveMI,exitMI,cutMI,copyMI,pasteMI,guanyuMI, yans3,yans4,yans5,yans6,yans1,yans2,ziti1,ziti2,ziti3,ziti4,yans7,yans8,yans9,yans10,yans11,yans12,guanyujMI;JTextArea ta;FileDialog fileSave,fileLoad;File fl;public void go(){f=new Frame("记事本");ta=new JTextArea(60,60);f.add(ta);mb=new MenuBar();f.setMenuBar(mb);wenj=new Menu("文件");bianj=new Menu("编辑");ges=new Menu("格式");bangz=new Menu("帮助");zuoz=new Menu("作者");mb.add(wenj);mb.add(bianj);mb.add(ges);mb.add(bangz);mb.add(zuoz);newMI=new MenuItem("新建",new MenuShortcut(KeyEvent.VK_N)); openMI=new MenuItem("打开",new MenuShortcut(KeyEvent.VK_O)); saveMI=new MenuItem("保存",new MenuShortcut(KeyEvent.VK_S)); exitMI=new MenuItem("退出",new MenuShortcut(KeyEvent.VK_Z)); wenj.add(newMI);wenj.add(openMI);wenj.add(saveMI);wenj.addSeparator();wenj.add(exitMI);cutMI=new MenuItem("剪切",new MenuShortcut(KeyEvent.VK_X)); copyMI=new MenuItem("复制",new MenuShortcut(KeyEvent.VK_C)); pasteMI=new MenuItem("粘贴",new MenuShortcut(KeyEvent.VK_V));bianj.add(cutMI);bianj.add(copyMI);bianj.add(pasteMI);lineMI=new Menu("背景颜色"); fontMI=new Menu("字体");ziyan=new Menu("字体颜色");yans1=new MenuItem("蓝色");yans2=new MenuItem("红色");yans3=new MenuItem("白色");yans4=new MenuItem("绿色");yans5=new MenuItem("黄色");yans6=new MenuItem("黑色");yans7=new MenuItem("蓝色");yans8=new MenuItem("红色");yans9=new MenuItem("白色");yans10=new MenuItem("绿色");yans11=new MenuItem("黄色");yans12=new MenuItem("黑色"); ziti1=new MenuItem("宋体");ziti2=new MenuItem("楷体");ziti3=new MenuItem("仿宋");ziti4=new MenuItem("黑体");ges.add(lineMI);lineMI.add(yans1);lineMI.add(yans2);lineMI.add(yans3);lineMI.add(yans4);lineMI.add(yans5);lineMI.add(yans6);ges.addSeparator();ges.add(fontMI);fontMI.add(ziti1);fontMI.add(ziti2);fontMI.add(ziti3);fontMI.add(ziti4);ges.addSeparator();ges.add(ziyan);ziyan.add(yans7);ziyan.add(yans8);ziyan.add(yans9);ziyan.add(yans10);ziyan.add(yans11);ziyan.add(yans12);guanyujMI=new MenuItem("关于记事本"); bangz.add(guanyujMI);guanyuMI=new MenuItem("关于作者");zuoz.add(guanyuMI);guanyuMI.addActionListener(this);newMI.addActionListener(this); openMI.addActionListener(this); saveMI.addActionListener(this); exitMI.addActionListener(this);cutMI.addActionListener(this);copyMI.addActionListener(this);pasteMI.addActionListener(this);yans1.addActionListener(this);yans2.addActionListener(this);yans3.addActionListener(this);yans4.addActionListener(this);yans5.addActionListener(this);yans6.addActionListener(this);ziti1.addActionListener(this);ziti2.addActionListener(this);ziti3.addActionListener(this);ziti4.addActionListener(this);yans7.addActionListener(this);yans8.addActionListener(this);yans9.addActionListener(this);yans10.addActionListener(this);yans11.addActionListener(this);yans12.addActionListener(this);fileSave=new FileDialog(f,"保存文件话框",FileDialog.SAVE);fileLoad=new FileDialog(f,"打开文件话框",FileDialog.LOAD);fileSave.addWindowListener(this);fileLoad.addWindowListener(this);f.addWindowListener(this);f.setSize(900,600);f.setVisible(true);}public void actionPerformed(ActionEvent e){if(e.getSource()==yans1){ta.setBackground(Color.blue);}if(e.getSource()==yans2)ta.setBackground(Color.red);}if(e.getSource()==yans3){ta.setBackground(Color.white);}if(e.getSource()==yans4){ta.setBackground(Color.green);}if(e.getSource()==yans5){ta.setBackground(Color.yellow);}if(e.getSource()==yans6){ta.setBackground(Color.black); }if(e.getSource()==yans7){ta.setForeground(Color.blue);if(e.getSource()==yans8){ta.setForeground(Color.red);}if(e.getSource()==yans9){ta.setForeground(Color.white);}if(e.getSource()==yans10){ta.setForeground(Color.green);}if(e.getSource()==yans11){ta.setForeground(Color.yellow);}if(e.getSource()==yans12){ta.setForeground(Color.black); }if(e.getSource()==ziti1){ta.setFont(new Font("宋体",Font.BOLD,20)); }if(e.getSource()==ziti2){ta.setFont(new Font("楷体",Font.BOLD,20)); }if(e.getSource()==ziti3){ta.setFont(new Font("仿宋",Font.BOLD,20)); }if(e.getSource()==ziti2){ta.setFont(new Font("黑体",Font.BOLD,20)); }if(e.getSource()==copyMI){ta.copy();}if(e.getSource()==pasteMI){ta.paste();}if(e.getSource()==cutMI){ta.cut();}if(e.getSource()==guanyuMI){JOptionPane.showMessageDialog(f,"雷智新制作\nQQ;970425630","作者信息",RMATION_MESSAGE);}if(e.getSource()==exitMI)System.exit(0);else if(e.getSource()==newMI){ta.setText("");}else if(e.getSource()==saveMI){fileSave.setVisible(true);if(fileSave.getFile()!=null){try{fl=newFile(fileSave.getDirectory(),fileSave.getFile());FileWriter fw=new FileWriter(fl);fw.write(ta.getText());//将文本中的内容写入输出流所对应的文件fw.close();}catch(IOException ee){System.out.println(ee);}}}else if(e.getSource()==openMI){fileLoad.setVisible(true);ta.setText("");if(fileLoad.getFile()!=null){try{fl=new File(fileLoad.getDirectory(),fileSave.getFile());BufferedReader br=newBufferedReader(new FileReader(fl));String str;while((str=br.readLine())!=null)ta.append(str+"\r\n");br.close();}catch(IOException ee){System.out.println(ee);}}}}public void windowClosing(WindowEvent e){if(e.getSource()==fileSave)fileSave.setVisible(false);else if(e.getSource()==fileLoad)fileLoad.setVisible(false);elseSystem.exit(0);}public static void main(String args[]){mune mymenu=new mune();mymenu.go();}}。
java编程记事本代码
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; public class Notepad extends JFrame {係统组件声明private JMenuBar menuBar = new JMe nuBar(; private JEditorPa ne content = new JEditorPa ne(; private JScrollPa ne scroll = new JScrollPa ne(c ontent; private JFileChooser filechooser = new JFileChooser(; private BorderLayout bord = new BorderLayout(; private JLabel statusBar = new JLabel(; private JPanel pane = new JPanel(; private File file = null; /定义文件菜单private JMenu fileMenu = new JMenu(; private JMenultem newMenultem = new JMenultem(; private JMe nultem ope nMen ultem = new JMe nultem(; private JMe nultem saveMe nultem = new JMe nultem(; private JMe nultem saveAsMe nultem = new JMe nultem(; private JMe nultem pageSetupMe nultem = new JMe nultem(; private JMe nultem prin tMe nultem = new JMe nultem(; private JMe nultem exitMe nultem = new JMenultem(; // 定义风格菜单private JMenu styleMenu = new JMenu(; private Butt on Group styleMe nu Group = new Butt on Group(; private JRadioButt onMen ultem javaStyleMe nultem = new JRadioButt onMen ultem(; private JRadioButt onMen ultem metalStyleMe nultem = new JRadioButt onMen ultem(; private JRadioButt onMen ultem windowsStyleMenultem = new JRadioButtonMenultem(; // 定义帮助菜单private JMe nultem aboutMe nultem = new JMe nultem(; private JMe nultem helpTopicMe nultem =new JMenultem(; private JMenu helpMenu = new JMenu(; 〃构造函数public Notepad({ initComponents(; } private void initComponents({ // 添加子菜单项到文件菜单fileMe nu.setText("\u6587\u4ef6 (F"; n ewMe nultem.setText(” 新建(NCtrl+N"; ope nMen ultem.setText(” 打开(O…Ctrl+O"; saveMe nultem.setText(”保存(S Ctrl+S"; saveAsMenultem.setText(” 另存为(A..."; pageSetupMenultem.setText(” 页面设置(U..."; printMenultem.setText(” 打印(P... Ctrl+P"; exitMe nultem.setText(” 退出";fileMe nu.add( newMe nultem;fileMe nu .add(ope nMen ultem; fileMe nu .add(saveMe nultem; fileMe nu .add(saveAsMe nultem; fileMe nu.addSeparator(; fileMenu.add(pageSetupMenultem;fileMenu.add(printMenultem; fileMe nu.addSeparator(; fileMe nu.add(exitMe nultem; // 添加子菜单项到风格菜单styleMe nu.setText(‘ 风格(S"; javaStyleMe nultem.setText("Java 默认";metalStyleMe nultem.setText("Metal 风格";wi ndowsStyleMe nultem.setText("Wi ndows 风格";styleMe nuGroup.add(javaStyleMe nultem;styleMe nuGroup.add(metalStyleMe nuItem;styleMe nu Group.add(wi ndowsStyleMe nultem; styleMe nu .add(javaStyleMe nultem; styleMe nu.add(metalStyleMe nultem; styleMe nu.add(wi ndowsStyleMe nultem; // 添加子菜单项到帮助菜单helpMenu.setText(‘帮助(H"; helpTopicMenultem.setText(” 帮助主题(H"; aboutMenultem.setText(” 关于记事本(A";helpMe nu .add(helpTopicMe nultem; helpMe nu .addSeparator(;helpMe nu .add(aboutMe nultem; //定义文件菜单下的事件监听n ewMe nultem.addActio nListe ner(new n ewMe nultem_actio nAdapter(this; ope nMen ultem.addActio nListe ner(new ope nMen ultem_actio nAdapter(this; saveMenultem.addActio nListe ner(new saveMe nultem_actio nAdapter(this; saveAsMe nultem.addActio nListe ner(new saveAsMe nultem_actio nAdapter(this; pageSetupMe nultem.addActio nListe ner(new pageSetupMe nultem_actio nAdapter(this; prin tMe nultem.addActi on Liste ner(n ew prin tMe nultem_actio nAdapter(this;exitMenultem.addActionListener(new exitMenultem_actionAdapter(this; // 定义风格菜单下的事件监听javaStyleMenultem.addActionListener(newjavaStyleMenultem_actionAdapter(this; metalStyleMenultem.addActionListener(new metalStyleMe nultem_actio nAdapter(this;wi ndowsStyleMe nultem.addActio nListe ner(newwi ndowsStyleMe nultem_actio nAdapter(this; // 定义帮助菜单下的事件监听helpTopicMe nultem.addActio nListe ner(new helpTopicMe nultem_actio nAdapter(this; aboutMe nultem.addActio nListe ner(new aboutMe nultem_actio nAdapter(this; 〃填加菜单至U菜单栏menuBar.add(fileMenu; menuBar.add(styleMenu; menuBar.add(helpMenu; // 对主窗口的一些设置this.setDefaultCloseOperation(EXIT_ON_CLOSE; this.setTitle(" 纪生的记事本";this.setSize(640,480; setJMenuBar(menuBar; pane.setLayout(bord;pane.add("Center",scroll; setContentPane(pane; } /定义新建菜单项方法public void newMe nultemActio nPeformed(Actio nEve nt evt{ file = nu II;if(!("".equals(co nten t.getText({ Object]] optio ns = {" 是(Y "," 否(N "," 取消"}; int s = JOptio nPan e.showOptio nDialog( null, "\u6587\u4ef6 "+getTitIe(+"\u7684\u6587\u5b57\u5df2\u7ecf\u6539\u53d8\u3002\n\u60f3\u4fdd\u5b58\u6587\u4ef6 \u5417\uff1f", "\u8bb0\u4e8b\u672c", JOptio nPan e.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]; switch(s{ case 0: int returnVal=filechooser.showSaveDialog(this; if(returnVal ==JFileChooser.APPROVE_OPTION { file=filechooser.getSelectedFile(; try{ FileWriterfw=new FileWriter(file; fw.write(co nten t.getText(;setTitle(filechooser.getSelectedFile(.getName(+" - \u8bb0\u4e8b\u672c"; fw.close(; } catch(Excepti on e{ e.pri ntStackTrace(; } break; } case 1: conten t.setText(""; setTitle("无标题-\u8bb0\u4e8b\u672c"; } } } // 定义打开菜单项方法public voidope nMen ultemActio nPeformed(Actio nEve nt evt{ try { file = n ull; int returnVal = filechooser.showOpenDialog(this; if(returnVal ==JFileChooser.APPROVE_OPTION{ file = filechooser.getSelectedFile(; FileReader fr = new FileReader(file; int len = (in tfile .len gth(; char[] buffer = new char[le n]; fr.read(buffer,0,le n; fr.close(; conten t.setText (newString(buffer; } } catch(Exception e{ e.printStackTrace(; } } // 定义退出菜单项方法public void exitMe nultem_actio nPeformed(Actio nEve nte{ if(!("".equals(co nte nt.getText({ Object]] optio ns = {" 是(Y "," 否(N "," 取消"}; int s = JOptionPane.showOptionDialog(null,"文件的文字已经改变。
Java学习案例-实现日记本功能
日记本【任务介绍】1.任务描述编写一个日记本功能的程序,使用字节流经日记的具体信息记录在本地的txt文件中。
当用户输入日记的特定内容后,会将输入的内容保存至本地的txt文件中。
需要输入的内容包括“姓名”,“天气”、“标题”、“内容”的数据。
保存的时候需要判断本地是否存在文件,如果存在则追加,不存在则新建。
文件命名格式为“黑马日记本”加上“.txt”后缀,如“黑马日记本.txt”2.运行结果任务运行结果如图7-1所示。
图7-2 运行结果运行结束后在本地生成一个“黑马日记本.txt”文件,如图7-2所示。
图7-2 黑马日记本.txt【任务目标】●学会分析"日记本小功能"程序的实现思路。
●根据思路独立完成"日记本小功能"的源代码编写、编译及运行。
●掌握字节流操作本地文件的方法。
●掌握ArrayList和StringBuffer的使用,以及异常的处理。
【实现思路】(1)为方便保存日记的相关信息,可以将日记信息封装成一个实体类。
(2)用户编写日记时,首先创建一个集合用于存放日记,然后用户依次填写的内容为“姓名”,“天气”、“标题”和“内容”,并将这些内容存放在集合中,再将实体类保存到txt文件中。
(3)查询日记时,使用字节流的读取实现控制台打印日记信息。
(4)将日记信息写入到txt文件之前,需先拼凑好txt文件名,再判断本地是否已存在此文件,这里可通过输入流尝试获取此文件的字节流,如果获取成功,则证明这个文件已存在,那么就通过输出流向文件末尾追加日记信息,如果获取失败,即异常,说明之前并没有生成日记信息,则需要新建此文件。
【实现代码】日记小功能的实现代码,如文件7-1所示。
(1)将日记信息封装成一个实体类Diary,具体如文件7-1所示。
文件7-1 Diary.java1 package chapter0703;2 public class Diary {3 String time; //时间4 String name; //姓名5 String weather;//天气6 String title;//标题7 String content;//内容8 public Diary(String time, String name, String weather, String title,9 String content) {10 this.time = time;11 = name;12 this.weather = weather;13 this.title = title;14 this.content=content;15 }16 }在文件7-1中,第3-7行代码定义了用于标识日记信息的各个字段,第8-14行代码重新了toString()方法。
记事本程序源代码汇总
记事本程序源代码汇总下面是一个简单的记事本程序的源代码:```#include <iostream>#include <fstream>#include <string>using namespace std;void showMencout << "**********************" << endl; cout << " 记事本程序 " << endl; cout << "**********************" << endl; cout << "请选择以下操作:" << endl;cout << "1. 新建记事本文件" << endl;cout << "2. 打开已有记事本文件" << endl; cout << "3. 查看记事本文件内容" << endl; cout << "4. 添加文本到记事本文件" << endl; cout << "5. 退出程序" << endl;cout << "**********************" << endl; void createFilstring filename;cout << "请输入新建记事本文件的文件名:";cin >> filename;//在当前目录创建一个新文件ofstream outFile(filename);outFile.close(;cout << "成功创建记事本文件:" << filename << endl; void openFilstring filename;cout << "请输入要打开的记事本文件的文件名:";cin >> filename;//尝试打开已存在的文件ifstream inFile(filename);if (!inFile)cout << "无法打开文件:" << filename << endl;} elsestring content;getline(inFile, content, '\0');cout << "记事本文件内容:" << endl;cout << content << endl;inFile.close(;}void viewFilstring filename;cout << "请输入要查看的记事本文件的文件名:"; cin >> filename;//尝试打开已存在的文件ifstream inFile(filename);if (!inFile)cout << "无法打开文件:" << filename << endl; } elsestring line;cout << "记事本文件内容:" << endl;while (getline(inFile, line))cout << line << endl;}inFile.close(;}void appendToFilstring filename;cout << "请输入要添加文本的记事本文件的文件名:";cin >> filename;//尝试打开已存在的文件ofstream outFile(filename, ios::app);if (!outFile)cout << "无法打开文件:" << filename << endl;} elsestring content;cout << "请输入要添加的文本内容(以#结束):" << endl; while (true)getline(cin, content);if (content == "#")break;}outFile << content << endl;}outFile.close(;cout << "成功添加文本到记事本文件:" << filename << endl; }int maiint choice;doshowMenu(;cout << "请输入您的选择:";cin >> choice;switch (choice)case 1:createFile(;break;case 2:openFile(;break;case 3:viewFile(;break;case 4:appendToFile(;break;case 5:cout << "感谢使用记事本程序,再见!" << endl;break;default:cout << "无效的选择,请重新输入!" << endl;}} while (choice != 5);return 0;```这个记事本程序通过命令行界面提供了以下操作:1.新建记事本文件:用户输入一个文件名后,在当前目录下创建一个新文件作为记事本。
java记事本源代码
JMenuItem m13=new JMenuItem("另保存为 ");
m13.addActionListener(this);
JMenuItem m14=new JMenuItem("退出 ");
m14.addActionListener(this);
{
myfr fr=new myfr("JAVA记事本");
fr.setSize(560,395);
}
}
///////////////////////////myfr主窗体类//////////////////////////////////////
class myfr extends JFrame implements ActionListener
JTextArea txt1; //主输入文本区
File newfiles;
JPopupMenu popm; //弹出菜单声明
//JMenu m1,m2,m3,m4,m5,m6; //各菜单项
JMenu m1, m2, m3;
JMenuItem m26,m271,m34,p_copy,p_cut,p_paste,p_del;
replb.addActionListener(this);
mainpane=(JPanel)this.getContentPane();
mainpane.setLayout(new BorderLayout());
txt1=new JTextArea("",13,61);
m21.setAccelerator(keycopy);
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.text.*;import javax.swing.event.*;public class IJMFrame extends JFrame {Document document = null;JTextArea textArea = new JTextArea();JScrollPane scrollPane = new JScrollPane(textArea); EditController controller;//------ 定义菜单变量------//JMenuBar menuBar = new JMenuBar();JMenu menuFile = new JMenu("文件");JMenu menuEdit = new JMenu("编辑");JMenu menuFormat = new JMenu("格式"); JPopupMenu memuPopup = new JPopupMenu(); JMenuItem itemNew = new JMenuItem("新建"); JMenuItem itemOpen = new JMenuItem("打开"); JMenuItem itemSave = new JMenuItem("保存"); JMenuItem itemSaveAs = new JMenuItem("另存"); JMenuItem itemExit = new JMenuItem("退出"); JMenuItem itemUndo = new JMenuItem("撤消"); JMenuItem itemCut = new JMenuItem("剪切"); JMenuItem itemCopy = new JMenuItem("复制"); JMenuItem itemPaste = new JMenuItem("粘贴"); JMenuItem itemDelete = new JMenuItem("删除"); JMenuItem itemFind = new JMenuItem("查找"); JMenuItem itemReplace = new JMenuItem("替换"); JMenuItem itemSelectAll = new JMenuItem("全选"); JMenuItem itemFont = new JMenuItem("字体");//------------定义右键菜单------------------------// JMenuItem popupMenu_Undo=new JMenuItem("撤销"); JMenuItem popupMenu_Cut=new JMenuItem("剪切"); JMenuItem popupMenu_Copy=new JMenuItem("复制"); JMenuItem popupMenu_Paste=new JMenuItem("粘贴"); JMenuItem popupMenu_Delete=new JMenuItem("删除"); JMenuItem popupMenu_SelectAll=new JMenuItem("全选");public IJMFrame() {super("记事本");setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setJMenuBar(menuBar);//创建新的菜单栏getContentPane().add(scrollPane);document = textArea.getDocument();textArea.setLineWrap(true);// 默认为换行textArea.setWrapStyleWord(true);//-- 设置菜单--//itemUndo.setEnabled(false);menuBar.add(menuFile);menuBar.add(menuEdit);menuBar.add(menuFormat);menuFile.add(itemNew);menuFile.add(itemOpen);menuFile.add(itemSave);menuFile.add(itemSaveAs);menuFile.addSeparator();menuFile.add(itemExit);menuEdit.add(itemUndo);menuEdit.addSeparator();menuEdit.add(itemCut);menuEdit.add(itemCopy);menuEdit.add(itemPaste);menuEdit.add(itemDelete);menuEdit.addSeparator();menuEdit.add(itemFind);menuEdit.add(itemReplace);menuEdit.add(itemSelectAll);menuFormat.add(itemFont);popupMenu_Undo.setEnabled(false); // 撤消选项初始设为不可用memuPopup.add(popupMenu_Undo);memuPopup.addSeparator();memuPopup.add(popupMenu_Cut);memuPopup.add(popupMenu_Copy);memuPopup.add(popupMenu_Paste);memuPopup.add(popupMenu_Delete);memuPopup.addSeparator();memuPopup.add(popupMenu_SelectAll);//-- 增加菜单的侦听者--//controller = new EditController(this);itemNew.addActionListener(controller);itemOpen.addActionListener(controller);itemSave.addActionListener(controller);itemSaveAs.addActionListener(controller);itemExit.addActionListener(controller);itemUndo.addActionListener(controller);itemCut.addActionListener(controller);itemCopy.addActionListener(controller);itemPaste.addActionListener(controller);itemDelete.addActionListener(controller);itemFind.addActionListener(controller);itemReplace.addActionListener(controller);itemSelectAll.addActionListener(controller);itemFont.addActionListener(controller);popupMenu_Undo.addActionListener(controller);popupMenu_Cut.addActionListener(controller);popupMenu_Copy.addActionListener(controller);popupMenu_Paste.addActionListener(controller);popupMenu_Delete.addActionListener(controller);popupMenu_SelectAll.addActionListener(controller);document.addDocumentListener(controller);document.addUndoableEditListener(controller);addWindowListener(controller);MouseAdapter mAdapter=new MouseAdapter(){public void mousePressed(MouseEvent e) {checkForTriggerEvent(e);}public void mouseReleased(MouseEvent e) {checkForTriggerEvent(e);}private void checkForTriggerEvent(MouseEvent e) {if (e.isPopupTrigger())memuPopup.show(e.getComponent(), e.getX(), e.getY());// 在组件调用者的坐标空间中的位置// X、Y// 显示弹出菜单。
}};textArea.addMouseListener(mAdapter);setSize(600,600);setVisible(true);}public static void main(String[] args) {new IJMFrame();}}import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;import javax.swing.undo.*;public class EditController implements ActionListener, DocumentListener, WindowListener, UndoableEditListener {IJMFrame frame;EditModel model;UndoManager um = new UndoManager();public EditController(IJMFrame ijFrame) {frame = ijFrame;model = new EditModel(frame);}//-------- 侦听器事件----------------//public void actionPerformed(ActionEvent e) {if (e.getSource()==frame.itemNew) {model.newFile();} else if (e.getSource()==frame.itemOpen) {model.openFile();} else if (e.getSource()==frame.itemSave) {model.saveFile();} else if (e.getSource()==frame.itemSaveAs) {model.saveAsFile();} else if (e.getSource()==frame.itemExit) {model.exit();} else if (e.getSource()==frame.itemPaste||e.getSource()==frame.popupMenu_Paste) { frame.textArea.paste();}else if (e.getSource()==frame.itemDelete||e.getSource()==frame.popupMenu_Delete) { frame.textArea.requestFocus();frame.textArea.replaceRange("", frame.textArea.getSelectionStart(), frame.textArea.getSelectionEnd());}else if (e.getSource()==frame.itemSelectAll||e.getSource()==frame.popupMenu_SelectAll) { frame.textArea.selectAll();} else if (e.getSource()==frame.itemFont) {model.setTextFont();} else if (e.getSource()==frame.itemFind) {model.find();} else if (e.getSource()==frame.itemReplace) {model.replace();} else if (e.getSource()==frame.itemCut||e.getSource()==frame.popupMenu_Cut) {frame.textArea.cut();} else if (e.getSource()==frame.itemCopy||e.getSource()==frame.popupMenu_Copy) {frame.textArea.copy();} else if (e.getSource()==frame.itemUndo||e.getSource()==frame.popupMenu_Undo) {try {if (um.canUndo()) {um.undo();}} catch (CannotUndoException ex) {}}}public void insertUpdate(DocumentEvent e) {model.setFileIsDirty(true);setUndoMenu();}public void removeUpdate(DocumentEvent e) {model.setFileIsDirty(true);setUndoMenu();}public void changedUpdate(DocumentEvent e) {model.setFileIsDirty(true);setUndoMenu();}// 设置是否使Undo按钮有效private void setUndoMenu() {if (um.canUndo()) {frame.itemUndo.setEnabled(true);frame.popupMenu_Undo.setEnabled(true);} else {frame.itemUndo.setEnabled(false);frame.popupMenu_Undo.setEnabled(false);}}public void undoableEditHappened(UndoableEditEvent e) {um.addEdit(e.getEdit());}public void windowOpened(WindowEvent e) {}public void windowClosed(WindowEvent e) {}public void windowIconified(WindowEvent e) {}public void windowDeiconified(WindowEvent e) {}public void windowActivated(WindowEvent e) {}public void windowDeactivated(WindowEvent e) {}public void windowClosing(WindowEvent e) { model.exit(); }}import java.io.*;import javax.swing.*;public class EditModel {IJMFrame ijMFrame;private boolean isDirty = false;private static final int YES = 1;private static final int NO =2;private static final int CANCEL = 3;private static final int ERROR = -1;File file ;public EditModel(IJMFrame ijEdit) {this.ijMFrame = ijEdit;{try {UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());} catch (ClassNotFoundException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (UnsupportedLookAndFeelException e) {e.printStackTrace();}}}public void newFile() {int answer = DirtyToHint();if (answer == YES || answer == NO) {ijMFrame.textArea.setText("");ijMFrame.setTitle("无标题");setFileIsDirty(false);}}public void openFile() {int answer = DirtyToHint();if (answer == YES || answer == NO) {JFileChooser fileChooser = new JFileChooser();int choice = fileChooser.showOpenDialog(ijMFrame);if (choice == JFileChooser.APPROVE_OPTION) {file = fileChooser.getSelectedFile();try {BufferedReader br = new BufferedReader(new FileReader(file));String temp = null;StringBuffer text = new StringBuffer();while (!((temp = br.readLine()) == null)) {text.append(temp);text.append('\n');}ijMFrame.textArea.setText(text.toString());ijMFrame.setTitle(file.getName());br.close();setFileIsDirty(false);} catch (FileNotFoundException fnfe) {JOptionPane.showMessageDialog(ijMFrame, "没有找到该文件", "错误",JOptionPane.ERROR_MESSAGE);} catch (IOException ioe) {JOptionPane.showMessageDialog(ijMFrame, "读取文件出错", "错误",JOptionPane.ERROR_MESSAGE);}}}}public boolean saveFile() {boolean result = false;if (!(file == null)) {try {FileWriter fw = new FileWriter(file);String text = ijMFrame.textArea.getText();fw.write(text);fw.flush();fw.close();result = true;setFileIsDirty(false);} catch (IOException ioe) {JOptionPane.showMessageDialog(ijMFrame, "保存文件出错", "错误",JOptionPane.ERROR_MESSAGE);result = false;}} else {saveAsFile();}return result;}public boolean saveAsFile() {boolean result = false;JFileChooser fileChooser = new JFileChooser();int choice = fileChooser.showSaveDialog(ijMFrame);if (choice == JFileChooser.APPROVE_OPTION) {file = fileChooser.getSelectedFile();result = saveFile();}return result;}public void exit() {int answer;answer = DirtyToHint();if ((answer == YES) || (answer == NO)) {System.exit(0);} else if (answer == ERROR) {System.err.println("发生错误");}}//返回文档是否被修改的布尔值public boolean getFileIsDirty() {return isDirty;}public void setFileIsDirty(boolean Dirty) {this.isDirty = Dirty;}//检测是否做过修改public int DirtyToHint() {int result = ERROR;if (getFileIsDirty()) {int choice = JOptionPane.showConfirmDialog(ijMFrame, "文档已经被修改,是否保存?", "提示",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);switch (choice) {case JOptionPane.YES_OPTION:if (saveFile()) {result = YES;} else {result =CANCEL;}break;case JOptionPane.NO_OPTION:result = NO;break;default:result =CANCEL;break;}} else {result = NO;}return result;}public void setTextFont() {JFontChooser font = new JFontChooser(ijMFrame, null);int answer = font.showDialog();if (answer == JFontChooser.APPROVE_OPTION) {ijMFrame.textArea.setFont(font.getFont());}}public void find() {JFindDialog findDlg = new JFindDialog(ijMFrame, ijMFrame.textArea);findDlg.showFindDialog();}public void replace() {JFindDialog findDlg = new JFindDialog(ijMFrame, ijMFrame.textArea);findDlg.showReplaceDialog();}}import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;import javax.swing.text.BadLocationException;public class JFindDialog extends JDialog {JPanel panel;JButton btnFind = new JButton("查找");JButton btnReplace = new JButton("替换");JButton btnCancel = new JButton("关闭");JTextField txtFind = new JTextField(20);JTextField txtReplace = new JTextField(20);JLabel lab1=new JLabel("查找:");JLabel lab2=new JLabel("替换:");JRadioButton btnFindForward = new JRadioButton("向下查找", true); JRadioButton btnFindBackward = new JRadioButton("向上查找", false); ButtonGroup btnGroup = new ButtonGroup();JTextArea findArea;public JFindDialog(JFrame owner, JTextArea findArea) {super(owner, "查找和替换", true);//-- 设置界面--//panel = (JPanel)this.getContentPane();JPanel panelCenter = new JPanel();JPanel panelBottom = new JPanel();panel.add(panelCenter, BorderLayout.CENTER);panel.add(panelBottom, BorderLayout.SOUTH);JPanel panel01 = new JPanel();panelCenter.add(panel01);JPanel pan1=new JPanel();JPanel pan2=new JPanel();pan1.add(lab1);pan1.add(txtFind);pan2.add(lab2);pan2.add(txtReplace);panel01.add(pan1, BorderLayout.NORTH);panel01.add(pan2, BorderLayout.SOUTH);panel01.setLayout(new GridLayout(2,1));JPanel panel02 = new JPanel();panelCenter.add(panel02);Box box2 = Box.createV erticalBox();panel02.add(box2);box2.add(btnFind);box2.add(btnReplace);box2.add(btnCancel);panelBottom.add(btnFindForward);panelBottom.add(btnFindBackward);btnGroup.add(btnFindForward);btnGroup.add(btnFindBackward);this.getRootPane().setDefaultButton(btnFind);//------------------------//btnFind.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {if (!find()) {JOptionPane.showMessageDialog(null, "找不到\"" + txtFind.getText() + "\"","提示", RMA TION_MESSAGE);}}});btnReplace.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {if (!replace()) {JOptionPane.showMessageDialog(null, "找不到\"" + txtFind.getText() + "\"", "提示", RMA TION_MESSAGE);}}});btnCancel.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {close();}});this.pack();this.setLocationRelativeTo(owner);}public void showFindDialog() {btnReplace.setVisible(false);txtReplace.setVisible(false);lab2.setVisible(false);this.setVisible(true);}public void showReplaceDialog() {btnReplace.setVisible(true);txtReplace.setVisible(true);this.setVisible(true);}private void close() {this.dispose();}protected boolean find() {boolean result = false;String findStr = txtFind.getText();int findStrLen = findStr.length();int pos = 0;/* 如果是向下查找,查找起点就是SelectionEnd;如果是向上查找,查找起点就是SelectionStart - 1。