java仿windows记事本小程序

 更新时间:2019年03月31日 17:11:57   作者:wuyihan1994  
这篇文章主要为大家详细介绍了java仿windows记事本小程序,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了java仿windows记事本小程序的具体代码,供大家参考,具体内容如下

import java.awt.CheckboxMenuItem;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.MenuShortcut;
import java.awt.TextArea;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.peer.ButtonPeer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.sql.Date;
import java.text.SimpleDateFormat;
 
import javax.print.DocFlavor.STRING;
import javax.script.ScriptException;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.AncestorListener;
import javax.swing.filechooser.FileNameExtensionFilter;
 
public class Crazy_15_4 {
 private JFrame f = new JFrame("记事本");
 
 //成员变量
 static String shearPlate = null;
 static boolean isAutoWrap = true;//是否自动换行
 JTextArea ta = new JTextArea(20, 60);
 JScrollPane jsp = new JScrollPane(ta);
 private MenuBar mb = new MenuBar();
 public String fontStr = "宋体";
 public String shapeStr = "0";
 public String sizeStr = "20";
 Font font = new Font(fontStr, Integer.parseInt(shapeStr),Integer.parseInt(sizeStr) );
 
 
 //menu
 Menu file = new Menu("文件");
 Menu edit = new Menu("编辑");
 Menu format = new Menu("格式");
 
 //menuitem
 MenuItem newItem = new MenuItem("新建");
 MenuItem openItem = new MenuItem("打开");
 MenuItem saveItem = new MenuItem("保存");
 MenuItem saveAsItem = new MenuItem("另存为");
 MenuItem cutItem = new MenuItem("剪切");
 MenuItem copyItem = new MenuItem("复制");
 MenuItem pasteItem = new MenuItem("粘贴");
 CheckboxMenuItem autoWrap = new CheckboxMenuItem("自动换行",isAutoWrap);
 MenuItem FontItem = new MenuItem("字体");
 //使用“ctrl+x”快捷键
 MenuItem exitIitem = new MenuItem("退出", new MenuShortcut(KeyEvent.VK_X));
 
 
 
 
 
 public void init() {
 //带滚动条的文本域
 ta.setLineWrap(isAutoWrap);
 jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
 jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
 
 
 file.add(newItem);
 file.add(openItem);
 file.add(saveItem);
 file.add(saveAsItem);
 
 edit.add(cutItem);
 edit.add(copyItem);
 edit.add(pasteItem);
 
 format.add(autoWrap);
 format.add(FontItem);
 
 mb.add(file);
 mb.add(edit);
 mb.add(format);
 
 f.setMenuBar(mb);
 f.addWindowListener(new WindowAdapter() {
 public void windowClosing(WindowEvent we) {
 if(!(ta.getText().equals(""))) {
  Object[] options = {"保存","不保存","取消"};
  int a = JOptionPane.showOptionDialog(null,"是否将更改保存到H:/Programing/无标题.txt","记事本", JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
  if(a == JOptionPane.OK_OPTION ) {
  if(save()) {
  System.exit(0);
  }
  }else if(a == JOptionPane.NO_OPTION) {
  System.exit(0);
  }
 }else {
  System.exit(0);
 }
 }
 });
 
 newItem.addActionListener(new newListener());
 openItem.addActionListener(new openListener());
 saveItem.addActionListener(new saveListener());
 saveAsItem.addActionListener(new saveAsListener());
 cutItem.addActionListener(new cutAsListener());
 copyItem.addActionListener(new copyAsListener());
 pasteItem.addActionListener(new pasteAsListener());
 autoWrap.addItemListener(new autoWrapAsListener());
 FontItem.addActionListener(new fontListener());
 
 ta.setFont(font);
 //使文本框处在屏幕中间
 int width = Toolkit.getDefaultToolkit().getScreenSize().width;
 int height = Toolkit.getDefaultToolkit().getScreenSize().height; 
 f.add(jsp);
 f.pack();
 f.setLocation(width/2-f.getWidth()/2, height/2-f.getHeight()/2);
 f.setVisible(true);
 //避免关闭对话框直接关闭文本文件
 f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
 }
 public static void main(String[] args) {
 new Crazy_15_4().init();
 }
 
 //是否保存
 public void saveOrNot() {
 if(!(ta.getText().equals(""))) {
 Object[] options = {"保存","不保存","取消"};
 int a = JOptionPane.showOptionDialog(null,"是否将更改保存到H:/Programing/无标题.txt","记事本", JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
 if(a == JOptionPane.OK_OPTION ) {
 save();
 }
 }
 }
 //保存文本文件
 public boolean save() {
 boolean isSaved = false;
 JFileChooser jf = new JFileChooser();
 FileNameExtensionFilter filter = new FileNameExtensionFilter("txt","txt");
 jf.setAcceptAllFileFilterUsed(false);
 jf.setFileFilter(filter);
 int value = jf.showSaveDialog(null);
 if(value == JFileChooser.APPROVE_OPTION) {
 File file = jf.getSelectedFile();
 String str = ta.getText();
 byte[] buf = str.getBytes();
 try {
 OutputStream os = new FileOutputStream(file);
 os.write(buf);
 os.flush();
 os.close();
 isSaved = true;
 } catch (IOException e) {
 e.printStackTrace();
 }
 }
 return isSaved;
 }
 //新建监听器
 class newListener implements ActionListener{
 public void actionPerformed(ActionEvent e) {
 if(!(ta.getText().equals(""))) {
 Object[] options = {"保存","不保存","取消"};
 int a = JOptionPane.showOptionDialog(null,"是否将更改保存到H:/Programing/无标题.txt","记事本", JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
 if(a == JOptionPane.OK_OPTION ) {
  if(save()) {
  ta.setText("");
  }
 }else if(a == JOptionPane.NO_OPTION) {
  ta.setText("");
 }
 }
 
 }
 }
 
 //打开监听器,从硬盘目录打开文本文件
 class openListener implements ActionListener{
 public void actionPerformed(ActionEvent e) {
 JFileChooser jf = new JFileChooser();
 FileNameExtensionFilter filter = new FileNameExtensionFilter("txt","txt");
 jf.setAcceptAllFileFilterUsed(false);
 jf.setFileFilter(filter);
 int value = jf.showOpenDialog(null);
 if(value == JFileChooser.APPROVE_OPTION) {
 File file = jf.getSelectedFile();
 try {
  String encoding = "GBK";//考虑编码格式
  InputStreamReader isr = new InputStreamReader(new FileInputStream(file),encoding);
  BufferedReader br = new BufferedReader(isr);
  String str = null;
  while((str = br.readLine()) != null) {
  ta.append(str);
  }
 } catch (FileNotFoundException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
 } catch (IOException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
 }
 }
 }
 }
 
 //保存监听器,以电脑时间命名
 class saveListener implements ActionListener{
 public void actionPerformed(ActionEvent e) {
 String name = null;
 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
 name = df.format(System.currentTimeMillis());
 File file = new File("H:/Programing/workspace/"+name+".txt");
 String str = ta.getText();
 byte[] buf = str.getBytes();
 if(!str.equals("")) {
 try {
  OutputStream os = new FileOutputStream(file);
  os.write(buf);
  os.flush();
  os.close();
 } catch (IOException e2) {
  e2.printStackTrace();
 }
 }
 }
 }
 
 //另存为监听器 
 class saveAsListener implements ActionListener{
 public void actionPerformed(ActionEvent e) {
 save();
 }
 }
 
 //剪切监听器 
 class cutAsListener implements ActionListener{
 public void actionPerformed(ActionEvent e) {
 shearPlate = ta.getSelectedText();
 int startPosi = ta.getSelectionStart();
 int endPosi = ta.getSelectionEnd();
 StringBuffer sb = new StringBuffer(ta.getText());
 sb.delete(startPosi, endPosi);
 ta.setText(sb.toString());
 }
 }
 
 //复制监听器 
 class copyAsListener implements ActionListener{
 public void actionPerformed(ActionEvent e) {
 shearPlate = ta.getSelectedText();
 }
 }
 
 //粘贴监听器 
 class pasteAsListener implements ActionListener{
 public void actionPerformed(ActionEvent e) {
 int position = ta.getCaretPosition();
 StringBuilder sb = new StringBuilder(ta.getText());
 sb.insert(position, shearPlate);
 ta.setText(sb.toString());
 ta.setCaretPosition(position+shearPlate.length());
 }
 }
 
 //自动换行监听器 
 class autoWrapAsListener implements ItemListener{
 
 @Override
 public void itemStateChanged(ItemEvent e) {
 if(autoWrap.getState()) {
  isAutoWrap = true;
  ta.setLineWrap(isAutoWrap);
  jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
  jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
 }else {
  isAutoWrap = false;
  ta.setLineWrap(isAutoWrap);
  jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
  jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
 }
 }
 }
 
 //字体监听器 
 class fontListener implements ActionListener{
 JFrame jf = new JFrame("字体");
 JPanel jp = new JPanel();
 ButtonPanel fontButton = new ButtonPanel("字体",new String[] {"宋体","黑体","楷体","吴祎晗1.0"});
 ButtonPanel shapeButton = new ButtonPanel("字形",new String[] {"常规","粗体","斜体","粗体&斜体"});
 ButtonPanel sizeButton = new ButtonPanel("字号",new String[] {"12","16","20","24","26"});
 public void actionPerformed(ActionEvent e) {
 jp.setBorder(new TitledBorder(new EtchedBorder(),"字体选择",TitledBorder.CENTER,TitledBorder.TOP));
 jp.add(fontButton);
 jp.add(shapeButton);
 jp.add(sizeButton);
 jf.add(jp);
 jf.pack();
 jf.setLocationRelativeTo(f);
 jf.setVisible(true);
 jf.addWindowListener(new WindowAdapter() {
  public void windowClosing(WindowEvent e) {
  fontStr = fontButton.getSelec();
  sizeStr = sizeButton.getSelec();
  font = new Font(fontStr, shapeVal(shapeButton.getSelec()), Integer.parseInt(sizeStr));
  ta.setFont(font);
  }
 });
 }
 
 public int shapeVal(String str) {
 int a = 0;
 switch (str) {
 case "常规":
  a = 0;
  break;
 case "粗体":
  a = 1;
  break;
 case "斜体":
  a = 2;
  break;
 case "粗体&斜体":
  a = 3;
  break;
 }
 return a;
 }
 }
 
}
 
//定义一个JPanel类扩展类,该类的对象包含多个纵向排列的
//JRadioButton控件,且panel扩展类可以指定一个字符串作为TitledBorder
class ButtonPanel extends JPanel{
 private ButtonGroup group;
 public ButtonPanel(String title, String[] options) {
 setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(),title));
 setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
 group = new ButtonGroup();
 for(int i=0; options!=null&&i<options.length; i++) {
 JRadioButton b = new JRadioButton(options[i]);
 b.setActionCommand(options[i]);
 this.add(b);
 group.add(b);
 if(title.equals("字号")) {
 b.setSelected(i == 2);
 }else {
 b.setSelected(i == 0);
 }
 }
 }
 public String getSelec() {
 return group.getSelection().getActionCommand();
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • 基于 IntelliJ IDEA 模拟 Servlet 网络请求示例

    基于 IntelliJ IDEA 模拟 Servlet 网络请求示例

    这篇文章主要介绍了基于 IntelliJ IDEA 模拟 Servlet 网络请求示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-04-04
  • Java线程池配置的一些常见误区总结

    Java线程池配置的一些常见误区总结

    这篇文章主要给大家介绍了关于Java线程池配置的一些常见误区,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • Java 8中 Stream小知识小技巧方法梳理

    Java 8中 Stream小知识小技巧方法梳理

    这篇文章主要介绍了Java8中Stream小知识小技巧方法梳理,Stream流和迭代器一样,它只能够迭代一次。当它遍历完的时候,我们就称它已经消费完了。如果还想重新执行操作,那么就只能从原来的地方再获取一个流
    2022-09-09
  • MyBatis映射文件中parameterType与resultType的用法详解

    MyBatis映射文件中parameterType与resultType的用法详解

    MyBatis中的ParameterType指的是SQL语句中的参数类型,即传入SQL语句中的参数的类型,下面这篇文章主要给大家介绍了关于MyBatis映射文件中parameterType与resultType用法的相关资料,需要的朋友可以参考下
    2023-04-04
  • Java如何Mock FileInputStream问题

    Java如何Mock FileInputStream问题

    这篇文章主要介绍了Java如何Mock FileInputStream问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-09-09
  • Mybatis动态sql中@Param使用详解

    Mybatis动态sql中@Param使用详解

    这篇文章主要介绍了Mybatis动态sql中@Param使用详解,当方法的参数为非自定义pojo类型,且使用了动态sql,那么就需要在参数前加上@Param注解,需要的朋友可以参考下
    2023-10-10
  • 详解Lombok的坑

    详解Lombok的坑

    这篇文章主要介绍了详解Lombok的坑,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-11-11
  • 浅谈Java中实现深拷贝的两种方式—clone() & Serialized

    浅谈Java中实现深拷贝的两种方式—clone() & Serialized

    这篇文章主要介绍了Java中实现深拷贝的两种方式—clone() & Serialized,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-03-03
  • Maven中dependencyManagement管理项目依赖项

    Maven中dependencyManagement管理项目依赖项

    在开发 Java 项目时,管理和协调依赖项的版本号是一项重要而繁琐的任务,本文主要介绍了Maven中dependencyManagement管理项目依赖项,具有一定的参考价值,感兴趣的可以了解一下
    2024-01-01
  • Spring Boot的应用启动与关闭的方法

    Spring Boot的应用启动与关闭的方法

    本篇文章主要介绍了Spring Boot的应用启动与关闭的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-12-12

最新评论