简体   繁体   English

如何清除JTextPane中的所有样式?

[英]How to clear all the styles in JTextPane?

I am creating a simple .rtf file editor application using RTFEditorKit() . 我正在使用RTFEditorKit()创建一个简单的.rtf文件编辑器应用程序。 I have added code to create a new document, open an .rtf document, save as an .rtf document, and to add styles to the content of the document such as bold, italics and underline. 我添加了代码来创建新文档,打开.rtf文档,另存为.rtf文档,以及向文档内容添加样式,例如粗体,斜体和下划线。

I am using a JTextPane . 我正在使用JTextPane


Here is my problem: I have added some styles to the content (eg bold, italics, underline or color) to the text. 这是我的问题:我在内容中添加了一些样式(例如,粗体,斜体,下划线或颜色)。 Then, saving or without saving that document I am opening a new document by clicking on the "New Document" icon. 然后,保存或不保存该文档,通过单击“新建文档”图标打开一个新文档。

If I enter some text in the New document, the text is displaying with the bold, italics, underline and color styles that I used in the previous document; 如果我在“新建”文档中输入一些文本,则该文本将以我在上一个文档中使用的粗体,斜体,下划线和颜色样式显示。 whereas I would have expected these to have been cleared. 而我原本希望这些会被清除。

How can I achieve this? 我该如何实现? I have tried three different ways in "New Document" action listener - none of them work. 我在“新文档”操作侦听器中尝试了三种不同的方法-它们都不起作用。 These can be seen below: 这些可以在下面看到:

StyledDocument styledDocument = new DefaultStyledDocument();
textPane.setStyledDocument(styledDocument = new DefaultStyledDocument());

Style bold = textPane.addStyle("bold", null);
textPane.getStyledDocument().setCharacterAttributes(0, textPane.getStyledDocument().getLength(), bold, false);

textPane.setFont(new Font("Arial", Font.PLAIN, 15));
textPane.setText("");

My application minimal code: 我的应用程序最小代码:

public class MyNotepadMini implements ActionListener {
public static JFrame frame;
public static JPanel panel;
public static JTextPane textPane;
public static RTFEditorKit rtf;
public static StyleContext styleContext;
public static DefaultStyledDocument defaultStyleDoc;
public static JScrollPane scrollPane;
public static JMenuBar menuBar;
public static JMenu fileMenu;
public static JMenu editMenu;
public static JMenu formatMenu;
public static JMenuItem newSubMenu;
public static JMenuItem openSubMenu;
public static JMenuItem save;
public static JMenuItem saveAs;
public static JMenuItem cut;
public static JMenuItem copy;
public static JMenuItem paste;
public static JMenuItem selectAll;
public static JMenuItem bold;
public static JMenuItem italic;
public static JMenuItem underline;
public static JMenuItem exit;
public static JFileChooser fc;
public static boolean openFileExtFlag = true;
public static boolean saveFileExtFlag = true;
public static File openFile;
public static File saveFile;
public static boolean saveWindowTitle = false;
public static boolean openFileFlag;
public static boolean saveFileFlag;
public static boolean saved = true;
public static boolean dontSaveOption;
public static BufferedReader br;
public static boolean saveForNewOpenExitListener;
public static boolean saveAsFlag;
public static int returnVal;
public static String filePath;
public static boolean flagForOpenListener;
public static StyledDocument styledDocument;
public static Style defaultStyle;

public MyNotepadMini() {
    try {
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception e) {
        e.printStackTrace();
    }
    frame = new JFrame("My Notepad");
    panel = new JPanel(new BorderLayout());      

    styledDocument = new DefaultStyledDocument();
    rtf = new RTFEditorKit();
    textPane = new JTextPane(styledDocument);
    textPane.setEditorKit(rtf);
    styleContext = new StyleContext();

    scrollPane = new JScrollPane();
    scrollPane.getViewport().add(textPane);
    menuBar = new JMenuBar();
    fileMenu = new JMenu("File");
    fileMenu.setMnemonic(KeyEvent.VK_F);
    newSubMenu = new JMenuItem("New");
    newSubMenu.setAccelerator(KeyStroke.getKeyStroke('N', CTRL_DOWN_MASK));
    openSubMenu = new JMenuItem("Open...");
    openSubMenu.setAccelerator(KeyStroke.getKeyStroke('O', CTRL_DOWN_MASK));
    save = new JMenuItem("Save");
    save.setAccelerator(KeyStroke.getKeyStroke('S', CTRL_DOWN_MASK));
    editMenu = new JMenu("Edit");
    editMenu.setMnemonic(KeyEvent.VK_E);
    cut = new JMenuItem("Cut");
    cut.setAccelerator(KeyStroke.getKeyStroke('X', CTRL_DOWN_MASK));
    copy = new JMenuItem("Copy");
    copy.setAccelerator(KeyStroke.getKeyStroke('C', CTRL_DOWN_MASK));
    paste = new JMenuItem("Paste");
    paste.setAccelerator(KeyStroke.getKeyStroke('V', CTRL_DOWN_MASK));
    selectAll = new JMenuItem("Select All");
    selectAll.setAccelerator(KeyStroke.getKeyStroke('A', CTRL_DOWN_MASK));
    exit = new JMenuItem("Exit");
    exit.setMnemonic(KeyEvent.VK_X);
    formatMenu = new JMenu("Format");
    formatMenu.setMnemonic(KeyEvent.VK_F);
    bold = new JMenuItem(new StyledEditorKit.BoldAction());
    bold.setText("Bold");
    bold.setMnemonic(KeyEvent.VK_B);
    bold.setAccelerator(KeyStroke.getKeyStroke('B', CTRL_DOWN_MASK));
    italic = new JMenuItem(new StyledEditorKit.ItalicAction());
    italic.setText("Italic");
    italic.setMnemonic(KeyEvent.VK_I);
    italic.setAccelerator(KeyStroke.getKeyStroke('I', CTRL_DOWN_MASK));
    underline = new JMenuItem(new StyledEditorKit.UnderlineAction());
    underline.setText("Underline");
    underline.setMnemonic(KeyEvent.VK_U);
    underline.setAccelerator(KeyStroke.getKeyStroke('U', CTRL_DOWN_MASK));

    defaultStyle = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);

    cut.addActionListener(this);
    copy.addActionListener(this);
    paste.addActionListener(this);
    selectAll.addActionListener(this);
    exit.addActionListener(this);
    newSubMenu.addActionListener(this);

    editMenu.addMenuListener(new MenuListener() {
        public void menuSelected(MenuEvent event) {
            if (textPane.getSelectionStart() == textPane.getSelectionEnd()) {
                cut.setEnabled(false);
                copy.setEnabled(false);
            } else {
                cut.setEnabled(true);
                copy.setEnabled(true);
            }
        }

        public void menuDeselected(MenuEvent event) {
        }

        public void menuCanceled(MenuEvent event) {  
        }
    });

    scrollPane.setPreferredSize(new Dimension(700,500));
    fileMenu.add(newSubMenu);
    fileMenu.add(openSubMenu);
    fileMenu.add(save);
    fileMenu.add(exit);
    editMenu.add(cut);
    editMenu.add(copy);
    editMenu.add(paste);
    editMenu.addSeparator();
    editMenu.add(selectAll);
    formatMenu.add(bold);
    formatMenu.add(italic);
    formatMenu.add(underline);
    menuBar.add(fileMenu);
    menuBar.add(editMenu);
    menuBar.add(formatMenu);

    textPane.setFont(new Font("Arial", Font.PLAIN, 12));    
    panel.add(scrollPane, BorderLayout.CENTER);
    panel.add(new JLabel(" "), BorderLayout.EAST);
    panel.add(new JLabel(" "), BorderLayout.WEST);
    panel.add(new JLabel(" "), BorderLayout.SOUTH);

    frame.setJMenuBar(menuBar);
    frame.add(panel);
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    frame.pack();
    textPane.requestFocus();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

public static void main(String[] args) {
    new MyNotepadMini();
}

public void actionPerformed(ActionEvent ae) {
    if ((ae.getSource() == cut)) {
        textPane.cut();
        textPane.requestFocus();
    } else if ((ae.getSource() == copy)) {
        textPane.copy();
        textPane.requestFocus();
    } else if ((ae.getSource() == paste)) {
        textPane.paste();
        textPane.requestFocus();
    } else if (ae.getSource() == selectAll) {
        textPane.selectAll();
    } else if ((ae.getSource() == exit)){   
        System.exit(0);
    } else if ((ae.getSource() == newSubMenu)) {                        /** New document **/
            textPane.setText("");
            textPane.setStyledDocument(styledDocument = new DefaultStyledDocument());

            Style bold = textPane.addStyle("bold", null);
            textPane.getStyledDocument().setCharacterAttributes(0, textPane.getStyledDocument().getLength(), bold, false);

            /*sampleDocument.setCharacterAttributes(0, sampleDocument.getLength(), defaultStyle, true);
              defaultStyleDoc = new DefaultStyledDocument(styleContext);
              textPane.setDocument(defaultStyleDoc);*/

            /*textPane.setFont(new Font("Arial", Font.PLAIN, 15));
            textPane.setText("");*/

            textPane.requestFocus();
        } 
}

} }

I have given the minimal code here. 我在这里给出了最少的代码。

That is not the minimal code or a proper MCVE". 那不是最小的代码或适当的MCVE”。

  1. We should be able to copy/paste/compile/test. 我们应该能够复制/粘贴/编译/测试。 So you need to include the import statements 所以你需要包括导入语句

  2. The cut/copy/paste Actions and menu items are not relevant to the problem so they should not be included. 剪切/复制/粘贴操作和菜单项与问题无关,因此不应包括在内。

We only have a certain amount of time to answer questions so we only want to look at minimal code that is directly related to the problem. 我们只有一定的时间来回答问题,因此我们只想查看与问题直接相关的最少代码。

How to get rid of these styles in the New document - the text should be plain. 如何在“新文档”中摆脱这些样式-文本应为纯文本。

The problem is not the Document. 问题不在于文档。

Every time the caret of the text pane is moved the text pane keeps track of the input attributes at the caret position. 每次移动文本窗格的插入标记时,文本窗格都会在插入标记位置跟踪输入属性。 So when you create the new Document if the caret happens to be positioned on a character with the 3 attributes, those attributes are retained the next time you start typing. 因此,当您创建新文档时,如果插入符号恰好位于具有3个属性的字符上,则这些属性将在您下次开始键入时保留。

You can clear these attributes by using: 您可以使用以下命令清除这些属性:

MutableAttributeSet mas = textPane.getInputAttributes();
System.out.println("before: " + mas);
mas.removeAttributes(mas);
System.out.println("after: " + mas);

when you create your new Document. 当您创建新文档时。

Also, 也,

public static JFrame frame;
public static JPanel panel;
public static JTextPane textPane;

You should not be using the static keyword an any of your variables. 您不应该在任何变量中使用static关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM