【问题标题】:How to save font style and font size to rich text file in java如何在java中将字体样式和字体大小保存到富文本文件中
【发布时间】:2018-04-29 23:36:25
【问题描述】:

您好,我目前正在为大学的一个模块开发 Java 文本编辑器。我在获取字体样式和大小以保存到富文本文件时遇到了一些麻烦我目前正在使用 printwriter 方法将文本区域中的文本写入文件。我在下面包含了我的 saveFile 代码。这是我第一次发帖,如果我的帖子有任何问题,请提前致谢。

public class saveFile  implements ActionListener
{

    @Override
    public void actionPerformed(ActionEvent e){
        //allow user to enter file name
        String s = JOptionPane.showInputDialog("Input name of file:");
        String w = "";
        try
        {
            //Allow user to enter directory
            w = JOptionPane.showInputDialog("Input Directory where you want the file:\n"
                    + "eg C:\\ for C drive");
        }
        catch(Exception writeFile)
        {
            JOptionPane.showMessageDialog(null, "Task could not be completed\nPlease try again"
                    ,"File Write Error", JOptionPane.ERROR_MESSAGE, null);
        }
        //try catch block
        try
        {
            //check if fields are null or empty
            if(!(s.isEmpty() && w.isEmpty()) && (w != null && s != null))
            {
                try
                {
                    //Create new file and append with .rtf
                    File userFile =  new File(w + s + ".rtf"); 
                    PrintWriter file = new PrintWriter(userFile);
                    //set files content = text
                    file.print(text.getText());
                    file.close();
                    File dir = new File(w);
                    if(dir.exists())
                    {
                        JOptionPane.showMessageDialog(null, "File " +  s + " created\n" + "Saved in " + w, null,JOptionPane.PLAIN_MESSAGE );
                    }
                    else
                    {
                        throw new Exception();
                    }

                }
                catch(Exception fileNotCreatedException)
                {
                    JOptionPane.showMessageDialog(null,"File not created\n"
                            + "Please check to see directory exists","File Error", 
                            JOptionPane.ERROR_MESSAGE, null);
                    fileNotCreatedException.printStackTrace();
                }

            }
        }

【问题讨论】:

    标签: java fonts font-size rtf printwriter


    【解决方案1】:

    如果您使用内容类型text/rtf 使用 JTextPane 进行摇摆,则 RTFEditorKit 用于 StyledDocument。

    OutputStream out = new FileOutputStream(userFile);
    StyledDocument doc = textPane.getStyledDocument();
    StyledEditorKit editorKit = textPane.getStyledEditorKit();
    editorKit.write(out, doc, 0, doc.getLength());
    

    由于 HTMLEditorKit 也是基于 StyledDocument 的,因此有时可能需要先尝试 HTML,因为 HTML 语法更容易。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      • 2017-12-15
      • 1970-01-01
      相关资源
      最近更新 更多