【问题标题】:How to set bold font style for selected text in JTextArea instance如何在 JTextArea 实例中为选定文本设置粗体字体样式
【发布时间】:2015-05-02 03:40:00
【问题描述】:

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

我试过这样:

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

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

我该怎么做?

【问题讨论】:

  • 我想将所选文本加粗,它对所有文本的影响
  • textArea.getSelectedText() 方法返回一个字符串,所以我无法调用textArea.getSelectedText().setFont[...])

标签: java swing fonts jtextarea


【解决方案1】:

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

您不能为JTextArea 执行此操作。您需要使用JTextPane

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

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

将按钮或菜单项添加到框架中。然后用户可以单击按钮/菜单项以在文本被选中后将其加粗。这是大多数编辑器的工作方式。也可以给Action加一个加速,只用键盘就可以调用Action。

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

【讨论】:

    【解决方案2】:

    简介

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

    我该怎么做?

    不过是对

    的解释

    但它不起作用。

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

    回答

    来自关于JTextArea的教程:

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

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

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

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

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

    但是,JTextPane 使用 DefaultStyledDocument

    无特定格式的样式文本的容器。

    【讨论】:

    • The (useful) answers for how to do what you want to do have already been posted by... 我不同意这一点。这些答案重新发明了轮子。 StyledEditorKit 已经提供了这个功能。您需要做的就是使用 BoldAction。
    • @camickr 我没有说它们是正确的答案。它们只是展示了一种方法来做 OP 想要做的事情,从这个意义上说它们是有用的。我试着仔细选择我的话:)
    • @camickr 编辑了我的答案并为你的答案 +1。
    【解决方案3】:

    您必须在 JTextPane 上设置插入符号侦听器,以便在选择部分或全部文本时进行侦听。

    这是我创建的 GUI。

    这是代码:

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

    【讨论】:

    • "您必须在 JTextArea 上设置插入符号侦听器",但您需要为 JTextPane 这样做。
    • @user1803551:你说得对。 JTextArea 没有支持它的样式化文档。我忘了更改 JFrame 标题。我已经确定了答案。
    【解决方案4】:

    您可以使用类似于更改颜色的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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-23
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多