如何在JTextArea实例中为所选文本设置粗体字体样式

时间:2015-05-01 16:37:40

标签: java swing fonts jtextarea

我想在JTextArea实例中为所选文本设置粗体字体样式。

我试过这种方式:

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

但它不起作用。我也试过了JTextPaneJEditorPane而不是JTextArea但没有效果。

我该怎么做?

3 个答案:

答案 0 :(得分:1)

  

我想在JTextArea实例中为所选文本设置粗体字体样式。

JTextArea无法执行此操作。您需要使用JTextPane

然后,您可以使用Action提供的默认StyledEditorKit。创建JButtonJMenuItem来执行此操作:

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

将按钮或菜单项添加到框架中。然后使用可以单击按钮/菜单项以在选择后加粗文本。这是大多数编辑工作的方式。您也可以使用键盘调用Action to Action的加速度。

阅读Text Component Features上Swing教程中的部分,了解更多信息和工作示例。

答案 1 :(得分:1)

<强>简介

@Freek de Bruijn和@Gilbert Le Blanc已经发布了关于如何做你想做的事情的(有用的)答案,但没有一个解释为什么你要做的事情不起作用。

不是答案
  

我该怎么做?

的解释
  

但它不起作用。

编辑: @camickr发布了我认为正确的方法。

<强>答案

关于约JTextArea

的教程
  

您可以通过多种方式自定义文本区域。例如,虽然给定的文本区域只能以一种字体和颜色显示文本,但您可以设置它使用的字体和颜色。

(引言中的所有重点都是我的)和

  

如果您希望文本区域使用多种字体或其他样式显示其文本,则应使用编辑器窗格或文本窗格。

这是因为JTextArea使用PlainDocument(请参阅this):

  

PlainDocument为文字提供了一个基本容器,其中所有文字都以相同的字体显示

但是,JTextPane使用DefaultStyledDocument

  

用于没有特定格式的样式文本的容器。

答案 2 :(得分:0)

您可以使用类似于更改颜色的JTextPane组件,如以下答案中所述:How to set font color for selected text in jTextArea

例如:

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);
    }
}
相关问题