View Single Post
  #2 (permalink)  
Old 09-22-2007, 06:25 AM
hardwired hardwired is offline
Senior Member
 
Join Date: Jul 2007
Posts: 1,222
hardwired is on a distinguished road
DocumentFilter
With a continuously–running loop that is busy styling all of the text in the textPane, called by a DocumentListener, I would say that your app could run very slow.
A lighter–weight way to do this is with a simple DocumentFilter. Here's one way you could put it together:
Code:
// <applet code="TEV3Rx" width="400" height="400"></applet> import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.text.*; public class TEV3Rx extends JApplet { public void init() { JTextPane textPane = new JTextPane(); Style style = textPane.addStyle("basic", null); StyleConstants.setFontSize(style, 18); StyleConstants.setForeground(style, Color.green.darker()); StyleConstants.setFontFamily(style, "Lucida Sans Unicode"); textPane.setLogicalStyle(style); style = textPane.addStyle("redDigits", null); StyleConstants.setForeground(style, Color.red); AbstractDocument doc = (AbstractDocument)textPane.getDocument(); doc.setDocumentFilter(new DigitFilter(style)); getContentPane().add(textPane); } public static void main(String[] args) { JApplet applet = new TEV3Rx(); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setContentPane(applet); f.setSize(400,400); f.setLocation(200,200); applet.init(); f.setVisible(true); } } class DigitFilter extends DocumentFilter { String domain = "0123456789"; Style digitStyle; public DigitFilter(Style style) { digitStyle = style; } public void insertString(DocumentFilter.FilterBypass fb, int offset, String str, AttributeSet attrs) throws BadLocationException { replace(fb, offset, 0, str, attrs); } public void replace(DocumentFilter.FilterBypass fb, int offset, int length, // selected text String str, // incoming string AttributeSet attrs) throws BadLocationException { char[] source = str.toCharArray(); char[] result = new char[source.length + 2]; int k = 0; for(int j = 0; j < source.length; j++) { result[k++] = source[j]; fb.replace(offset, length, new String(result, 0, k), attrs); if(domain.indexOf(source[j]) != -1) { StyledDocument doc = (StyledDocument)fb.getDocument(); doc.setCharacterAttributes(offset, 1, digitStyle, false); } } } }
Reply With Quote