1

I want to set bold font style for selected text in JTextArea instance.

I tried this way:

textArea.getSelectedText().setFont(new Font("sansserif",Font.BOLD, 12));

But it does not work. Also I've tried JTextPane and JEditorPane instead of JTextArea but without effect.

How can I do that?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Ehsan
  • 13
  • 1
  • 4
  • 1
    check this link: http://stackoverflow.com/questions/9141449/styling-text-in-a-jtextarea-or-jtextpane –  May 01 '15 at 16:49
  • i want to bold SELECTED text its affect on all of the text – Ehsan May 01 '15 at 16:52
  • The `textArea.getSelectedText()` method returns a string, so I'm unable to call `textArea.getSelectedText().setFont[...])`. – Freek de Bruijn May 01 '15 at 17:33

4 Answers4

1

I want to set bold font style for selected text in JTextArea instance.

You can't do this for a JTextArea. You need to use a JTextPane.

Then you can use the default Action provided by the StyledEditorKit. Create a JButton or JMenuItem to do this:

JButton boldButton = new JButton( new StyledEditorKit.BoldAction() );
JMenuItem boldMenuItem = new JMenuItem( new StyledEditorKit.BoldAction() );

Add the button or menu item to the frame. Then the use can click on the button/menu item to bold the text after it has been selected. This is the way most editor work. You can also add an acceleration to the Action to the Action can be invoked just by using the keyboard.

Read the section from the Swing tutorial on Text Component Features for more information and a working example.

user1803551
  • 12,965
  • 5
  • 47
  • 74
camickr
  • 321,443
  • 19
  • 166
  • 288
1

Introduction

The (useful) answers for how to do what you want to do have already been posted by @Freek de Bruijn and @Gilbert Le Blanc, but none of them explain why what you're trying to do doesn't work. This isn't an answer for

How can I do that?

but an explanation for

But it does not work.

Edit: @camickr posted what I believe is the correct approach.

Answer

From the tutorial about about JTextArea:

You can customize text areas in several ways. For example, although a given text area can display text in only one font and color, you can set which font and color it uses.

(all emphasis in quotes are mine) and

If you want the text area to display its text using multiple fonts or other styles, you should use an editor pane or text pane.

This is because JTextArea uses PlainDocument (see this):

PlainDocument provides a basic container for text where all the text is displayed in the same font.

However, a JTextPane uses DefaultStyledDocument:

a container for styled text in no particular format.

user1803551
  • 12,965
  • 5
  • 47
  • 74
  • `The (useful) answers for how to do what you want to do have already been posted by...` I would disagree with that. Those answer reinvent the wheel. The `StyledEditorKit` already provides this functionality. All you need to do is use the BoldAction. – camickr May 01 '15 at 19:34
  • @camickr I didn't say they were the correct answers. They just show a way to do what the OP wants to do, in that sense they are useful. I try to choose my words carefully :) – user1803551 May 01 '15 at 19:36
  • @camickr Edited my answer and +1'd yours. – user1803551 May 01 '15 at 19:40
0

You could use a JTextPane component similar to changing the color as described in the following answer: How to set font color for selected text in jTextArea.

For example:

import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.WindowConstants;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;

public class BoldSelected {
    public static void main(final String[] args) {
        new BoldSelected().launchGui();
    }

    private void launchGui() {
        final String title = "Set bold font style for selected text in JTextArea instance";
        final JFrame frame = new JFrame("Stack Overflow: " + title);
        frame.setBounds(100, 100, 800, 600);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        final JTextPane textPane = new JTextPane();
        textPane.setText(title + ".");
        final Style style = textPane.addStyle("Bold", null);
        StyleConstants.setBold(style, true);
        textPane.getStyledDocument().setCharacterAttributes(4, 33, style, false);
        frame.getContentPane().add(textPane);
        frame.setVisible(true);
    }
}
Community
  • 1
  • 1
Freek de Bruijn
  • 3,552
  • 2
  • 22
  • 28
0

You have to set up a caret listener on a JTextPane to listen for when some or all of the text is selected.

Here's the GUI I created.

JTextPane

And here's the code:

package com.ggl.testing;

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
import javax.swing.text.StyledDocument;

public class JTextPaneTest implements Runnable {

    private JTextPane textPane;

    private StyledDocument styledDocument;

    public static void main(String[] args) throws BadLocationException {
        SwingUtilities.invokeLater(new JTextPaneTest());
    }

    public JTextPaneTest() throws BadLocationException {
        this.styledDocument = new DefaultStyledDocument();
        this.styledDocument.insertString(0, displayText(), null);
        addStylesToDocument(styledDocument);
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("JTextPane Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationByPlatform(true);

        textPane = new JTextPane(styledDocument);
        textPane.addCaretListener(new SelectedText());
        textPane.setPreferredSize(new Dimension(250, 125));
        JScrollPane scrollPane = new JScrollPane(textPane);

        frame.add(scrollPane);
        frame.pack();
        frame.setVisible(true);
    }

    private String displayText() {
        return "This is some sample text.  Pick part of the text to select "
                + "by double clicking on a word.";
    }

    private void addStylesToDocument(StyledDocument styledDocument) {
        Style def = StyleContext.getDefaultStyleContext().getStyle(
                StyleContext.DEFAULT_STYLE);
        Style s = styledDocument.addStyle("bold", def);
        StyleConstants.setBold(s, true);
    }

    private class SelectedText implements CaretListener {

        @Override
        public void caretUpdate(CaretEvent event) {
            int dot = event.getDot();
            int mark = event.getMark();
            if (dot != mark) {
                if (dot < mark) {
                    int temp = dot;
                    dot = mark;
                    mark = temp;
                }
                boldSelectedText(mark, dot);
            }
        }

        private void boldSelectedText(int mark, int dot) {
            try {
                int length = dot - mark;
                String s = styledDocument.getText(mark, length);
                styledDocument.remove(mark, length);
                styledDocument.insertString(mark, s,
                        styledDocument.getStyle("bold"));
            } catch (BadLocationException e) {
                e.printStackTrace();
            }
        }

    }

}
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111