1

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>
4

1 に答える 1

3

選択したテキストを太字にするボタンのアクションリスナーのコードは次のとおりです

独自のアクションを作成しないでください。エディターキットが提供するアクションを使用します。例えば:

JButton bold = new JButton( new StyledEditorKit.BoldAction() );
于 2013-03-25T03:28:48.953 に答える