首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >格式化HTMLEditorKit

格式化HTMLEditorKit
EN

Stack Overflow用户
提问于 2013-03-25 10:14:22
回答 1查看 711关注 0票数 1

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

以下是按钮的操作侦听器的代码,它应该将选定的文本设置为粗体

代码语言:javascript
复制
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();
                        }

            }

        });

它是有效的,除非您尝试使粗体文本也加下划线(基本上相同的操作侦听器)。源代码看起来是这样的:

代码语言:javascript
复制
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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-25 11:28:49

这里是按钮的操作侦听器的代码,它应该将选定的文本设置为粗体

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

代码语言:javascript
复制
JButton bold = new JButton( new StyledEditorKit.BoldAction() );
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15606622

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档