JTextPane样式文本编辑

wen java案例 1

我来为您详细介绍如何使用JTextPane进行样式文本编辑。

JTextPane样式文本编辑

JTextPane 样式文本编辑指南

基本设置

import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
public class StyleTextEditor {
    public static void main(String[] args) {
        JFrame frame = new JFrame("样式文本编辑器");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 400);
        // 创建JTextPane
        JTextPane textPane = new JTextPane();
        textPane.setFont(new Font("宋体", Font.PLAIN, 14));
        // 添加到滚动面板
        JScrollPane scrollPane = new JScrollPane(textPane);
        frame.add(scrollPane);
        frame.setVisible(true);
    }
}

应用文本样式

public void applyStyles(JTextPane textPane) {
    StyledDocument doc = textPane.getStyledDocument();
    // 创建各种样式
    Style defaultStyle = StyleContext.getDefaultStyleContext()
        .getStyle(StyleContext.DEFAULT_STYLE);
    // 粗体样式
    Style bold = doc.addStyle("bold", defaultStyle);
    StyleConstants.setBold(bold, true);
    // 斜体样式
    Style italic = doc.addStyle("italic", defaultStyle);
    StyleConstants.setItalic(italic, true);
    // 带颜色样式
    Style redStyle = doc.addStyle("red", defaultStyle);
    StyleConstants.setForeground(redStyle, Color.RED);
    StyleConstants.setFontSize(redStyle, 16);
    try {
        // 插入不同样式的文本
        doc.insertString(0, "这是普通文本\n", defaultStyle);
        doc.insertString(doc.getLength(), "这是粗体文本\n", bold);
        doc.insertString(doc.getLength(), "这是斜体文本\n", italic);
        doc.insertString(doc.getLength(), "这是红色大号文本\n", redStyle);
    } catch (BadLocationException e) {
        e.printStackTrace();
    }
}

实时样式切换

class StyleEditorPanel extends JPanel {
    private JTextPane textPane;
    private StyledDocument doc;
    public StyleEditorPanel() {
        setLayout(new BorderLayout());
        // 创建工具栏
        JToolBar toolbar = createToolBar();
        add(toolbar, BorderLayout.NORTH);
        // 创建文本面板
        textPane = new JTextPane();
        doc = textPane.getStyledDocument();
        add(new JScrollPane(textPane), BorderLayout.CENTER);
    }
    private JToolBar createToolBar() {
        JToolBar toolbar = new JToolBar();
        // 粗体按钮
        JButton boldBtn = new JButton("B");
        boldBtn.setFont(new Font("Arial", Font.BOLD, 14));
        boldBtn.addActionListener(e -> applyBold());
        toolbar.add(boldBtn);
        // 斜体按钮
        JButton italicBtn = new JButton("I");
        italicBtn.setFont(new Font("Arial", Font.ITALIC, 14));
        italicBtn.addActionListener(e -> applyItalic());
        toolbar.add(italicBtn);
        // 下划线按钮
        JButton underlineBtn = new JButton("U");
        underlineBtn.setFont(new Font("Arial", Font.PLAIN, 14));
        underlineBtn.addActionListener(e -> applyUnderline());
        toolbar.add(underlineBtn);
        // 颜色选择器
        JButton colorBtn = new JButton("颜色");
        colorBtn.addActionListener(e -> chooseColor());
        toolbar.add(colorBtn);
        // 字体大小选择器
        JComboBox<Integer> sizeCombo = new JComboBox<>(new Integer[]{10, 12, 14, 16, 18, 20, 24, 28, 32});
        sizeCombo.addActionListener(e -> applyFontSize((Integer) sizeCombo.getSelectedItem()));
        toolbar.add(new JLabel("字号:"));
        toolbar.add(sizeCombo);
        return toolbar;
    }
    private void applyBold() {
        applyStyle(StyleConstants.Bold, !isStyleActive(StyleConstants.Bold));
    }
    private void applyItalic() {
        applyStyle(StyleConstants.Italic, !isStyleActive(StyleConstants.Italic));
    }
    private void applyUnderline() {
        applyStyle(StyleConstants.Underline, !isStyleActive(StyleConstants.Underline));
    }
    private void applyStyle(Object style, boolean value) {
        int start = textPane.getSelectionStart();
        int end = textPane.getSelectionEnd();
        if (start != end) {
            // 对选中文本应用样式
            if (style == StyleConstants.Bold) {
                StyleConstants.setBold(textPane.getCharacterAttributes(), value);
            } else if (style == StyleConstants.Italic) {
                StyleConstants.setItalic(textPane.getCharacterAttributes(), value);
            } else if (style == StyleConstants.Underline) {
                StyleConstants.setUnderline(textPane.getCharacterAttributes(), value);
            }
            // 应用样式到选中文本
            MutableAttributeSet attrs = textPane.getInputAttributes();
            textPane.setCharacterAttributes(attrs, true);
        }
    }
    private boolean isStyleActive(Object style) {
        AttributeSet attrs = textPane.getCharacterAttributes();
        if (style == StyleConstants.Bold) {
            return StyleConstants.isBold(attrs);
        } else if (style == StyleConstants.Italic) {
            return StyleConstants.isItalic(attrs);
        } else if (style == StyleConstants.Underline) {
            return StyleConstants.isUnderline(attrs);
        }
        return false;
    }
    private void chooseColor() {
        Color color = JColorChooser.showDialog(this, "选择颜色", Color.BLACK);
        if (color != null) {
            MutableAttributeSet attrs = new SimpleAttributeSet();
            StyleConstants.setForeground(attrs, color);
            textPane.setCharacterAttributes(attrs, true);
        }
    }
    private void applyFontSize(int size) {
        MutableAttributeSet attrs = new SimpleAttributeSet();
        StyleConstants.setFontSize(attrs, size);
        textPane.setCharacterAttributes(attrs, true);
    }
}

段落样式控制

public void applyParagraphStyles(JTextPane textPane) {
    StyledDocument doc = textPane.getStyledDocument();
    // 创建段落样式
    SimpleAttributeSet centerAlign = new SimpleAttributeSet();
    StyleConstants.setAlignment(centerAlign, StyleConstants.ALIGN_CENTER);
    SimpleAttributeSet rightAlign = new SimpleAttributeSet();
    StyleConstants.setAlignment(rightAlign, StyleConstants.ALIGN_RIGHT);
    SimpleAttributeSet leftAlign = new SimpleAttributeSet();
    StyleConstants.setAlignment(leftAlign, StyleConstants.ALIGN_LEFT);
    try {
        // 插入不同对齐方式的段落
        doc.insertString(0, "左对齐文本\n", null);
        doc.setParagraphAttributes(0, 7, leftAlign, false);
        doc.insertString(doc.getLength(), "居中对齐文本\n", null);
        doc.setParagraphAttributes(doc.getLength() - 8, 8, centerAlign, false);
        doc.insertString(doc.getLength(), "右对齐文本\n", null);
        doc.setParagraphAttributes(doc.getLength() - 7, 7, rightAlign, false);
    } catch (BadLocationException e) {
        e.printStackTrace();
    }
}

样式工具类

public class StyleUtils {
    // 设置选中文本的颜色
    public static void setTextColor(JTextPane textPane, Color color) {
        MutableAttributeSet attrs = new SimpleAttributeSet();
        StyleConstants.setForeground(attrs, color);
        textPane.setCharacterAttributes(attrs, true);
    }
    // 设置选中文本的背景色
    public static void setTextBackgroundColor(JTextPane textPane, Color color) {
        MutableAttributeSet attrs = new SimpleAttributeSet();
        StyleConstants.setBackground(attrs, color);
        textPane.setCharacterAttributes(attrs, true);
    }
    // 设置字体
    public static void setFont(JTextPane textPane, String fontName) {
        MutableAttributeSet attrs = new SimpleAttributeSet();
        StyleConstants.setFontFamily(attrs, fontName);
        textPane.setCharacterAttributes(attrs, true);
    }
    // 设置字体大小
    public static void setFontSize(JTextPane textPane, int size) {
        MutableAttributeSet attrs = new SimpleAttributeSet();
        StyleConstants.setFontSize(attrs, size);
        textPane.setCharacterAttributes(attrs, true);
    }
    // 添加超链接样式
    public static void makeHyperlink(JTextPane textPane, String url) {
        MutableAttributeSet attrs = new SimpleAttributeSet();
        StyleConstants.setUnderline(attrs, true);
        StyleConstants.setForeground(attrs, Color.BLUE);
        attrs.addAttribute(AttributeSet.NameAttribute, url);
        textPane.setCharacterAttributes(attrs, false);
    }
}

完整示例 - 简易富文本编辑器

public class RichTextEditor extends JFrame {
    private JTextPane textPane;
    private boolean isBold = false;
    private boolean isItalic = false;
    private boolean isUnderline = false;
    public RichTextEditor() {
        setTitle("简易富文本编辑器");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 600);
        initUI();
        setVisible(true);
    }
    private void initUI() {
        setLayout(new BorderLayout());
        // 菜单栏
        JMenuBar menuBar = new JMenuBar();
        JMenu fileMenu = new JMenu("文件");
        JMenuItem saveItem = new JMenuItem("保存");
        JMenuItem exitItem = new JMenuItem("退出");
        fileMenu.add(saveItem);
        fileMenu.add(exitItem);
        menuBar.add(fileMenu);
        setJMenuBar(menuBar);
        // 工具栏
        JToolBar toolbar = new JToolBar();
        // 样式按钮
        JToggleButton boldBtn = new JToggleButton("粗体");
        boldBtn.addActionListener(e -> {
            isBold = !isBold;
            toggleBold();
        });
        toolbar.add(boldBtn);
        JToggleButton italicBtn = new JToggleButton("斜体");
        italicBtn.addActionListener(e -> {
            isItalic = !isItalic;
            toggleItalic();
        });
        toolbar.add(italicBtn);
        JToggleButton underlineBtn = new JToggleButton("下划线");
        underlineBtn.addActionListener(e -> {
            isUnderline = !isUnderline;
            toggleUnderline();
        });
        toolbar.add(underlineBtn);
        toolbar.addSeparator();
        // 字体选择
        String[] fonts = GraphicsEnvironment.getLocalGraphicsEnvironment()
            .getAvailableFontFamilyNames();
        JComboBox<String> fontCombo = new JComboBox<>(fonts);
        fontCombo.addActionListener(e -> changeFont((String) fontCombo.getSelectedItem()));
        toolbar.add(new JLabel("字体:"));
        toolbar.add(fontCombo);
        // 字号选择
        Integer[] sizes = {8, 10, 12, 14, 16, 18, 20, 24, 28, 32, 36, 48, 72};
        JComboBox<Integer> sizeCombo = new JComboBox<>(sizes);
        sizeCombo.setSelectedItem(12);
        sizeCombo.addActionListener(e -> changeFontSize((Integer) sizeCombo.getSelectedItem()));
        toolbar.add(new JLabel("字号:"));
        toolbar.add(sizeCombo);
        add(toolbar, BorderLayout.NORTH);
        // 文本编辑区
        textPane = new JTextPane();
        add(new JScrollPane(textPane), BorderLayout.CENTER);
        // 状态栏
        JPanel statusBar = new JPanel(new FlowLayout(FlowLayout.LEFT));
        JLabel statusLabel = new JLabel("就绪");
        statusBar.add(statusLabel);
        add(statusBar, BorderLayout.SOUTH);
    }
    private void toggleBold() {
        MutableAttributeSet attrs = new SimpleAttributeSet();
        StyleConstants.setBold(attrs, isBold);
        textPane.setCharacterAttributes(attrs, false);
    }
    private void toggleItalic() {
        MutableAttributeSet attrs = new SimpleAttributeSet();
        StyleConstants.setItalic(attrs, isItalic);
        textPane.setCharacterAttributes(attrs, false);
    }
    private void toggleUnderline() {
        MutableAttributeSet attrs = new SimpleAttributeSet();
        StyleConstants.setUnderline(attrs, isUnderline);
        textPane.setCharacterAttributes(attrs, false);
    }
    private void changeFont(String fontName) {
        MutableAttributeSet attrs = new SimpleAttributeSet();
        StyleConstants.setFontFamily(attrs, fontName);
        textPane.setCharacterAttributes(attrs, false);
    }
    private void changeFontSize(int size) {
        MutableAttributeSet attrs = new SimpleAttributeSet();
        StyleConstants.setFontSize(attrs, size);
        textPane.setCharacterAttributes(attrs, false);
    }
}
  1. 样式应用方式

    • 通过 StyledDocument 插入带样式的文本
    • 通过 AttributeSet 实时修改选中文本样式
  2. 常用样式属性

    • 字体:FontFamily, FontSize, Bold, Italic
    • 颜色:Foreground, Background
    • 装饰:Underline, StrikeThrough
    • 段落:Alignment, LineSpacing, FirstLineIndent
  3. 注意事项

    • 使用 SimpleAttributeSet 创建新样式
    • 使用 StyleConstants 设置样式属性
    • 使用 setCharacterAttributes 应用字符样式
    • 使用 setParagraphAttributes 应用段落样式

JTextPane 提供了丰富的样式编辑功能,适合实现简单的富文本编辑器,对于更复杂的需求,可以考虑使用 JavaFX 或第三方库。

抱歉,评论功能暂时关闭!