Java用Swing写一个txt文本阅读器,并保存成有格式文本

主体部分:

package txtReader;

import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.html.HTMLEditorKit;

import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JColorChooser;
import javax.swing.JFileChooser;
import javax.swing.JTextPane;
import javax.swing.UIManager;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
import javax.swing.JScrollPane;
import javax.swing.BoxLayout;
import java.awt.Toolkit;
import java.awt.Font;

@SuppressWarnings("serial")
public class TxtReader extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        try {

            //UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");//Nimbus风格,jdk6 update10版本以后的才会出现
            //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());//当前系统风格
            //UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");//Motif风格,是蓝黑
            //UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());//跨平台的Java风格
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");//windows风格
            //UIManager.setLookAndFeel("javax.swing.plaf.windows.WindowsLookAndFeel");//windows风格
            //UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");//java风格
            //UIManager.setLookAndFeel("com.apple.mrj.swing.MacLookAndFeel");//待考察,

            } catch (Exception e) {
            e.printStackTrace();
            }
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    TxtReader frame = new TxtReader();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public TxtReader() {
        setIconImage(Toolkit.getDefaultToolkit().getImage(TxtReader.class.getResource("/com/sun/javafx/scene/control/skin/modena/HTMLEditor-Bullets-Black-rtl.png")));
        setVisible(true);
        setTitle("TextMaster ReleaseVer 1.2--by Cocca");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 733, 738);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        JTextPane txtpnnwordnhtml = new JTextPane();
        txtpnnwordnhtml.setFont(new Font("Microsoft YaHei UI", Font.PLAIN, 15));

        contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.X_AXIS));
        contentPane.add(txtpnnwordnhtml);

        JScrollPane scrollPane = new JScrollPane(txtpnnwordnhtml);
        scrollPane.setAutoscrolls(true);
        contentPane.add(scrollPane);
        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);


        JMenu mns = new JMenu("\u5F00\u59CB");
        menuBar.add(mns);

        JMenuItem mntmNew = new JMenuItem("\u65B0\u5EFA...");
        mntmNew.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                JFileChooser jFileChooser = new JFileChooser();
                int option =jFileChooser.showSaveDialog(null);
                if (option==JFileChooser.APPROVE_OPTION) {
                    File  writeF=jFileChooser.getSelectedFile();
                        StyledDocument doc = (StyledDocument) txtpnnwordnhtml.getDocument();
                        HTMLEditorKit kit = new HTMLEditorKit();
                        BufferedOutputStream out;
                        try {

                            if (!writeF.exists()) {
                                writeF.createNewFile();
                            }
                            out = new BufferedOutputStream(new FileOutputStream(writeF));
                            kit.write(out, doc, doc.getStartPosition().getOffset(),doc.getLength());
                        } catch (FileNotFoundException e1) {
                            e1.printStackTrace();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        } catch (BadLocationException e1) {
                            e1.printStackTrace();
                        }



                }
            }
        });
        mns.add(mntmNew);
        JMenuItem mntmOpen = new JMenuItem("\u6253\u5F00...");

        mns.add(mntmOpen);

        JMenuItem mntmSave = new JMenuItem("\u4FDD\u5B58...");
        mntmSave.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                JFileChooser jFileChooser = new JFileChooser();
                //JFileChooser jFileChooser = new JFileChooser();
                FileNameExtensionFilter fileNameExtensionFilter = new FileNameExtensionFilter("格式文本文件", "html");
                jFileChooser.setFileFilter(fileNameExtensionFilter);
                File file = new File("新建格式文档.html");
                jFileChooser.setSelectedFile(file);
                //int option = jFileChooser.showOpenDialog(null);
                int option =jFileChooser.showSaveDialog(null);
                if (option==JFileChooser.APPROVE_OPTION) {
                    File  writeF=jFileChooser.getSelectedFile();
                        StyledDocument doc = (StyledDocument) txtpnnwordnhtml.getDocument();
                        HTMLEditorKit kit = new HTMLEditorKit();
                        BufferedOutputStream out;
                        try {

                            if (!writeF.exists()) {
                                writeF.createNewFile();
                            }
                            out = new BufferedOutputStream(new FileOutputStream(writeF));
                            kit.write(out, doc, doc.getStartPosition().getOffset(),doc.getLength());
                        } catch (FileNotFoundException e1) {
                            e1.printStackTrace();
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        } catch (BadLocationException e1) {
                            e1.printStackTrace();
                        }



                }
            }
        });
        mns.add(mntmSave);

        JMenuItem mntmExit = new JMenuItem("\u9000\u51FA");
        mntmExit.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                String message="退出前请注意保存文件!\n是否继续退出?";
                int val= JOptionPane.showConfirmDialog(null, message);
                if (val==JOptionPane.YES_OPTION) {
                    System.exit(0);
                }

            }
        });
        mns.add(mntmExit);

        JMenu mnSetup = new JMenu("\u7F16\u8F91");
        menuBar.add(mnSetup);

        JMenuItem mntmBackgroundColor = new JMenuItem("\u80CC\u666F\u8272...");
        mntmBackgroundColor.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                Color color=JColorChooser.showDialog(null, "choose a color", Color.WHITE);
                txtpnnwordnhtml.setBackground(color);
            }
        });

                JMenuItem mntmAlign = new JMenuItem("\u5BF9\u9F50...");
                mntmAlign.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mousePressed(MouseEvent e) {
                        String[] options = {"左对齐","居中","右对齐","自适应"};
                        String message="请选择对齐方式:";
                        int num=JOptionPane.showOptionDialog(null, message, "对齐", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, options, "");
                        int kekka = StyleConstants.ALIGN_LEFT;
                        if (options[num].equals("居中")) {
                            kekka=StyleConstants.ALIGN_CENTER;
                        } 
                        if (options[num].equals("右对齐")) {
                            kekka=StyleConstants.ALIGN_RIGHT;
                        }
                        if (options[num].equals("自适应")) {
                            kekka=StyleConstants.ALIGN_JUSTIFIED;
                        }
                        SimpleAttributeSet attr=new SimpleAttributeSet();
                        //实例化一个simpleAttributeSet类。
                        StyleConstants.setAlignment(attr, kekka); 
                                    //使用StyleConstants工具类来设置attr属性,这里设置居中属性。
                        txtpnnwordnhtml.setParagraphAttributes(attr,false);
                    }
                });
                mnSetup.add(mntmAlign);
        mnSetup.add(mntmBackgroundColor);

        JMenuItem mntmNewMenuItem = new JMenuItem("\u5B57\u4F53...");
        mntmNewMenuItem.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                JFontChooser jFontChooser = new JFontChooser(txtpnnwordnhtml.getFont(),Color.BLACK);
                jFontChooser.showDialog(null,500,200);
                SimpleAttributeSet attr=new SimpleAttributeSet();
                //实例化一个simpleAttributeSet类。
                StyleConstants.setForeground(attr, jFontChooser.getSelectedcolor());
                //设置颜色属性,参数为color类型。
                StyleConstants.setBold(attr,jFontChooser.isBold()||jFontChooser.isBoldItalic());
                StyleConstants.setItalic(attr, jFontChooser.isItalic()||jFontChooser.isBoldItalic());
                //StyleConstants.set(attr, jFontChooser.isItalic());
                StyleConstants.setFontFamily(attr, jFontChooser.getFontFamily());
                StyleConstants.setFontSize(attr, jFontChooser.getFontSize());
                txtpnnwordnhtml.setCharacterAttributes(attr, false);


            }
        });
        mnSetup.add(mntmNewMenuItem);

        JMenuItem mntmNewMenuItem_1 = new JMenuItem("\u5168\u9009");
        mntmNewMenuItem_1.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                Highlighter highlighter=txtpnnwordnhtml.getHighlighter();
                try {
                    highlighter.addHighlight(0,txtpnnwordnhtml.getText().length(), DefaultHighlighter.DefaultPainter);
                } catch (BadLocationException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        mnSetup.add(mntmNewMenuItem_1);

        JMenu menu = new JMenu("\u5DE5\u5177");
        menuBar.add(menu);

        JCheckBoxMenuItem checkBoxMenuItem = new JCheckBoxMenuItem("\u4FDD\u6301\u7A97\u53E3\u6700\u524D");
        checkBoxMenuItem.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent arg0) {
                boolean b = checkBoxMenuItem.isSelected();
                setAlwaysOnTop(b);
            }
        });
        menu.add(checkBoxMenuItem);

        JMenuItem menuItem = new JMenuItem("\u67E5\u627E...");
        menuItem.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                String content = txtpnnwordnhtml.getText();
                String key="";
                key=JOptionPane.showInputDialog("请输入搜索关键字:");
                if (key.equals("")) {
                    //lblNewLabel.setText("                          未输入搜索关键字词");
                    return;
                }
                if (content.equals("")) {
                    //lblNewLabel.setText("                没有搜索目标,请先输入或导入文件");
                    return ;
                }
                Highlighter highlighter =txtpnnwordnhtml.getHighlighter();
                highlighter.removeAllHighlights();
                if (content.contains(key)) {
                    int index = content.indexOf(key);
                    while (true) {
                        if(index!=-1) {
                        try {
                            highlighter.addHighlight(index, index+key.length(), DefaultHighlighter.DefaultPainter);
                        } catch (BadLocationException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                        index=content.indexOf(key,++index);
                        }else {
                            break;
                        }
                    }
                    //JOptionPane.showMessageDialog(null, "搜索完成!\n已找到"+houh+"处。","搜索结果",JOptionPane.INFORMATION_MESSAGE);
                }
            }
        }); 

        JMenuItem mntmNewMenuItem_2 = new JMenuItem("\u5B57\u6570\u7EDF\u8BA1...");
        mntmNewMenuItem_2.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                JOptionPane.showMessageDialog(null, "office统计法-字数统计:"+new WordCount().getMSWordsCount(txtpnnwordnhtml.getText())+"\n总字符数:"+txtpnnwordnhtml.getText().length());
            }
        });
        menu.add(mntmNewMenuItem_2);
        menu.add(menuItem);

        JMenu mnHelp = new JMenu("\u5E2E\u52A9");
        menuBar.add(mnHelp);

        JMenuItem mntmAbout = new JMenuItem("\u5173\u4E8E");
        mntmAbout.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                String message = "This Java program is produced by cocca.\nVersion 1.2";
                String title="About";
                JOptionPane.showMessageDialog(null, message, title, JOptionPane.INFORMATION_MESSAGE);
            }
        });
        mnHelp.add(mntmAbout);

//      JLabel lblNewLabel = new JLabel("               使用提示:可以将制作好的有格式文件保存成.html格式导出,保存成.txt格式是无格式文本哟  ");
//      lblNewLabel.setFont(new Font("微软雅黑 Light", Font.ITALIC, 12));
//      menuBar.add(lblNewLabel);
//      txtpnnwordnhtml.addInputMethodListener(new InputMethodListener() {
//          public void caretPositionChanged(InputMethodEvent arg0) {
//              lblNewLabel.setText("                      汉字数:"+new WordCount().getMSWordsCount(txtpnnwordnhtml.getText())+"\n总字符数:"+txtpnnwordnhtml.getText().length());
//              
//          }
//          public void inputMethodTextChanged(InputMethodEvent arg0) {
//              lblNewLabel.setText("                      汉字数:"+new WordCount().getMSWordsCount(txtpnnwordnhtml.getText())+"\n总字符数:"+txtpnnwordnhtml.getText().length());
//          }
//      });
        mntmOpen.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent arg0) {
                JFileChooser jFileChooser = new JFileChooser();
                FileNameExtensionFilter fileNameExtensionFilter = new FileNameExtensionFilter("文本文件", "txt");
                jFileChooser.setFileFilter(fileNameExtensionFilter);
                int option = jFileChooser.showOpenDialog(null);
                if (option == JFileChooser.APPROVE_OPTION) {
                    File file = jFileChooser.getSelectedFile();
                    BufferedReader bre = null;
                    String str;
                    try {
                    bre = new BufferedReader(new FileReader(file));//此时获取到的bre就是整个文件的缓存流
                    try {
                        while ((str = bre.readLine())!= null) // 判断最后一行不存在,为空结束循环
                        {
                        txtpnnwordnhtml.setText(txtpnnwordnhtml.getText()+str+"\n");
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }} catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }finally {

                    }

//                  try {
//                      bufferedReader =new FileReader(file);
//                      while (bufferedReader.read()!=-1) {
//                          text = bufferedReader.read();
//                          // 设置字体大小
//                          // SimpleAttributeSet attrset = new SimpleAttributeSet();
//                          // StyleConstants.setFontSize(attrset,24);
//                          textPane.setText(textPane.getText() + (char)text);
//                      }
//                      bufferedReader.close();
//                  } catch (FileNotFoundException e) {
//
//                  } catch (IOException e) {
//
//                  }

                }
            }

        });

    }
}

其他:

package txtReader;

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Cursor;
    import java.awt.Font;
    import java.awt.Frame;
    import java.awt.GraphicsEnvironment;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
import java.io.ObjectInputStream.GetField;
import java.util.HashMap;
    import java.util.Map;
    import javax.swing.JButton;
    import javax.swing.JColorChooser;
    import javax.swing.JComboBox;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;

    @SuppressWarnings("serial")
    public class JFontChooser extends JPanel {

        // 设置界面风格
        {
            try {
                javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //[start] 定义变量
        private String                          current_fontName                            = "宋体";//当前的字体名称,默认宋体.
        private String                          showStr                                     = "果冻  Cocca";//展示的文字
        private int                             current_fontStyle                           = Font.PLAIN;//当前的字样,默认常规.
        private int                             current_fontSize                            = 9;//当前字体大小,默认9号.
        private Color                           current_color                               = Color.BLACK;//当前字色,默认黑色.
        private JDialog                         dialog;                                     //用于显示模态的窗体
        private JLabel                          lblFont;                                    //选择字体的LBL
        private JLabel                          lblStyle;                                   //选择字型的LBL
        private JLabel                          lblSize;                                    //选择字大小的LBL
        private JLabel                          lblColor;                                   //选择Color的label
        private JLabel                          otherColor;                                 //其它颜色
        private JTextField                      txtFont;                                    //显示选择字体的TEXT
        private JTextField                      txtStyle;                                   //显示选择字型的TEXT
        private JTextField                      txtSize;                                    //显示选择字大小的TEXT
        private JTextField                      showTF;                                     //展示框(输入框)
        private JList                           lstFont;                                    //选择字体的列表.
        private JList                           lstStyle;                                   //选择字型的列表.
        private JList                           lstSize;                                    //选择字体大小的列表.
        private JComboBox                       cbColor;                                    //选择Color的下拉框.
        private JButton                         ok, cancel;                                 //"确定","取消"按钮.
        private JScrollPane                     spFont;
        private JScrollPane                     spSize;
        private JPanel                          showPan;                                    //显示框.
        private Map                             sizeMap;                                    //字号映射表.
        private Map                             colorMap;                                   //字着色映射表.
        private Font                            selectedfont;                               //用户选择的字体
        private Color                           selectedcolor;                              //用户选择的颜色
        //[end]

        //无参初始化
        public JFontChooser(){
                this.selectedfont = null;
                this.selectedcolor = null;
                /* 初始化界面 */
                init(null,null);
        }

        //重载构造,有参的初始化 用于初始化字体界面
        public JFontChooser(Font font, Color color){
            if (font != null) {
                this.selectedfont = font;
                this.selectedcolor = color;
                this.current_fontName = font.getName();
                this.current_fontSize = font.getSize();
                this.current_fontStyle = font.getStyle();
                this.current_color = color;
                /* 初始化界面 */
                init(font,color);
            }else{
                JOptionPane.showMessageDialog(this, "没有被选择的控件", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }

        //可供外部调用的方法
        public Font getSelectedfont() {
            return selectedfont;
        }

        public void setSelectedfont(Font selectedfont) {
            this.selectedfont = selectedfont;
        }

        public Color getSelectedcolor() {
            return selectedcolor;
        }

        public void setSelectedcolor(Color selectedcolor) {
            this.selectedcolor = selectedcolor;
        }

        /*初始化界面*/
//      private void init(Font txt_font) {
        @SuppressWarnings("unchecked")
        private void init(Font font,Color color) {
            //实例化变量
            lblFont = new JLabel("字体:");
            lblStyle = new JLabel("字型:");
            lblSize = new JLabel("大小:");
            lblColor = new JLabel("颜色:");
            otherColor = new JLabel("<html><U>其它颜色</U></html>");
            txtFont = new JTextField("宋体");
            txtStyle = new JTextField("常规");
            txtSize = new JTextField("9");

            //取得当前环境可用字体.
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            String[] fontNames = ge.getAvailableFontFamilyNames();

            lstFont = new JList(fontNames);

            //字形.
            lstStyle = new JList(new String[]{"常规", "粗体" ,"斜体", "粗斜体"});

            //字号.
            String[] sizeStr = new String[]{
                "8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "26", "28", "36", "48", "72","初号", "小初",
                 "一号", "小一", "二号", "小二", "三号", "小三", "四号", "小四", "五号", "小五", "六号", "小六", "七号", "八号"
            };
            int sizeVal[] = {8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28, 36, 48, 72, 42, 36, 26, 24, 22, 18, 16, 15, 14, 12, 11, 9, 8, 7, 6, 5};
            sizeMap = new HashMap();
            for (int i = 0; i < sizeStr.length; ++i) {
                sizeMap.put(sizeStr[i], sizeVal[i]);
            }
            lstSize = new JList(sizeStr);
            spFont = new JScrollPane(lstFont);
            spSize = new JScrollPane(lstSize);

            //颜色
            String[] colorStr = new String[]{
                "黑色", "蓝色", "青色", "深灰", "灰色", "绿色", "浅灰", "洋红", "桔黄", "粉红", "红色", "白色", "黄色"
            };
            Color[] colorVal = new Color[]{
                Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE, Color.YELLOW
            };
            colorMap = new HashMap();
            for (int i = 0; i < colorStr.length; i++) {
                colorMap.put(colorStr[i], colorVal[i]);
            }
            cbColor = new JComboBox(colorStr);
            showPan = new JPanel();
            ok = new JButton("确定");
            cancel = new JButton("取消");


            //布局控件
            //字体框
            this.setLayout(null);   //不用布局管理器
            add(lblFont);
            lblFont.setBounds(12, 10, 30, 20);
            txtFont.setEditable(false);
            add(txtFont);
            txtFont.setBounds(10, 30, 155, 20);
            txtFont.setText("宋体");
            lstFont.setSelectedValue("宋体", true);
            if (font != null) {
                txtFont.setText(font.getName());
                lstFont.setSelectedValue(font.getName(), true);
            }

            add(spFont);
            spFont.setBounds(10, 50, 155, 100);

            //样式
            add(lblStyle);
            lblStyle.setBounds(175, 10, 30, 20);
            txtStyle.setEditable(false);
            add(txtStyle);
            txtStyle.setBounds(175, 30, 130, 20);
            lstStyle.setBorder(javax.swing.BorderFactory.createLineBorder(Color.gray));
            add(lstStyle);
            lstStyle.setBounds(175, 50, 130, 100);
            txtStyle.setText("常规"); //初始化为默认的样式
            lstStyle.setSelectedValue("常规",true);   //初始化为默认的样式
            if(font != null){
                lstStyle.setSelectedIndex(font.getStyle()); //初始化样式list
                if (font.getStyle() == 0) {
                    txtStyle.setText("常规");
                } else if (font.getStyle() == 1) {
                    txtStyle.setText("粗体");
                } else if (font.getStyle() == 2) {
                    txtStyle.setText("斜体");
                } else if (font.getStyle() == 3) {
                    txtStyle.setText("粗斜体");
                }
            }


            //大小
            add(lblSize);
            lblSize.setBounds(320, 10, 30, 20);
            txtSize.setEditable(false);
            add(txtSize);
            txtSize.setBounds(320, 30, 60, 20);
            add(spSize);
            spSize.setBounds(320, 50, 60, 100);
            lstSize.setSelectedValue("9", false);
            txtSize.setText("9");
            if (font != null) {
                lstSize.setSelectedValue(Integer.toString(font.getSize()), false);
                txtSize.setText(Integer.toString(font.getSize()));
            }

            //颜色
            add(lblColor);
            lblColor.setBounds(18, 220, 30, 20);
            cbColor.setBounds(18, 245, 100, 22);
            cbColor.setMaximumRowCount(5);
            add(cbColor);
            otherColor.setForeground(Color.blue);
            otherColor.setBounds(130, 245, 60, 22);
            otherColor.setCursor(new Cursor(Cursor.HAND_CURSOR));
            add(otherColor);

            //展示框
            showTF = new JTextField();
            showTF.setFont(new Font(current_fontName, current_fontStyle, current_fontSize));
            showTF.setBounds(10, 10, 300, 50);
            showTF.setHorizontalAlignment(JTextField.CENTER);
            showTF.setText(showStr);
            showTF.setBackground(Color.white);
            showTF.setEditable(false);
            showPan.setBorder(javax.swing.BorderFactory.createTitledBorder("示例"));
            add(showPan);
            showPan.setBounds(13, 150,370, 80);
            showPan.setLayout(new BorderLayout());
            showPan.add(showTF);
            if (font != null) {
                showTF.setFont(font); // 设置示例中的文字格式
            }
            if (font != null) {
                showTF.setForeground(color);
            }

            //确定和取消按钮
            add(ok);
            ok.setBounds(230, 245, 60, 20);
            add(cancel);
            cancel.setBounds(300, 245, 60, 20);
            //布局控件_结束

            //listener.....
            /*用户选择字体*/
            lstFont.addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent e) {
                    current_fontName = (String) lstFont.getSelectedValue();
                    txtFont.setText(current_fontName);
                    showTF.setFont(new Font(current_fontName, current_fontStyle, current_fontSize));
                }
            });

            /*用户选择字型*/
            lstStyle.addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent e) {
                    String value = (String) ((JList) e.getSource()).getSelectedValue();
                    if (value.equals("常规")) {
                        current_fontStyle = Font.PLAIN;
                    }
                    if (value.equals("斜体")) {
                        current_fontStyle = Font.ITALIC;
                    }
                    if (value.equals("粗体")) {
                        current_fontStyle = Font.BOLD;
                    }
                    if (value.equals("粗斜体")) {
                        current_fontStyle = Font.BOLD | Font.ITALIC;
                    }
                    txtStyle.setText(value);
                    showTF.setFont(new Font(current_fontName, current_fontStyle, current_fontSize));
                }
            });

            /*用户选择字体大小*/
            lstSize.addListSelectionListener(new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent e) {
                    current_fontSize = (Integer) sizeMap.get(lstSize.getSelectedValue());
                    txtSize.setText(String.valueOf(current_fontSize));
                    showTF.setFont(new Font(current_fontName, current_fontStyle, current_fontSize));
                }
            });

            /*用户选择字体颜色*/
            cbColor.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    current_color = (Color) colorMap.get(cbColor.getSelectedItem());
                    showTF.setForeground(current_color);
                }
            });
            /*其它颜色*/
            otherColor.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    Color col_temp = new JColorChooser().showDialog(null, null, Color.pink);
                    if (col_temp != null) {
                        current_color = col_temp;
                        showTF.setForeground(current_color);
                        super.mouseClicked(e);
                    }
                }
            });
            /*用户确定*/
            ok.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    /*用户用户选择的字体设置*/
                    setSelectedfont(new Font(current_fontName, current_fontStyle, current_fontSize));
                     /*用户用户选择的颜色设置*/
                    setSelectedcolor(current_color);
                    dialog.dispose();
                    dialog = null;
                }
            });

            /*用户取消*/
            cancel.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    dialog.dispose();
                    dialog = null;
                }
            });
        }

        /*显示字体选择器对话框(x,y表示窗体的启动位置)*/
        public void showDialog(Frame parent,int x,int y) {
            String  title = "字体";
            dialog = new JDialog(parent, title,true);
            dialog.add(this);
            dialog.setResizable(false);
            dialog.setSize(400, 310);
          //设置接界面的启动位置
            dialog.setLocation(x,y);
            dialog.addWindowListener(new WindowAdapter() {

                /*窗体关闭时调用*/
                public void windowClosing(WindowEvent e) {
                    dialog.removeAll();
                    dialog.dispose();
                    dialog = null;
                }
            });
            dialog.setVisible(true);
        }

        /*测试使用*/
//      public static void main(String[] args) {
//            JFontChooser one = new JFontChooser(new Font("方正舒体", Font.BOLD, 18), new Color(204,102,255));
////            JFontChooser one = new JFontChooser(); //无参
//              one.showDialog(null,500,200);
//              
//             
//      }
        public String getFontFamily() {
            return txtFont.getText();
        }
        public int getFontSize() {
            return Integer.parseInt(txtSize.getText()); 
        }
        public boolean isBold() {
            if (txtStyle.equals("粗体")) {
                return true;
            }
            return false;
        }
        public boolean isItalic() {
            if (txtStyle.equals("斜体")) {
                return true;
            }
            return false;
        }
        public boolean isBoldItalic() {
            if (txtStyle.equals("粗斜体")) {
                return true;
            }
            return false;
        }

    }  


还有:

package txtReader;

public class WordCount {
    // TODO caihao 2016-11-06 字数统计 工具类
    /**
    * 统计字数,参照MS office word 2007规则
    * @param context 文本内容
    * @return 字数
    */
    public int getMSWordsCount(String context){
    int words_count = 0;
    //中文单词
    String cn_words = context.replaceAll("[^(\\u4e00-\\u9fa5,。《》?;’‘:“”【】、)(……¥!·)]", "");
    int cn_words_count = cn_words.length();
    //非中文单词
    String non_cn_words = context.replaceAll("[^(a-zA-Z0-9`\\-=\';.,/~!@#$%^&*()_+|}{\":><?\\[\\])]", " ");
    int non_cn_words_count = 0;
    String[] ss = non_cn_words.split(" ");
    for(String s:ss){
    if(s.trim().length()!=0) non_cn_words_count++;
    }
    //中文和非中文单词合计
    words_count = cn_words_count + non_cn_words_count;
    return words_count;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_25222351/article/details/81666514