如何在JTextPane中放置光标或选择文本时更改JCombobox中对应的字体名称?

How to change the corresponding font name in JCombobox while placing the cursor or selecting the text in JTextPane?

我正在 Java Swing 中创建一个文本编辑器应用程序。我正在使用 JTextPane 并添加了代码以在 JComboBox 中获取所有系统字体和一些字体大小。

我在 jtextpane 中输入了文本 - "Hello World",并将单词 "Hello" 的字体更改为 "Arial",字体大小更改为 10,将 "World" 更改为 "Calibri",字体大小为12.

我预期的场景: 如果我 select 单词 "Hello" 或将光标放在单词 "Hello" 中,字体 JCombobox 中的字体名称应自动更改为 "Arial" 并且字体大小 Jcombobox 应为自动更改为 10,与单词 "World" 相同,Jcombobox 中的值应更改为 "Calibri" 和“12”。我怎样才能做到这一点? 提前致谢。

这基本上解决了如何 select 与 selected 文本或光标在文本中的位置对应的组合框项目的问题。例如,我只选择了字体大小。同样的技术也可以应用于字体系列。

示例是使用 JTextPane 的文本编辑器,其文档类型是 DefaultStyledDocument。有一个带有字体大小列表(16 到 50)的 JComboBox。可以 select 编辑器中的一段文本和 select 组合框中的字体大小,以将文本设置为该字体大小。这是通过将 ItemListener 添加到 JComboBox 来实现的。侦听器具有将编辑器文档的属性设置为新 selected 字体大小的代码 - selected 文本。

编辑器允许将多种字体大小应用于文本的不同部分,如下图所示。


要求是当插入符(或光标)位于文本或 selected 文本的一部分时 - 需要在 [=13] 中设置相应的字体大小=] 与字体大小。为此,将 CaretListener 添加到 JTextPane

这个监听器的逻辑主要是定位插入符位置,获取该位置文档文本的属性并提取字体大小属性。此属性的字体大小在字体大小组合框中设置。

示例代码:

public class Editor2 {

    private JTextPane editor;
    private DefaultStyledDocument doc;
    private JComboBox<String> fontSizeComboBox;
    private boolean caretControlFlag;
    private static final int DEFAULT_FONT_SIZE = 18;

    public static void main(String [] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Editor2().createAndShowGUI();
            }
        });
    }

    private void createAndShowGUI() {
        editor = new JTextPane();
        editor.setMargin(new Insets(5, 5, 5, 5));
        editor.addCaretListener(new MyCaretListener());     
        JScrollPane editorScrollPane = new JScrollPane(editor);
        doc = new DefaultStyledDocument();
        initDocAttrs();
        editor.setDocument(doc);

        final String [] fontSizes = {"Font Size", "16", "18", 
            "20", "24", "28", "30", "34", "40", "50"};
        fontSizeComboBox = new JComboBox<String>(fontSizes);
        fontSizeComboBox.setEditable(false);
        fontSizeComboBox.addItemListener(new FontSizeItemListener());
        JFrame frame = new JFrame("Text Editor");
        frame.add(fontSizeComboBox, BorderLayout.NORTH);
        frame.add(editorScrollPane, BorderLayout.CENTER);
        frame.add(editorScrollPane);
        frame.setSize(800, 400);
        frame.setLocation(300, 150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        editor.requestFocusInWindow();
    }

    private void initDocAttrs() {
        Style style = doc.addStyle("my_doc_style", null);
        StyleConstants.setFontSize(style, 18);
        StyleConstants.setFontFamily(style, "SansSerif");
        doc.setParagraphAttributes(0, doc.getLength(), style, true);
    }

    private class FontSizeItemListener implements ItemListener {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if ((e.getStateChange() != ItemEvent.SELECTED) ||
                    (fontSizeComboBox.getSelectedIndex() == 0)) {
                return;
            }
            String fontSizeStr = (String) e.getItem();
            int newFontSize = 0;
            try {
                newFontSize = Integer.parseInt(fontSizeStr);
            }
            catch (NumberFormatException ex) {
                return;
            }
            if (caretControlFlag) {
                caretControlFlag = false;
                return;
            }
            setFontAttrs(newFontSize);
            editor.requestFocusInWindow();
        }

        private void setFontAttrs(int newFontSize) {
            SimpleAttributeSet attrs = new SimpleAttributeSet();
            Style docStyle = doc.getStyle("my_doc_style");  
            int size = StyleConstants.getFontSize(docStyle);
            StyleConstants.setFontSize(attrs, newFontSize);
            String attrName = "mysize" + Integer.toString(newFontSize);
            attrs.addAttribute(attrName, attrName);

            int startPos = editor.getSelectionStart();
            String selectedText = editor.getSelectedText();
            if (selectedText == null || selectedText.trim().isEmpty()) {
                return;
            }
            int length = selectedText.length(); 
            doc.setCharacterAttributes(startPos, length, attrs, false);     
            editor.setDocument(doc);
        }
    }


    private class MyCaretListener implements CaretListener {
        @Override
        public void caretUpdate(CaretEvent e) {
            caretControlFlag = true;
            int dot = e.getDot();
            Element ele = doc.getCharacterElement(dot);
            AttributeSet attrs = ele.getAttributes();
            String fontSizeStr = "18";
            for (Enumeration en = attrs.getAttributeNames(); en.hasMoreElements();) {
                String attrName = en.nextElement().toString();
                if (attrName.contains("mysize")) {
                    fontSizeStr = attrName.substring(6);
                }
            }
            fontSizeComboBox.setSelectedItem(fontSizeStr);
            caretControlFlag = false;
        }
    }
}