JTextPane怎么不能自动换行?
我在做一个聊天室的程序,为了显示不同的颜色,我把JTextPane的文本设成text/html格式,结果发现不能自动换行了,文本过长后就会出现一个水平滚动条,我不想要这种效果,只想让他自动换行,应该怎么做? 问题点数:30、回复次数:3Top
1 楼sunjie1981()回复于 2005-05-18 20:11:49 得分 5
setLineWrap(boolean t);看看有没有这个方法可以调用,如果有,设置真就可以实现自动换行Top
2 楼mq612(五斗米)回复于 2005-05-18 21:39:48 得分 20
JTextPane没有setLineWrap(boolean t);方法,StyledDocument控制着JTextPane中的显示,自动换行,当你把JTextPane设置成text/html格式,html语法将控制它的显示,这时换行将通过<br>来实现,想要自动换行就需要用到表格,一个设置好宽度的表格可以使其中的文字自动折行,这完全和网页上的做法相同。
如果确定采用text/html格式,你可以使用JTextPane的父类JEditorPane,建议服务器端采取推技术。
用JTextPane显示不同色彩的文字,又想自动折行,请参照下面的代码:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.*;
import java.io.*;
public class Test {
JFrame frame;
JTextPane textPane;
//File file;
//Icon image;
public Test(){
frame = new JFrame("JTextPane");
textPane = new JTextPane();
//file = new File("./classes/test/icon.gif");
//image = new ImageIcon(file.getAbsoluteFile().toString());
}
public void insert(String str, AttributeSet attrSet) {
Document doc = textPane.getDocument();
str ="\n" + str ;
try {
doc.insertString(doc.getLength(), str, attrSet);
}
catch (BadLocationException e) {
System.out.println("BadLocationException: " + e);
}
}
public void setDocs(String str,Color col,boolean bold,int fontSize) {
SimpleAttributeSet attrSet = new SimpleAttributeSet();
StyleConstants.setForeground(attrSet, col);
//颜色
if(bold==true){
StyleConstants.setBold(attrSet, true);
}//字体类型
StyleConstants.setFontSize(attrSet, fontSize);
//字体大小
insert(str, attrSet);
}
public void gui() {
//textPane.insertIcon(image); //插入图片
setDocs("第一行的文字文字文字文字文字文字文字文字文字文字",Color.red,false,20); //折行测试
setDocs("第二行的文字",Color.BLACK,true,25);
setDocs("第三行的文字",Color.BLUE,false,20);
frame.getContentPane().add(textPane, BorderLayout.CENTER);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}});
frame.setSize(200,300);
frame.setVisible(true);
}
public static void main(String[] args) {
Test test = new Test();
test.gui();
}
}Top
3 楼viewtifuljoe(小白)回复于 2005-05-18 22:49:50 得分 5
正好学习,留个名Top




