【问题标题】:Formatting HTMLEditorKit格式化 HTMLEditorKit
【发布时间】:2013-03-14 10:49:40
【问题描述】:

我正在尝试在 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();
                        }

            }

        });

除非您尝试将粗体文本也加下划线(基本上相同的动作侦听器),否则它可以工作。那么源代码是这样的:

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>

【问题讨论】:

    标签: java html swing dom htmleditorkit


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢,我不敢相信解决方案如此简单。我花了大约 3 个小时才弄清楚这一点......
    猜你喜欢
    • 2010-11-21
    • 2012-02-29
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 2023-04-10
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多