JTextPane和JEditorPane都可以实现。因为它们都是以RTF形式来处理文档的。不过由于在同一文档内部,字体大小可以不同,字体也可以不同,所以无法计算显示空间大小。从而必须自己控制组件大小和宽度。下面是一个交替以红、蓝色显示数字框的例子。
输入的所有字符自动有颜色。 DefaultStyledDocument doc=new DefaultStyledDocument(); doc。setDocumentFilter(new DocumentFilter(){ public void remove(DocumentFilter。
FilterBypass fb,int offset,int len){ try{ super。remove(fb,offset,len); } catch(BadLocationException ex){} setAttribute(fb,offset); } public void replace(DocumentFilter。
FilterBypass fb,int offset,int len,String text,AttributeSet attr){ try{ super。replace(fb,offset,len,text,attr); } catch(BadLocationException ex){} setAttribute(fb,offset); } private void setAttribute(DocumentFilter。
FilterBypass fb,int offset){ StyledDocument doc=(StyledDocument)(fb。getDocument()); MutableAttributeSet redText=new SimpleAttributeSet(),blueText=new SimpleAttributeSet(); StyleConstants。
setForeground(redText,Color。RED); StyleConstants。setForeground(blueText,Color。BLUE); for(int i=doc。
getLength()-1;i>=offset;i--){ doc。setCharacterAttributes(i,1,i%2==0?redText:blueText,false); } } }); txtInput=new JTextPane(); Insets insets=txtInput。
getInsets(); Insets margin=txtInput。getMargin(); FontMetrics metrics=txtInput。getFontMetrics(txtInput。getFont()); txtInput。
setPreferredSize(new Dimension(metrics。charWidth('X')*20+insets。left+insets。right+margin。left+margin。right,metrics。
getHeight()+insets。top+insets。bottom+margin。top+margin。bottom)); txtInput。setDocument(doc); add(txtInput);这个txtInput框的宽度为输入20个字符‘X’的宽度。
有关的类分别在javax。swing、javax。swing。text、java。awt中
追问
你能按照我的程序,帮忙把这个插到我原来的程序么,我看不懂你编得哎。。。
本回答由网友推荐。
全部