Java写个简单的记事本()

本文分享了一个使用Java编写的简单记事本程序,虽然功能不全,但包含了基本的文本编辑能力。作者提到该程序在课程设计中完成,存在改进空间,如添加快捷键等功能。
摘要由CSDN通过智能技术生成

一个简单的记事本,功能不太全

直接放代码了

import java.awt.*;            //抽象窗口
import java.awt.event.*;          //窗口事件
import java.io.*;                        //输入输出流
import java.text.DateFormat;                                    //时间获取
import java.util.Date;                                          //实现对时间标签内容的赋值
import javax.swing.ButtonGroup;                                 //按钮组,保证同一时间只有一个能选中
import javax.swing.JCheckBox;                                   //组合框,提供大小和字体库的选择口
import javax.swing.JComboBox;                                   //复选框,提供字体风格的选择口,可同时多选
import javax.swing.JFrame;                                      //内容面板
import javax.swing.JLabel;                                      //标签类
import javax.swing.JRadioButton;                                //颜色按钮
import javax.swing.JScrollPane;                                 //滚动条
import javax.swing.JTextArea;                                   //多行文本域
import javax.swing.JToolBar;                                    //工具栏
import javax.swing.undo.UndoManager;                            //撤销和还原提供类
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){    //添加二级菜单,用getMenu()定位
  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 a1){            //添加监听器
  for(int i=0;i<getMenuCount();i++)                        //用双重循环添加动作监听
   for(int j=0;j<getMenu(i).getItemCount();j++)
    getMenu(i).getItem(j).addActionListener(a1);
 }
}
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 OpenData() throws IOException{                     //打开文件方法           
 fDlg.setTitle("打开");                                       //设置文件对话框的标题为打开
 fDlg.setMode(FileDialog.LOAD);                               //设置模式为打开
 fDlg.setVisible(true);                                       //设为可见
 BufferedReader br=new BufferedReader(new FileReader(getPath()));//开启文件读入
 StringBuffer sb=new StringBuffer();                             //读入文件对话框中选中文件的内容
 String aline;
 while((aline=br.readLine())!=null){                          //用append()方式读入
  sb.append(aline+'\n');
 }
 br.close();
 return sb.toString();                                        //返回
}
public void setData(String data) throws IOException{             //保存文件方法
 fDlg.setTitle("保存");                                       //设置标题为保存
 fDlg.setMode(FileDialog.LOAD);                               //设置模式为打开
 fDlg.setVisible(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);               //transferable,剪切板内容封装在其中
  try{
   return (String)content.getTransferData(DataFlavor.stringFlavor);//数据就从tranfserable中读出
  }catch(Exception ue){}                                   //有可能会出异常
  return null;
 }
}
class Time implements Runnable{                                  //时间类,用单线程,两个方法
    private JLabel lab=new JLabel();                             //声明一个标签
    public Time(JLabel lab){                                     //初始化
     this.lab=lab;
    }
 @Override
 public void run() {                                         
  while(true) {
      try {
       DateFormat kk=DateFormat.getDateTimeInstance();  //用dateformat获取时间
       lab.setText(kk.format(new Date()));              //将内容交给标签
       Thread.sleep(1000);                              //睡眠一秒
      }catch(InterruptedException iu) {iu.printStackTrace();}
  }
 }
    
}
class HelpItem{                                                  //帮助信息类,只是给出一段文字说明
 private JFrame help=new JFrame();                            //开启一个新的面板,用作文字说明 
 Font t=new Font("微软雅黑",0,26);                            //声明一个字体所有的格式
 public void  bang(){
  String separator = System.getProperty("line.separator");// 获得系统默认的分隔符
  help.setBounds(410, 250, 600, 320);                      //设置大小 位置
  help.setLayout(new BorderLayout());                      //设置布局
  help.setVisible(true);                                   //设置为可见
  TextArea helptextarea=new TextArea("版本2.11,功能如下:"+separator+separator//说明内容
    +"1.文件功能:新建,打开,保存"+separator+separator      //获得系统默认的分隔符-固定写法
    +"2.编辑功能:粘贴,赋值,剪切,清除,撤销,还原"+separator+separator
    +"3.工具栏:字体,颜色,风格,字体大小"+separator+separator
    +"感谢您的使用。");
  helptextarea.setForeground(Color.red);                   //设置字体为红色
  helptextarea.setFont(t);                                 //使用前面已经给出的字体格式
  help.add(helptextarea,"Center");                         //设置帮助面板位置为中心
 }
} 
public class pubClass extends JFrame implements ActionListener{ //主类
 private JTextArea editor=new JTextArea();                      //开一个文本域
 private MyFile mf=new MyFile(this);                            //文本类对象
 private MyClipboard cb=new MyClipboard();                      //剪切板对象
 private UndoManager undo=new UndoManager();                    //一个对象,用于撤销和恢复
 private HelpItem hp=new HelpItem();                            //帮助类对象                                 
 private String[] fontsize=new String[10];                      //字体大小数组
 private String[] fontnames;                                    //字体名称数组
 private JComboBox size;                                        //字体大小的组合框
 private JComboBox names;                                       //字体名称的组合框
 private Label fontname;                                        //字体名称的标签
 private Label sizefont;                                        //字体大小标签
 private Label fontcolor;                                       //字体颜色标签
 private Label fontStyle;                                       //字体风格标签
 private JCheckBox Stylebold;                                   //粗体复选框
 private JCheckBox Styleitalic;                                 //斜体复选框
 private int[] flog=new int[10];
 private JRadioButton colorred;                                 //五个颜色按钮
 private JRadioButton colorblack;
 private JRadioButton colorblue;
 private JRadioButton colorwhite;
 private JRadioButton colorgreen;
 private ButtonGroup goup;                                    //颜色按钮组
private void addToolBar() {                                        //添加工具栏的方法
  JToolBar jtBar=new JToolBar();                             //创建一个新的工具栏
  goup=new ButtonGroup();                                    //颜色按钮组的初始化
  for(int i=0;i<flog.length;i++) {                           //用随机数,获得一个int数组
   flog[i]=(int)(Math.random()*(100-10+1)+10);            //,大小在10到100之间
  }
  for(int i=0;i<flog.length-1;i++) {                         //用冒泡算法排序
   for(int j=0;j<flog.length-i-1;j++) {
    if(flog[j]>flog[j+1]) {
     int t=flog[j+1];
     flog[j+1]=flog[j];
     flog[j]=t;
    }
   }
  }
  for(int j=0;j<fontsize.length;j++) {                       //将之前的int数组转为String数组
   fontsize[j]=String.valueOf(flog[j]);                   //到字体大小数组中
  }
   GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();//获取系统字体库
       fontnames = ge.getAvailableFontFamilyNames();
       size=new JComboBox(fontsize);                            //选择框获取内容
       names=new JComboBox(fontnames);
       fontname=new Label("字体");                              //标签给予内容
       sizefont=new Label("大小");
       fontcolor=new Label("颜色");
       fontStyle=new Label("风格");
       Stylebold=new JCheckBox("加粗");
       Styleitalic=new JCheckBox("斜体");
       colorred=new JRadioButton("红");                         //颜色按钮给予内容
       colorblue=new JRadioButton("蓝");
       colorgreen=new JRadioButton("绿");
       colorblack=new JRadioButton("黑");
       colorwhite=new JRadioButton("白");
       fontname.setBounds(10, 20, 5, 5);                       //设置选择框的位置与大小
       size.setBounds(10, 10, 100, 10);
       names.setBounds(10, 30, 100, 10);
       colorred.addActionListener(this);                       //为颜色按钮添加监听器
    colorgreen.addActionListener(this);
    colorblack.addActionListener(this);
    colorblue.addActionListener(this);
    colorwhite.addActionListener(this);
       size.addActionListener(this);                           //给选择框全都添加监听器
       names.addActionListener(this);
       Stylebold.addActionListener(this);
       Styleitalic.addActionListener(this);
       goup.add(colorblack);                                   //颜色按钮加入按钮组
       goup.add(colorblue);
       goup.add(colorgreen);
       goup.add(colorred);
       goup.add(colorred);
       goup.add(colorwhite);
       jtBar.add(fontname);                                    //向工具栏中添加所有的按钮,选择框
       jtBar.add(names);
       jtBar.add(sizefont);
       jtBar.add(size);
       jtBar.add(fontStyle);
       jtBar.add(Stylebold);
       jtBar.add(Styleitalic);
       jtBar.add(fontcolor);
       jtBar.add(colorblack);
       jtBar.add(colorblue);
       jtBar.add(colorgreen);
       jtBar.add(colorred);
       jtBar.add(colorwhite);
       this.add(jtBar,BorderLayout.NORTH);                      //设置工具栏在布局中的位置
       
}
public pubClass(String title){
 JFrame f1=new JFrame("title");                                 //声明面板
 MyMenuBar mb=new MyMenuBar(this);                              //添加菜单,直接赋值
 editor.getDocument().addUndoableEditListener(undo);
 mb.addMenus(new String[]{"文件(F)","编辑(E)","帮助(H)"});
 mb.addMenuItems(0,new String[]{"新建(N)","打开(O)","保存(S)","退出(X)" });
 mb.addMenuItems(1,new String[]{"剪贴(A)","复制(C)","粘贴(V)","清除(D)","撤销(Z)","全选(L)" ,"恢复(U)"});
 mb.addMenuItems(2,new String[]{"我的记事本信息(M)"});
 this.addToolBar();                                             //调用工具栏方法
 add(editor);                                                   
 mb.addActionListener(this);                                    //添加监听器
 addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e)
 {pubClass.this.dispose();}});
}                                                                //在窗口添加一个Window的消息,保证正常的关闭
public void actionPerformed(ActionEvent e){                       //事件执行方法
 Font font = editor.getFont();                                 //获取文本区的字体形式
    int fontStyle = font.getStyle();                              //临时字体风格
    int fontSize = font.getSize();                                //临时字体大小
    String fontName = font.getName();                             //临时字体名称
 String selected=e.getActionCommand();                         //用一个变量获取命令
 if(selected.equals("新建(N)")) {                              //执行新建命令
  editor.setText("");
 }else if(selected.equals("打开(O)")){                         //执行打开命令,打开文件可能会出错,用try
  try{ 
   editor.setText(mf.OpenData());
  }catch(IOException ie){}
 }else if(selected.equals("保存(S)")){                         //执行保存命令,同上此时也是打开文件
  try{                                                      //也有可能会出错
   mf.setData(editor.getText());
  }catch(IOException ie){}
 }else if(selected.equals("退出(X)")){                         //执行退出命令
  dispose();                                                //关闭窗口,释放屏幕资源
 }else if(selected.equals("剪贴(A)")){                         //执行剪切命令
  cb.setData(editor.getSelectedText());                     //将选择到的数据存入剪切板
  editor.replaceRange("",editor.getSelectionStart(),editor.getSelectionEnd());  //用空替换选择到的数据
 }else if(selected.equals("复制(C)")){                          //执行赋值命令
  cb.setData(editor.getSelectedText());                      //将剪切板中的数据返回出来
 }else if(selected.equals("粘贴(V)")){                          //执行粘贴命令
  String str=cb.getData();                                   //数组保存剪切板的数据
  editor.replaceRange(str,editor.getSelectionStart(),editor.getSelectionEnd());//再替换出来
 }else if(selected.equals("清除(D)")){                          //执行清除命令
  editor.setSelectionStart(0);                               //就是全选+替换
  editor.setSelectionEnd(editor.getText().length());
  editor.replaceRange("",editor.getSelectionStart(),editor.getSelectionEnd());
 }else if(selected.equals("全选(L)")){                          //执行全选命令
  editor.setSelectionStart(0);
  editor.setSelectionEnd(editor.getText().length());
 }else if(selected.equals("撤销(Z)")) {                         //通过之前的undo对象执行撤销
  undo.undo();
 }else if(selected.equals("恢复(U)")) {                         //同上
  undo.redo();
 }else if(selected.equals("我的记事本信息(M)")) {               //执行记事本信息的命令
  hp.bang();
 }else if(e.getSource().equals(size)) {                        //当获到点击字体大小时执行
    String str=(String)size.getSelectedItem();
    editor.setFont(new Font(fontName, fontStyle, Integer.parseInt(str)));//用setFont替换新获得的字体格式
 }else if(e.getSource().equals(names)) {                       //点击到字体名称时执行
    fontName=(String)names.getSelectedItem();           
    editor.setFont(new Font(fontName, fontStyle,fontSize));  //也是同上用setfont
 }else if (e.getSource().equals(colorred)) {                   //点击到颜色按钮时执行
  editor.setSelectedTextColor(Color.yellow);                //设置选到的字为黄色
        editor.setForeground(Color.red);                          //设置字体为红色
    }else if(e.getSource().equals(colorblue)) {
     editor.setForeground(Color.blue);                         //蓝色
    }else if (e.getSource().equals(colorblack)) {
        editor.setForeground(Color.black);                        //黑色
    }else  if (e.getSource().equals(colorgreen)) {
        editor.setForeground(Color.green);                        //绿色
    }else if (e.getSource().equals(colorwhite)) {
        editor.setForeground(Color.white);                        //白色
    }else if (e.getSource().equals(Stylebold)) {
        fontStyle = fontStyle ^ 1;                                //用异或运算,奇数次点击为真
        editor.setFont(new Font(fontName, fontStyle, fontSize));
    }else if (e.getSource().equals(Styleitalic)) {                //同上,不过用2异或
        fontStyle = fontStyle ^ 2; 
        editor.setFont(new Font(fontName, fontStyle, fontSize));
    }
    
}
public static void main(String[] args) {
 pubClass n1=new pubClass("我的记事本");                  //声明对象
 JScrollPane jsp = new JScrollPane(n1.editor);                 //向文本域中添加滚动条
 n1.add(jsp);                                                  //添加入n1
 Container con=n1.getContentPane();                            //声明一个容器
 JLabel la1=new JLabel();                                      //时间标签
 la1.setBounds(900, 900,150,40);                               //设置时间标签大小
 Thread t1=new Thread(new Time(la1));                          //用thread,开线程
 t1.start();
 con.add(la1,BorderLayout.SOUTH);                              //设置时间标签的位置
 n1.setBackground(Color.GRAY);                                 //设置工具栏的背景色
 n1.setSize(800, 400);                                         //设置n1的位置
 n1.setTitle("我的记事本");                                     //添加名称
 n1.setVisible(true);                                          //设置为可见
 }
}

这是我在这学期做的课程设计,做的不太好。有许多可以更改,添加的地方(比如像是快捷键),希望可以起作用。
下面是运行结果。在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值