在Swing的JTextPane中设置标签策略 [英] Setting the tab policy in Swing's JTextPane

查看:84
本文介绍了在Swing的JTextPane中设置标签策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的JTextPane每次按Tab时都插入空格.当前,它会插入制表符(ASCII 9).

I want my JTextPane to insert spaces whenever I press Tab. Currently it inserts the tab character (ASCII 9).

反正有没有自定义JTextPane的选项卡策略(除了捕获"tab-key"事件并插入自己看来是空格的东西)?

Is there anyway to customize the tab policy of JTextPane (other than catching "tab-key" events and inserting the spaces myself seems an)?

推荐答案

您可以在JTextPane上设置javax.swing.text.Document.以下示例将使您了解我的意思:)

You can set a javax.swing.text.Document on your JTextPane. The following example will give you an idea of what I mean :)

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;

public class Tester {

    public static void main(String[] args) {
        JTextPane textpane = new JTextPane();
        textpane.setDocument(new TabDocument());
        JFrame frame = new JFrame();
        frame.getContentPane().add(textpane);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(new Dimension(200, 200));
        frame.setVisible(true);
    }

    static class TabDocument extends DefaultStyledDocument {
        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            str = str.replaceAll("\t", " ");
            super.insertString(offs, str, a);
        }
    }
}

定义一个DefaultStyleDocument来完成这项工作.然后将文档设置为您的JTextPane.

Define a DefaultStyleDocument to do the work. Then set the Document to your JTextPane.

欢呼 凯

这篇关于在Swing的JTextPane中设置标签策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆