河北北方学院信息科学与工程学院《Java程序设计》实验报告实验学期 2014 至 2015 学年第 2 学期学生所在系部信息科学与工程学院年级 2012 专业班级电子三班学生姓名冯洋学号 201242220 任课教师实验成绩实验七 GUI标准组件及事件处理一、课程设计目的:《面向对象程序设计》是一门实践性很强的计算机专业基础课程,课程设计是学习完该课程后进行的一次较全面的综合练习。
其目的在于通过实践加深学生对面向对象程序设计的理论、方法和基础知识的理解,掌握使用Java语言进行面向对象设计的基本方法,提高运用面向对象知识分析实际问题、解决实际问题的能力,提高学生的应用能力。
二、实验要求:设计一个简单的文本编辑器,具有如下基本功能:1)所见即所得的文本输入;2)能方便地选中文本、复制、删除和插入文本;3)具有一般编辑器所具有的查找和替换功能;4)简单的排版,如设置字体和字号等。
三、课程设计说明:1、需求分析:简单文本编辑器提供给用户基本的纯文本编辑功能,能够将用户录入的文本存储到本地磁盘中。
能够读取磁盘中现有的纯文本文件,以及方便用户进行需要的编辑功能。
文件操作能够实现新建、保存、打开文档等,编辑操作能过实现文本的剪贴、复制、粘贴等,格式操作能过实现字体设置、背景等,帮助操作能够实现关于主题的查看等功能2、概要设计:(一)其基本功能包括:①基本的文本操作功能。
包括新建,保存,打开,保存。
②基本的编辑功能。
包括复制,剪贴,粘贴。
③基本的格式功能,字体。
④简单的帮助,关于主题。
(二)主要的组件包括:①基本的Frame框架;②菜单;③打开文件对话框;④保存文件对话框;⑤颜色对话框;⑥简单的帮助框架。
3、程序说明:整个记事本分成:Jframe程序主体框架,Jmenu菜单栏、JtextArea文本输入区、PopupMenu 右键菜单、JscrollPane滚动条、FonDialog字体类等。
本程序中首先定义一个Java Yang类继承JFrame作为最底层容器。
要想记事本完成需求分析中相应的功能,还必须添加事件监听器。
事件监听器不仅要添加在菜单栏和内容输入区,还需加在容器中。
本程序中ActListener实现了ActionListener接口,用来监听并处理所有菜单项和内容输入区为事件源的事件。
另外,还用来WindowListener来监听处理容器关闭触发的事件,WindowListener继承了WindowsAdapter类并覆盖了WindowsClosing方法。
四、程序调试:1、调试分析:(1)关于打开、保存和退出我运用了文件对话框, openFileDialog、saveFileDialog和System.exit()以及文件输入输出流来实现,新建功能我选用了 textArea.setText()方法.(2)对于剪贴,粘贴,复制的实现则用复制String text = textArea.getSelectedText();StringSelection selection= new StringSelection(text);clipboard.setContents(selection,null);粘贴Transferable contents = clipboard.getContents(this);if(contents==null) return;String text;text="";try{ text = (String)contents.getTransferData(DataFlavor.stringFlavor);}catch(Exception ex){}textArea.replaceRange(text,textArea.getSelectionStart(),textArea.getSelectionEn d());(3)至于字体功能的实现,则是新建了一个字体类,在这个类中设置了字形,字体以及大小并且有字体样式可预览用户当前的设置。
FlowLayout()设置布局,setSize()设置大小add ()添加需要用的原件。
添加监听器获取选择用户的字号大小public void itemStateChanged(ItemEvent event) {size = (new Integer((String) event.getItem()).intValue());setCustomFont(new Font(name, type, size));}设置字体private void setCustomFont(Font customFont) {this.customFont = customFont;area.setFont(customFont);area.revalidate();}获取字体public Font getCustomFont() {return (this.customFont);}附录:源代码//记事本主体类import java.awt.event.*;import java.awt.*;import java.io.*;import java.awt.datatransfer.*;import javax.swing.*;import java.awt.print.PrinterException;public class MiniNote extends JFrame implements ActionListener {JMenuBar menuBar = new JMenuBar();JMenu file = new JMenu("文件(F)"), //菜单edit = new JMenu("编辑(E)"),format = new JMenu("格式(O)"),view = new JMenu("查看(V)"),help = new JMenu("帮助(H)");JMenuItem[] menuItem ={ //菜单下拉项new JMenuItem("新建(N)"),new JMenuItem("打开(O)"),new JMenuItem("保存(S)"),new JMenuItem("打印(P)"),new JMenuItem("全选(A)"),new JMenuItem("复制(C)"),new JMenuItem("剪切(T)"),new JMenuItem("粘贴(P)"),new JMenuItem("自动换行(W)"),new JMenuItem("字体(F)"),new JMenuItem("状态栏(S)"),new JMenuItem("帮助主题(H)"),new JMenuItem("关于记事本(A)"),new JMenuItem("页面设置(U)"),new JMenuItem("退出(X)"),new JMenuItem("查找(F)"),new JMenuItem("查找下一个(N)"),new JMenuItem("替换(R)")};JPopupMenu popupMenu = new JPopupMenu(); ;//右键菜单JMenuItem [] menuItem1 ={new JMenuItem("撤销(Z)"),new JMenuItem("剪切(X)"),new JMenuItem("复制(C)"),new JMenuItem("粘贴(V)"),new JMenuItem("删除(D)"),new JMenuItem("全选(A)"),};private JTextArea textArea ; //文本区域private JScrollPane js ; //滚动条private JPanel jp ;private FileDialog openFileDialog ; //打开保存对话框private FileDialog saveFileDialog ;private Toolkit toolKit; //获取默认工具包。
private Clipboard clipboard; //获取系统剪切板private String fileName; //设置默认的文件名/*** MiniEdit 方法定义** 实现记事本初始化***/public MiniNote() {fileName = "无标题";toolKit = Toolkit.getDefaultToolkit();clipboard = toolKit.getSystemClipboard();textArea =new JTextArea();js = new JScrollPane(textArea);jp = new JPanel();openFileDialog = new FileDialog(this,"打开",FileDialog.LOAD);saveFileDialog = new FileDialog(this,"另存为",FileDialog.SAVE);js.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); jp.setLayout(new GridLayout(1,1));jp.add(js);textArea.setComponentPopupMenu(popupMenu); //文本区域添加右键textArea.add(popupMenu);add(jp);setTitle("迷你记事本");setFont(new Font("Times New Roman",Font.PLAIN,15));setBackground(Color.white);setSize(800,600);setJMenuBar(menuBar);menuBar.add(file);menuBar.add(edit);menuBar.add(format);menuBar.add(view);menuBar.add(help);for(int i=0;i<4;i++){file.add(menuItem[i]);edit.add(menuItem[i+4]);}for(int i=0;i<3;++i){edit.add(menuItem[i+15]);}for(int i=0;i<2;++i){format.add(menuItem[i+8]);help.add(menuItem[i+11]);}view.add(menuItem[10]);file.add(menuItem[14]);for(int i=0; i<6;++i){popupMenu.add(menuItem1[i]);}//窗口监听addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ e.getWindow().dispose();System.exit(0);}});//注册各个菜单项的事件监听器for(int i=0;i<menuItem.length;i++){menuItem[i].addActionListener(this);}for(int i=0;i<menuItem1.length;i++){menuItem1[i].addActionListener(this);}}/*** actionPerformed 方法定义** 动作触发实现***/public void actionPerformed(ActionEvent e) {Object eventSource = e.getSource();if(eventSource == menuItem[0]) //新建动作{textArea.setText("");}else if(eventSource == menuItem[1])//打开动作{openFileDialog.setVisible(true);fileName = openFileDialog.getDirectory()+openFileDialog.getFile();if(fileName != null){openFile(fileName);}}else if(eventSource ==menuItem[2])//保存动作{saveFileDialog.setVisible(true);fileName = saveFileDialog.getDirectory()+saveFileDialog.getFile(); if(fileName !=null){writeFile(fileName);}}else if(eventSource==menuItem[14])//退出动作{System.exit(0);}else if(eventSource == menuItem[4]||eventSource == menuItem1[5]) //全选动作{textArea.selectAll();}else if(eventSource == menuItem[5]||eventSource == menuItem1[2]) //复制动作{String text = textArea.getSelectedText();StringSelection selection= new StringSelection(text);clipboard.setContents(selection,null);}else if(eventSource == menuItem[6]||eventSource == menuItem1[1])//剪切动作 {String text = textArea.getSelectedText();StringSelection selection = new StringSelection(text);clipboard.setContents(selection,null);textArea.replaceRange("", textArea.getSelectionStart(),textArea.getSelectionEnd());}else if(eventSource == menuItem[7]||eventSource == menuItem1[3])//粘贴动作 {Transferable contents = clipboard.getContents(this);if(contents==null) return;String text;text="";try{text =(String)contents.getTransferData(DataFlavor.stringFlavor);}catch(Exception ex){}textArea.replaceRange(text,textArea.getSelectionStart(),textArea.getSelectionEnd());}else if(eventSource == menuItem[8]) //自动换行{if (textArea.getLineWrap()) textArea.setLineWrap(false);else textArea.setLineWrap(true);}else if(eventSource == menuItem[9]) //字体{//实例化字体类FontDialog fontdialog = new FontDialog(new JFrame(),"字体",true);textArea.setFont(fontdialog.showFontDialog()); //设置字体 }else if(eventSource == menuItem[11]) //帮助{try{String filePath = "C:/WINDOWS/Help/notepad.hlp";Runtime.getRuntime().exec("cmd.exe /c "+filePath);}catch(Exception ee){JOptionPane.showMessageDialog(this,"打开系统的记事本帮助文件出错!","错误信息",RMATION_MESSAGE);}}else if(eventSource == menuItem[12]) //关于记事本{String help = "记事本版本1.0\n操作系统:WIN 8 \n编译器:eclipse\n 版权"+ "所有: ESTON YANG \n最终解释权归本人所有"+ "" +"\nBuild By 冯洋"+ "\n课程设计:JAVA";JOptionPane.showConfirmDialog(null, help, "关于记事本",JOptionPane.DEFAULT_OPTION, RMATION_MESSAGE);}else if(eventSource == menuItem[15]||eventSource == menuItem[16]) //查找下一个{search();}else if(eventSource == menuItem[17]) //替换{substitude();}else if(eventSource == menuItem[3]) //打印{try{textArea.print();}catch (PrinterException e1){e1.printStackTrace();}}}/*** openFile方法** 从TXT读进数据到记事本***/public void openFile(String fileName){try{File file = new File(fileName);FileReader readIn = new FileReader(file);int size = (int)file.length();int charsRead = 0;char[] content = new char[size];while(readIn.ready()){charsRead += readIn.read(content,charsRead,size-charsRead); }readIn.close();textArea.setText(new String(content,0,charsRead));}catch(Exception e){System.out.println("Error opening file!");}}/*** saveFile方法** 从记事本写进数据到TXT***/public void writeFile(String fileName){try{File file = new File(fileName);FileWriter write = new FileWriter(file);write.write(textArea.getText());write.close();}catch(Exception e){System.out.println("Error closing file!");}}/*** substitude方法** 实现替换功能**/public void substitude() {final JDialog findDialog = new JDialog(this, "查找与替换", true);Container con = findDialog.getContentPane();con.setLayout(new FlowLayout(FlowLayout.LEFT));JLabel searchContentLabel = new JLabel("查找内容(N) :");JLabel replaceContentLabel = new JLabel("替换为(P) :");final JTextField findText = new JTextField(30);final JTextField replaceText = new JTextField(30);final JCheckBox matchcase = new JCheckBox("区分大小写(C)");ButtonGroup bGroup = new ButtonGroup();final JRadioButton up = new JRadioButton("向上(U)");final JRadioButton down = new JRadioButton("向下(D)");down.setSelected(true); //默认向下搜索bGroup.add(up);bGroup.add(down);JButton searchNext = new JButton("查找下一个(F)");JButton replace = new JButton("替换(R)");final JButton replaceAll = new JButton("全部替换(A)");//"替换"按钮的事件处理replace.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {if (replaceText.getText().length() == 0 &&textArea.getSelectedText() != null)textArea.replaceSelection("");if (replaceText.getText().length() > 0 &&textArea.getSelectedText() != null)textArea.replaceSelection(replaceText.getText());}});//"替换全部"按钮的事件处理replaceAll.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {textArea.setCaretPosition(0); //将光标放到编辑区开头int a = 0, b = 0, replaceCount = 0;if (findText.getText().length() == 0){JOptionPane.showMessageDialog(findDialog, "请填写查找内容!", "提示",JOptionPane.WARNING_MESSAGE);findText.requestFocus(true);return;}while (a > -1){int FindStartPos = textArea.getCaretPosition();//获取光标位置 String str1, str2, str3, str4, strA, strB;str1 = textArea.getText();str2 = str1.toLowerCase();str3 = findText.getText();str4 = str3.toLowerCase();if (matchcase.isSelected()) //大小写区分{strA = str1;strB = str3;}else{strA = str2;strB = str4;}if (up.isSelected()) //向上搜索{if (textArea.getSelectedText() == null){a = stIndexOf(strB, FindStartPos - 1);}else{a = stIndexOf(strB, FindStartPos-findText.getText().length() - 1);}}else //向下搜索{if (textArea.getSelectedText() == null){a = strA.indexOf(strB, FindStartPos);}else{a = strA.indexOf(strB, FindStartPos-findText.getText().length() + 1);}}if (a > -1){if (up.isSelected()){textArea.setCaretPosition(a);b = findText.getText().length();textArea.select(a, a + b);}else if (down.isSelected()){textArea.setCaretPosition(a);b = findText.getText().length();textArea.select(a, a + b);}}else{if (replaceCount == 0){JOptionPane.showMessageDialog(findDialog,"找不到您查找的内容!", "记事本",RMATION_MESSAGE);}else{JOptionPane.showMessageDialog(findDialog, "成功替换"+ replaceCount + "个匹配内容!", "替换成功",RMATION_MESSAGE);}}if (replaceText.getText().length() == 0&&textArea.getSelectedText() != null) //用空字符代替选定内容 {textArea.replaceSelection("");replaceCount++;}if (replaceText.getText().length() > 0&&textArea.getSelectedText() != null) //用指定字符代替选定内容{textArea.replaceSelection(replaceText.getText());replaceCount++;}}//end while}});//"查找下一个"按钮事件处理searchNext.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {int a = 0, b = 0;int FindStartPos = textArea.getCaretPosition();String str1, str2, str3, str4, strA, strB;str1 = textArea.getText();str2 = str1.toLowerCase();str3 = findText.getText();str4 = str3.toLowerCase();//"区分大小写"的CheckBox被选中if (matchcase.isSelected()) //区分大小写{strA = str1;strB = str3;}else //不区分大小写{strA = str2;strB = str4;}if (up.isSelected()) //向上搜索{if (textArea.getSelectedText() == null){a = stIndexOf(strB, FindStartPos - 1);}else{a = stIndexOf(strB, FindStartPos -findText.getText().length() - 1);}}else if (down.isSelected()){if (textArea.getSelectedText() == null){a = strA.indexOf(strB, FindStartPos);}else{a = strA.indexOf(strB, FindStartPos - findText.getText().length() + 1);}}if (a > -1){if (up.isSelected()){textArea.setCaretPosition(a);b = findText.getText().length();textArea.select(a, a + b);}else if (down.isSelected()){textArea.setCaretPosition(a);b = findText.getText().length();textArea.select(a, a + b);}}else{JOptionPane.showMessageDialog(null, "找不到您查找的内容!", "记事本", RMATION_MESSAGE);}}});//"取消"按钮及事件处理JButton cancel = new JButton("取消");cancel.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {findDialog.dispose();}});//创建"查找与替换"对话框的界面JPanel bottomPanel = new JPanel();JPanel centerPanel = new JPanel();JPanel topPanel = new JPanel();JPanel direction = new JPanel();direction.setBorder(BorderFactory.createTitledBorder("方向")); direction.add(up);direction.add(down);JPanel replacePanel = new JPanel();replacePanel.setLayout(new GridLayout(1, 2));replacePanel.add(searchNext);replacePanel.add(replace);replacePanel.add(replaceAll);replacePanel.add(cancel);topPanel.add(searchContentLabel);topPanel.add(findText);centerPanel.add(replaceContentLabel);centerPanel.add(replaceText);centerPanel.add(replacePanel);bottomPanel.add(matchcase);bottomPanel.add(direction);con.add(replacePanel);con.add(topPanel);con.add(centerPanel);con.add(bottomPanel);//设置"查找与替换"对话框的大小、可更改大小(否)、位置和可见性findDialog.setSize(550, 240);findDialog.setResizable(true);findDialog.setLocation(230, 280);findDialog.setVisible(true);}//方法mySearch()结束/*** search方法** 实现查找功能**/public void search() {final JDialog findDialog = new JDialog(this, "查找下一个", true);Container con = findDialog.getContentPane();con.setLayout(new FlowLayout(FlowLayout.LEFT));JLabel searchContentLabel = new JLabel(" 查找内容(N) :");final JTextField findText = new JTextField(17);final JCheckBox matchcase = new JCheckBox("区分大小写(C)");ButtonGroup bGroup = new ButtonGroup();final JRadioButton up = new JRadioButton("向上(U)");final JRadioButton down = new JRadioButton("向下(D)");down.setSelected(true); //默认向下搜索bGroup.add(up);bGroup.add(down);JButton searchNext = new JButton("查找下一个(F)");//"查找下一个"按钮事件处理searchNext.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {int a = 0, b = 0;int FindStartPos = textArea.getCaretPosition();String str1, str2, str3, str4, strA, strB;str1 = textArea.getText();str2 = str1.toLowerCase();str3 = findText.getText();str4 = str3.toLowerCase();//"区分大小写"的CheckBox被选中if (matchcase.isSelected()) //不区分大小写{strA = str1;strB = str3;}else //区分大小写{strA = str2;strB = str4;if (up.isSelected()) //向上搜索{if (textArea.getSelectedText() == null){a = stIndexOf(strB, FindStartPos - 1);}else{a = stIndexOf(strB, FindStartPos -findText.getText().length() - 1);}}else if (down.isSelected()){if (textArea.getSelectedText() == null){a = strA.indexOf(strB, FindStartPos);}else{a = strA.indexOf(strB, FindStartPos - findText.getText().length() + 1);}}if (a > -1){if (up.isSelected()){textArea.setCaretPosition(a);b = findText.getText().length();textArea.select(a, a + b);}else if (down.isSelected()){textArea.setCaretPosition(a);b = findText.getText().length();textArea.select(a, a + b);}}else{JOptionPane.showMessageDialog(null, "找不到您查找的内容!", "记事本", RMATION_MESSAGE);}});//"取消"按钮及事件处理JButton cancel = new JButton(" 取消 ");cancel.addActionListener(new ActionListener() {public void actionPerformed(ActionEvent e) {findDialog.dispose();}});//创建"替换"对话框的界面JPanel bottomPanel = new JPanel();JPanel centerPanel = new JPanel();JPanel topPanel = new JPanel();JPanel direction = new JPanel();direction.setBorder(BorderFactory.createTitledBorder("方向"));direction.add(up);direction.add(down);topPanel.add(searchContentLabel);topPanel.add(findText);topPanel.add(searchNext);bottomPanel.add(matchcase);bottomPanel.add(direction);bottomPanel.add(cancel);con.add(topPanel);con.add(centerPanel);con.add(bottomPanel);//设置"替换"对话框的大小、可更改大小(否)、位置和可见性findDialog.setSize(425, 200);findDialog.setResizable(true);findDialog.setLocation(230, 280);findDialog.setVisible(true);}/*** 主函数*****/public static void main(String[] args) {MiniNote note = new MiniNote();note.setVisible(true);}} //字体类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 java.awt.*;import javax.swing.*;import java.awt.event.*;import javax.swing.border.*;import java.util.*;public class FontDialog {private Dialog fontdialog;private JButton okButton, cancelButton;private int width = 480;private int height = 250;private String name = "Serif";private int type = 0;private int size = 12;private Font customFont = new Font("宋体", Font.ITALIC, 12);private boolean okpressed = false;private boolean cancelpressed = false;private JLabel lbl1 = new JLabel("字体:");private JLabel lbl2 = new JLabel("字形:");private JLabel lbl3 = new JLabel("大小:");private JTextArea area;String[] zx = { "常规", "加粗", "斜体", "基线" };String[] dx = {"8" , "9" , "10", "12", "14", "15", "16", "18","20", "21", "22", "24", "26", "28", "30", "36","48", "54","72" , "89"};JLabel lbl = new JLabel("字体样式Style");private JComboBox cb1, cb3 = new JComboBox(dx), cb2 = new JComboBox(zx); private String[] zt;public FontDialog(Frame owner, String title, boolean modal) {init();fontdialog = new Dialog(owner, title, modal);fontdialog.setLocation(owner.getLocation());fontdialog.setLayout(new FlowLayout());fontdialog.setSize(getWidth(), getHeight());fontdialog.add(lbl1);fontdialog.add(cb1);fontdialog.add(lbl2);fontdialog.add(cb2);fontdialog.add(lbl3);fontdialog.add(cb3);fontdialog.add(okButton);fontdialog.add(cancelButton);fontdialog.add(area);fontdialog.setResizable(false);fontdialog.setAlwaysOnTop(true);cancelButton.addActionListener(new fontListener());okButton.addActionListener(new fontListener());fontdialog.addWindowListener(new fontListener());cb1.addItemListener(new ItemListener() { //字体动作 public void itemStateChanged(ItemEvent event) { //添加监听器获取选择用户的字体类型name = (String) event.getItem();setCustomFont(new Font(name, type, size));}});cb2.addItemListener(new ItemListener() { //字形动作 public void itemStateChanged(ItemEvent event) { //添加监听器获取选择用户的字形String s = (String) event.getItem();if (s.equals("常规")){type = Font.PLAIN;setCustomFont(new Font(name, type, size));}else if (s.equals("加粗")){type = Font.BOLD;setCustomFont(new Font(name, type, size));}else if (s.equals("斜体")){type = Font.ITALIC;setCustomFont(new Font(name, type, size));}else{type = Font.CENTER_BASELINE;setCustomFont(new Font(name, type, size));}}});cb3.addItemListener(new ItemListener() { //大小动作 public void itemStateChanged(ItemEvent event) { //添加监听器获取选择用户的字号大小size = (new Integer((String) event.getItem()).intValue());setCustomFont(new Font(name, type, size));}});}public Font showFontDialog() {fontdialog.setVisible(true);if (okpressed){return getCustomFont();}else{return customFont;}}private void init() { //初始化okButton = new JButton("确定");cancelButton = new JButton("取消");GraphicsEnvironment ge =GraphicsEnvironment.getLocalGraphicsEnvironment();zt = ge.getAvailableFontFamilyNames();cb1 = new JComboBox(zt);cb1.setMaximumRowCount(6);area = new JTextArea(6, 30);cb3 = new JComboBox(dx);cb3.setMaximumRowCount(6);okButton.setFocusable(true);area.setEditable(false);area.setText(new Date().toString());area.setBorder(new TitledBorder("字体样式"));}public void setWidth(int width){this.width = width;}public void setHeight(int height){this.height = height;}private int getWidth(){return (this.width);}private int getHeight(){return (this.height);}private void setCustomFont(Font customFont) //设置字体{this.customFont = customFont;area.setFont(customFont);area.revalidate();}public String toString(){return FontDialog.class.toString();}public Font getCustomFont() //获取字体{return (this.customFont);}private class fontListener extends WindowAdapter implements ActionListener //监听事件类{public void windowClosing(WindowEvent e){fontdialog.dispose();}public void actionPerformed(ActionEvent e){if (e.getSource() == cancelButton){fontdialog.dispose();cancelpressed = true;}else if (e.getSource() == okButton){okpressed = true;setCustomFont(new Font(name, type, size));fontdialog.dispose();}}}}。