此程序是在前面程序的基础上增加响应事件的完整程序,为了不让程序太长,我想将快捷键(右键弹出菜单)的事件专门放在一个类里面,但遇到了一个问题,发现不好将原来类EditorJFrame3里的popupmenu和text成员变量参数传递到专门的事件类中,于是想出了一个解决办法:重新构造一个类似JTextArea的JTextAreaMenu(继承JTextArea)类,他比JTextArea类的功能更强大,有复制、黏贴、剪切、自动换行等新的功能。
这个综合程序实现了记事本文件的打开、保存、另存为,文本域字体和颜色的设置,鼠标右键实现的复制、粘贴、剪切等详细功能。美中不足的是,打开的文件在JTextArea中显示时,若打开的是txt文件没什么问题,但若是其他文件则会显示乱码。此问题我暂时还解决不了,忘高人指点!
源程序:
import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.GraphicsEnvironment; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JRadioButton; import javax.swing.JRadioButtonMenuItem; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JToolBar; import javax.swing.KeyStroke; import myjtextarea.JTextAreaMenu; public class EditorJFrame3 extends JFrame implements ActionListener{ private JComboBox combox_name,combox_size;//字体、字号组合框 private JCheckBox checkb_bold,checkb_italic;//粗体斜体复选框 JCheckBoxMenuItem bold,italic;//粗体、斜体复选菜单项 private JRadioButton radiob_color[];//颜色单选按钮 private JTextArea text; private Color color; private File file; public EditorJFrame3(){ super("文本编辑器");//默认BorderLayout布局 Dimension dim = getToolkit().getScreenSize(); setBounds(dim.width/4,dim.height/4,dim.width/2,dim.height/2); setDefaultCloseOperation(EXIT_ON_CLOSE); text = new JTextAreaMenu("Welcome 欢迎"); add(new JScrollPane(text)); addmyMenu();//菜单栏 addmyJToolbar();//工具栏 setVisible(true); } private void addmyMenu(){//菜单栏部分 JMenuBar menubar = new JMenuBar();//菜单栏 setJMenuBar(menubar); String menustr[] = {"文件","编辑","帮助"}; JMenu menu[]=new JMenu[menustr.length];//菜单 for(int i=0;i<menustr.length;i++){ menu[i] = new JMenu(menustr[i]); menubar.add(menu[i]); } JMenuItem open = new JMenuItem("打开",new ImageIcon("images/open.jpg")); open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK));//快捷键 menu[0].add(open);//菜单项加入到菜单"文件"里 open.addActionListener(this); JMenuItem save = new JMenuItem("保存",new ImageIcon("images/open.jpg")); menu[0].add(save); save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK)); save.addActionListener(this); JMenuItem saveas = new JMenuItem("另存为"); saveas.addActionListener(this); menu[0].add(saveas); menu[0].addSeparator();//添加分割线 JMenuItem menuitem_exit = new JMenuItem("退出"); menu[0].add(menuitem_exit); menuitem_exit.addActionListener(this);////////// //注册事件 JMenu menu_style = new JMenu("字形");//菜单 bold = new JCheckBoxMenuItem("粗体"); bold.addActionListener(this); menu_style.add(bold);//复选框菜单项加入到菜单中 italic = new JCheckBoxMenuItem("斜体"); italic.addActionListener(this); menu_style.add(italic); menu[1].add(menu_style); JMenu menu_color = new JMenu("颜色");//菜单 menu[1].add(menu_color); ButtonGroup buttongroup = new ButtonGroup();//按钮组 String colorstr[]={"红","绿","蓝"}; JRadioButtonMenuItem rbmi_color[]=new JRadioButtonMenuItem[colorstr.length];//单选菜单项 for(int i =0;i<colorstr.length;i++){ rbmi_color[i] = new JRadioButtonMenuItem(colorstr[i]); buttongroup.add(rbmi_color[i]);//单选菜单项添加到按钮组中 // menu_color.add(rbmi_color[i]);//单选菜单项添加到菜单中 } JMenuItem author = new JMenuItem("关于作者"); author.addActionListener(this); menu[2].add(author); } private void addmyJToolbar(){//工具栏部分 JToolBar toolbar=new JToolBar(); //创建工具栏,默认水平方向 add(toolbar,"North"); //工具栏添加到框架内容窗格北部 GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment(); String[] fontsName=ge.getAvailableFontFamilyNames(); //获得系统字体 combox_name = new JComboBox(fontsName); //组合框显示系统字体 combox_name.addActionListener(this);////////// //注册事件 toolbar.add(combox_name);//字体组合框加到工具栏里 //设置组合框的宽度260和高度30 combox_name.setMaximumSize(new Dimension(260,30)); String sizestr[]={"20","30","40","50","60","70"}; combox_size = new JComboBox(sizestr); //数组加到字号组合框 //组合框默认不可编辑 combox_size.setEditable(true); //设置组合框可编辑 combox_size.addActionListener(this);////////// //注册事件 combox_size.setMaximumSize(new Dimension(180,30)); toolbar.add(combox_size);//字体组合框加到工具栏里 checkb_bold = new JCheckBox("粗体"); //字形复选框 toolbar.add(checkb_bold); checkb_bold.addActionListener(this);////////// //注册事件 checkb_italic = new JCheckBox("斜体"); toolbar.add(checkb_italic); checkb_italic.addActionListener(this);////////// //注册事件 String colorstr[]={"红","绿","蓝"}; ButtonGroup bgroup_color = new ButtonGroup(); //按钮组 radiob_color = new JRadioButton[colorstr.length];//颜色单选按钮数组 for (int i=0; i<radiob_color.length; i++) { radiob_color[i]=new JRadioButton(colorstr[i]); //颜色单选按钮 radiob_color[i].addActionListener(this);///////////每个单选项均要注册事件 bgroup_color.add(radiob_color[i]); //单选按钮添加到按钮组 toolbar.add(radiob_color[i]); ////////单选按钮添加到工具栏 } //radiob_color[0].setSelected(true); //设置单选按钮的选中状态 } public static void main(String[] args) { new EditorJFrame3(); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JMenuItem) //单击菜单项 { if(e.getActionCommand()=="打开"){ open(); return; } if(e.getActionCommand()=="保存"){ save(); return; } if(e.getActionCommand() == "另存为"){ saveas(); return; } if (e.getActionCommand()=="退出") if (JOptionPane.showConfirmDialog(this, "终止当前程序运行?")==0) System.exit(0); //单击确认对话框中的“是”按钮,结束程序运行 if(e.getActionCommand() == "关于作者"){ AboutAuthor aboutAuthor = new AboutAuthor(); aboutAuthor.setSize(375, 200); aboutAuthor.setLocation(340, 220); aboutAuthor.setVisible(true); } } if (e.getSource() instanceof JRadioButton) //选择一个颜色单选框 { if (e.getSource()==radiob_color[0]) color = new Color(255,0,0); if (e.getSource()==radiob_color[1]) color = new Color(0,255,0); if (e.getSource()==radiob_color[2]) color = new Color(0,0,255); text.setForeground(color); //设置文本区颜色 } if (e.getSource() instanceof JComboBox || e.getSource() instanceof JCheckBox || e.getSource() == bold || e.getSource()==italic) { //组合框、复选框 int size=0; try { String fontname = (String)combox_name.getSelectedItem();//获得字体名 size = Integer.parseInt((String)combox_size.getSelectedItem());//获得字号 if (size<4 || size>120) //字号超出指定范围时,抛出异常对象 throw new Exception("SizeException"); Font font = text.getFont(); //获得文本区的当前字体对象 int style = font.getStyle(); //获得字形 if (e.getSource()==checkb_bold || e.getSource() == bold) //粗体 style = style ^ 1; //整数的位运算,异或^ if (e.getSource()==checkb_italic || e.getSource()==italic) //斜体 style = style ^ 2; text.setFont(new Font(fontname, style, size)); //设置文本区字体样式、字号大小 } catch(NumberFormatException nfe) { JOptionPane.showMessageDialog(this, "/""+(String)combox_size.getSelectedItem()+"/" 不能转换成整数,请重新输入!"); } catch(Exception ex) { if (ex.getMessage()=="SizeException") //捕获自己抛出的异常对象 JOptionPane.showMessageDialog(this, size+" 字号不合适,请重新输入!"); } finally{} } if (e.getSource()==combox_size) //单击字号组合框 { //将新输入的字号添加到组合框的下拉列表中,先要查找,不添加重复值 String size = (String)combox_size.getSelectedItem();//获得当前输入数据 int i=0, n=combox_size.getItemCount(); //n获得组合框的选项数 while (i<n && size.compareTo((String)combox_size.getItemAt(i))>=0) { //size与组合框的选项比较 if (size.compareTo((String)combox_size.getItemAt(i))==0) return ; //相同,不插入 i++; } combox_size.insertItemAt(size, i); //将size插入在组合框的第i项 } } private void open()//打开文件 { JFileChooser fc=new JFileChooser();//文件选择对话框 fc.showOpenDialog(this); file=fc.getSelectedFile();//选择的文件 try{ FileInputStream in=new FileInputStream(file);//文件字节输入流 byte[] b=new byte[in.available()]; in.read(b); //text.setLineWrap(true);text已有该性质 text.setText(new String(b)); in.close(); } catch(Exception e){} } private void save(){ FileWriter out ; try { if(file == null){ file = new File("新建文件.txt"); } out = new FileWriter(file); out.write(text.getText()); out.close(); } catch (IOException e) { // TODO: handle exception } } private void saveas() //文件另存 { JFileChooser fc=new JFileChooser(); fc.showSaveDialog(this); File file=fc.getSelectedFile(); try{ FileWriter out=new FileWriter(file); out.write(text.getText()); out.close(); }catch(Exception e){} } } package myjtextarea; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JTextArea; import javax.swing.KeyStroke; public class JTextAreaMenu extends JTextArea implements MouseListener , ActionListener{ private JPopupMenu popupmenu = null;//快捷菜单 JMenuItem popmenuitem[]; public JTextAreaMenu(){ createComponents(); } public JTextAreaMenu(String str){ super(str); createComponents(); } private void createComponents(){ setLineWrap(true); //////自动换行 popupmenu = new JPopupMenu(); String menuitemstr[]={"复制","粘贴","剪切"}; popmenuitem = new JMenuItem[menuitemstr.length]; for (int i=0; i<popmenuitem.length; i++) { popmenuitem[i] = new JMenuItem(menuitemstr[i]); //菜单项 popupmenu.add(popmenuitem[i]); /////快捷菜单项加入弹出菜单 popmenuitem[i].addActionListener(this); } popmenuitem[0].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, InputEvent.CTRL_MASK));//设置快捷键Ctrl+X popmenuitem[1].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK));//设置快捷键Ctrl+C popmenuitem[2].setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, InputEvent.CTRL_MASK));//设置快捷键Ctrl+V add(popupmenu); //弹出菜单加到文本域组件中 this.addMouseListener(this); } @Override public void mouseClicked(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) { //单击的是鼠标右键 popmenuitem[0].setEnabled(isCanCopy()); //复制启用与否 popmenuitem[1].setEnabled(isClipboardString()); //黏贴 popmenuitem[2].setEnabled(isCanCopy()); //剪切 popupmenu.show(this, e.getX(), e.getY()); //在鼠标单击处显示快捷菜单 } } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } /** * 剪切板中是否有文本数据可供粘贴 * * @return true为有文本数据 */ public boolean isClipboardString() { boolean b = false; Clipboard clipboard = this.getToolkit().getSystemClipboard(); Transferable content = clipboard.getContents(this); try { if (content.getTransferData(DataFlavor.stringFlavor) instanceof String) { b = true; } } catch (Exception e) { } return b; } /** * 文本组件中是否具备复制的条件 * * @return true为具备 */ public boolean isCanCopy() { boolean b = false; int start = this.getSelectionStart(); //返回选定文本的起始位置 int end = this.getSelectionEnd(); //返回选定文本的结束位置 if (start != end) b = true; //文本不为空返回true return b; } @Override public void actionPerformed(ActionEvent e) { String str = e.getActionCommand(); if (str.equals(popmenuitem[0].getText())) { // 复制 this.copy(); } else if (str.equals("粘贴")) { // 粘贴 this.paste(); } else if (str.equals(popmenuitem[2].getText())) { // 剪切 this.cut(); } } } import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class AboutAuthor extends JFrame{ private JLabel author; private JLabel pop,bottom; private JPanel jpanel; public AboutAuthor() { jpanel = new JPanel(); jpanel.setBackground(Color.blue);//背景色 author = new JLabel("作 者 :余 永 利"); author.setForeground(Color.white);//前景色 author.setFont(new Font("黑体", Font.PLAIN, 22));//设置字体 pop = new JLabel(new ImageIcon("images/copyright.gif")); bottom = new JLabel("学校:湖北工业大学"); bottom.setForeground(Color.white); bottom.setFont(new Font("黑体", Font.PLAIN, 22));//设置字体 jpanel.add(pop); jpanel.add(author); jpanel.add(bottom); setResizable(false);//禁止最大化 setTitle("关于作者"); add(jpanel); } }
此程序的源代码下载:http://download.csdn.net/source/3079845