java - 格式化 HTMLEditorKit

标签 java html swing dom htmleditorkit

我正在尝试在 JTextPane 中进行一些基本的格式化。为此,我决定使用 html(HTMLDocument 和 HTMLEditorKit)。

这里是按钮的操作监听器代码,应使所选文本变为粗体

boldButton.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent arg0) {

                    System.out.print(outputTextPane.getSelectedText());

                        int offset = outputTextPane.getSelectionStart();
                        int length = outputTextPane.getSelectionEnd()-outputTextPane.getSelectionStart();
                        String content = "";
                        try {
                            content = outputDoc.getText(offset, length);
                        } catch (BadLocationException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }                   
                        try {
                            outputDoc.replace(offset, length, "", null);
                            outputKit.insertHTML(outputDoc, outputTextPane.getSelectionStart(), "<b>"+content+"</b>", 0, 0, HTML.Tag.B);

                        } catch (BadLocationException | IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

            }

        });

它可以工作,除非您尝试使粗体文本也带有下划线(基本上相同的 Action 监听器)。源代码如下所示:

text -> select "text" and press bold button
<b>text</b> -> select "x" and press underline button
<b>te</b><u>x</u><b>t</b>

最佳答案

Here is code of action listener of button that should make selected text bold

不要创建自己的操作。使用编辑器工具包提供的操作。例如:

JButton bold = new JButton( new StyledEditorKit.BoldAction() );

关于java - 格式化 HTMLEditorKit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15606622/

相关文章:

Java mouseListener 的 mousemove 不工作

java - 打破 Transformer 流程​​ Spring Integration

java - Android:操作栏内的 AppCompatActivity 和 textview

html - 如何在移动 View 中以不同的顺序渲染 HTML 元素?

html - 在嵌套的 flexboxes 的情况下居中失败

javascript - 复制和区分表格的部分

java - 如何使用字符串 JTree 创建节点?

java - java中枚举的优雅泛型 "Cross product"

java - 无法通过 JDBC 连接到虚拟机上的 Oracle 11g : Connection reset

Java 图形用户界面 : Can the JLabel hold an object/class?