質問

I am trying to do some basic formatting in JTextPane. For that purpose I decided to use html (HTMLDocument and HTMLEditorKit).

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

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();
                        }

            }

        });

It works except when you try to make bold text also underlined (basically same action listener). Source code looks like this then:

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

Don't create your own Action. Use the Actions provided by the editor kit. For example:

JButton bold = new JButton( new StyledEditorKit.BoldAction() );
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top