I make The C language code editor on the Java Swing platform. How to change the length of a tab character in a JTextPane from 8 to 4 or 2.
1 answer
Google for "jtextpane tab width" offered me a lot of options. Here is one of them:
public class TestTextPane extends JFrame { private static final int TAB_SIZE = 4; public TestTextPane() { JPanel panel = new JPanel(); setContentPane(panel); JTextPane textPane = new JTextPane(); textPane.setFont(new Font("monospaced", Font.PLAIN, 12)); JScrollPane scrollPane = new JScrollPane(textPane); scrollPane.setPreferredSize(new Dimension(200, 200)); panel.add(scrollPane); setTabs(textPane, TAB_SIZE); } public void setTabs(JTextPane textPane, int charactersPerTab) { FontMetrics fm = textPane.getFontMetrics(textPane.getFont()); int charWidth = fm.charWidth('w'); int tabWidth = charWidth * charactersPerTab; TabStop[] tabs = new TabStop[10]; for (int j = 0; j < tabs.length; j++) { int tab = j + 1; tabs[j] = new TabStop(tab * tabWidth); } TabSet tabSet = new TabSet(tabs); SimpleAttributeSet attributes = new SimpleAttributeSet(); StyleConstants.setTabSet(attributes, tabSet); int length = textPane.getDocument().getLength(); textPane.getStyledDocument() .setParagraphAttributes(0, length, attributes, true); } public static void main(String[] args) { TestTextPane frame = new TestTextPane(); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } } |