Java_Easy—记事本小程序

我又来了,这次带来了“简单版Java记事本”

这次的功能有:文件(新建、打开、保存、另存为)、格式(字体设置、大小、颜色、自动换行)、工具(查找替换)

写了好多东西,但好像没人看😔,那就给自己看!!!冲啊!!!😎
package KeShe.Study.Day_07;
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

//调用以下Java类
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;




//主类Txt
public class Txt extends javax.swing.JFrame {

    //自定义变量
    static File file=null;
    public static JFileChooser fileChooser=new JFileChooser();


    /**
     * Creates new form Txt
     */
    public Txt() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">


    //NetBeans操作添加的JSwing部件
    private void initComponents() {
        jScrollPane1 = new javax.swing.JScrollPane();
        txtArea = new javax.swing.JTextArea();
        jMenuBar2 = new javax.swing.JMenuBar();
        fileBtn = new javax.swing.JMenu();
        newFileBtn = new javax.swing.JMenuItem();
        openFileBtn = new javax.swing.JMenuItem();
        saveFileBtn = new javax.swing.JMenuItem();
        savaToAnotherFileBtn = new javax.swing.JMenuItem();
        jMenu5 = new javax.swing.JMenu();
        FontSet = new javax.swing.JMenuItem();
        FontColor = new javax.swing.JMenuItem();
        FontSize = new javax.swing.JMenuItem();
        toLine = new javax.swing.JCheckBoxMenuItem();
        jMenu1 = new javax.swing.JMenu();
        serOrRep = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        txtArea.setColumns(20);
        txtArea.setRows(5);
        jScrollPane1.setViewportView(txtArea);

        jMenuBar2.setFont(new java.awt.Font("Microsoft YaHei UI", Font.PLAIN, 24)); // NOI18N

        fileBtn.setText("文件");
        newFileBtn.setText("新建");
        newFileBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newFileBtnActionPerformed(evt);
            }
        });
        fileBtn.add(newFileBtn);

        openFileBtn.setText("打开");
        openFileBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openFileBtnActionPerformed(evt);
            }
        });
        fileBtn.add(openFileBtn);

        saveFileBtn.setText("保存");
        saveFileBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveFileBtnActionPerformed(evt);
            }
        });
        fileBtn.add(saveFileBtn);

        savaToAnotherFileBtn.setText("另存为");
        savaToAnotherFileBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                savaToAnotherFileBtnActionPerformed(evt);
            }
        });
        fileBtn.add(savaToAnotherFileBtn);

        jMenuBar2.add(fileBtn);

        jMenu5.setText("格式");

        FontSet.setText("字体设置");
        FontSet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FontSetActionPerformed(evt);
            }
        });
        jMenu5.add(FontSet);

        FontColor.setText("字体颜色");
        FontColor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FontColorActionPerformed(evt);
            }
        });
        jMenu5.add(FontColor);

        FontSize.setText("字体大小");
        FontSize.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FontSizeActionPerformed(evt);
            }
        });
        jMenu5.add(FontSize);

        toLine.setSelected(true);
        toLine.setText("自动换行");
        toLine.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                toLineActionPerformed(evt);
            }
        });
        jMenu5.add(toLine);

        jMenuBar2.add(jMenu5);

        jMenu1.setText("工具");

        serOrRep.setText("查找||替换");
        serOrRep.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                serOrRepActionPerformed(evt);
            }
        });
        jMenu1.add(serOrRep);

        jMenuBar2.add(jMenu1);

        setJMenuBar(jMenuBar2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 786, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 634, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>



/*
*
* 自定义方法实现部分
*
*/

    //打开文件方法
    public void showFileDialog(JTextArea txtArea) {

            fileChooser.setCurrentDirectory(new File("e:/桌面"));//默认目录
            fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
            fileChooser.setFileFilter(new FileNameExtensionFilter("txt(*.txt)", "txt"));//设置文件过滤器
            int n = fileChooser.showOpenDialog(txtArea);
            if (n == 0) {
                try {
                    file = fileChooser.getSelectedFile();
                    FileReader fr = new FileReader(file);
                    BufferedReader br = new BufferedReader(fr);
                    String userInfor = br.readLine();
                    while (userInfor != null) {
                        txtArea.setText(txtArea.getText() + userInfor + "\n");
                        userInfor = br.readLine();
                    }
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }

    //保存文件方法
    public void showFileSavaDialog(JTextArea txtArea){
        try{
            FileWriter fw=new FileWriter(file);
            BufferedWriter bw=new BufferedWriter(fw);
            String userInfo=txtArea.getText();
            bw.write(userInfo);
            bw.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    //另保存文件方法
    public void showFileAnotherSaveDialog(JTextArea txtArea) throws HeadlessException {
        try {
            String jfn = JOptionPane.showInputDialog("请输入文件名:") + ".txt";

            fileChooser.setSelectedFile(new File(jfn));//设置打开文件选择框后默认输入的文件名

            fileChooser.setFileFilter(new FileNameExtensionFilter(".txt(*.txt)", "txt"));

            fileChooser.setCurrentDirectory(null);

            int result = fileChooser.showSaveDialog(null);//打开文件选择框(线程将被阻塞,直到选择框被关闭)

            if (result == JFileChooser.APPROVE_OPTION) {//如果点击了“保存”,则获取选择的保存路径
                File file = new File(fileChooser.getCurrentDirectory(), jfn/*fileChooser.getName(fileChooser.getSelectedFile())*/);//设置文件的目录和名字
                file.createNewFile();//创建指定目录和文件名的新文件
                FileWriter fw = new FileWriter(file);
                fw.write(txtArea.getText());
                fw.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //判断非空内容是否保存方法
    int result;//定义变量,随时访问对话框是否点击保存
    public void isSave(JTextArea txtArea){
        String s=txtArea.getText();
        if (s.length() != 0) {
            result = JOptionPane.showConfirmDialog(null, "当前内容是否保存", "提示", JOptionPane.YES_NO_CANCEL_OPTION);
            if (result == 0) {
                showFileAnotherSaveDialog(txtArea);
                txtArea.setText("");
            } else if (result == 1) {
                txtArea.setText("");
            }
        }
    }


    /*
     *
     * 菜单按钮响应实现部分
     *
     */

    //新建菜单选项按钮响应
    private void newFileBtnActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        isSave(txtArea);
        txtArea.setForeground(Color.BLACK);
        txtArea.setFont(new Font(null, Font.PLAIN,18));
    }

    //打开菜单选项按钮响应
    private void openFileBtnActionPerformed (java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            String s = txtArea.getText();
            isSave(txtArea);
            if(result==1||result==0)
                showFileDialog(txtArea);
        }

    //另存为菜单选项按钮响应
    private void savaToAnotherFileBtnActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        showFileAnotherSaveDialog(txtArea);
        txtArea.setText("");

    }

    //保存菜单选项按钮响应
    private void saveFileBtnActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        if(file!=null) showFileSavaDialog(txtArea);
        else showFileAnotherSaveDialog(txtArea);
        txtArea.setText("");
    }

    //字体颜色菜单选项按钮响应
    private void FontColorActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        try {
            Color color = JColorChooser.showDialog(null, "文字颜色选择", Color.yellow);
            txtArea.setForeground(color);
        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    //字体设置菜单选项按钮响应
    private void FontSetActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        Object[] fontName=new Object[]{"黑体","楷体","宋体","仿宋"
                ,"微软雅黑","方正姚体","华文行楷","方正舒体","幼圆","华文中宋","隶书","等线","方正粗黑宋简体"};

        //显示输入对话框,返回选择的内容,点击取消或关闭,则返回null
        Object name=JOptionPane.showInputDialog(null,"请选择一项字体格式","字体格式",JOptionPane.PLAIN_MESSAGE,null,fontName,fontName[0]);
        int size=txtArea.getFont().getSize();

        if(name!=null) {
            txtArea.setFont(new Font((String) name, Font.PLAIN,size));
        }
    }

    //字体大小菜单选项按钮响应
    private void FontSizeActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        Object name=txtArea.getFont().getFontName();
        String fontSize=JOptionPane.showInputDialog("请输入想要的字体大小");
        int Size=Integer.parseInt(fontSize);
        txtArea.setFont(new Font((String) name,Font.PLAIN,Size));
    }

    //自动换行菜单选项按钮响应
    private void toLineActionPerformed(java.awt.event.ActionEvent evt) {//自动换行
        // TODO add your handling code here:
        txtArea.setLineWrap(toLine.getState());
    }

    //替换||查找菜单选项按钮响应
    private void serOrRepActionPerformed(java.awt.event.ActionEvent evt) {//替换||查找
        // TODO add your handling code here:
        JDialog search = new JDialog();
        search.setSize(300, 100);
        search.setLocation(450, 350);
        JLabel label_1 = new JLabel("查找的内容");
        JLabel label_2 = new JLabel("替换的内容");
        final JTextField textField_1 = new JTextField(5);
        final JTextField textField_2 = new JTextField(5);
        JButton buttonFind = new JButton("查找下一个");
        JButton buttonChange = new JButton("替换");
        JPanel panel = new JPanel(new GridLayout(2, 3));
        panel.add(label_1);
        panel.add(textField_1);
        panel.add(buttonFind);
        panel.add(label_2);
        panel.add(textField_2);
        panel.add(buttonChange);
        search.add(panel);
        search.setVisible(true);

        buttonFind.addActionListener(new ActionListener() {// 为查找下一个 按钮绑定监听事件
            int  start=0,end=0;
            public void actionPerformed(ActionEvent e) {

                String findText = textField_1.getText();// 查找的字符
                String textArea = txtArea.getText();// 当前文本框的内容

                start = textArea.indexOf(findText, end);
                end = start + findText.length();
                if (start == -1) // 没有找到
                    JOptionPane.showMessageDialog(null, "没找到更多的”" + findText + "”", "文档查询", JOptionPane.WARNING_MESSAGE);
                else txtArea.select(start, end);

            }
        });

        buttonChange.addActionListener(new ActionListener() {// 为替换按钮绑定监听时间
            public void actionPerformed(ActionEvent e) {
                String changeText = textField_2.getText();// 替换的字符串
                if (txtArea.getSelectionStart() != txtArea.getSelectionEnd())//判断选中的区域不为空
                    txtArea.replaceRange(changeText, txtArea.getSelectionStart(), txtArea.getSelectionEnd());//将选中文本替换为特定内容
            }
        });
    }


    /*
    *
    * NetBeans操作自主生成的代码如下
    *
    */

    /*
     * @param args the command line arguments
     */
    public static void main(String[] args) {//主方法
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Txt.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Txt.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Txt.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Txt.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Txt().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JMenuItem FontColor;
    private javax.swing.JMenuItem FontSet;
    private javax.swing.JMenuItem FontSize;
    private javax.swing.JMenu fileBtn;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu5;
    private javax.swing.JMenuBar jMenuBar2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JMenuItem newFileBtn;
    private javax.swing.JMenuItem openFileBtn;
    private javax.swing.JMenuItem savaToAnotherFileBtn;
    private javax.swing.JMenuItem saveFileBtn;
    private javax.swing.JMenuItem serOrRep;
    private javax.swing.JCheckBoxMenuItem toLine;
    private javax.swing.JTextArea txtArea;
    // End of variables declaration                   
}

到这里,Java记事本小程序,就告一段落了,毕竟他只是我学习路上的一个纪念碑,标志这我在Java语言方向上,有了一丢丢小进步~~~嘿嘿🙄

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值