JTextPane本身是不能完成这种工作的,它与javax.swing.text.StyledDocument接口的文档一起联合工作。所以只要从textPane中将StyledDocument类提取出来传递就可以了。
StyledEditorKit还可以提供辅助配置信息(具体参阅API Docs文档)。import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.*;
import java.io.*;public class Test {
  JFrame frame, frame2;
  JTextPane textPane,textPane2;
  File file;
  Icon image;  public Test(){
    frame = new JFrame("JTextPane");
    frame2 = new JFrame("提取的内容");
    textPane = new JTextPane();
    textPane2 = new JTextPane();
    file = new File("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);
      }});
    frame2.getContentPane().add(textPane2, BorderLayout.CENTER);
    frame.setSize(200,300);
    frame.setVisible(true);
    frame2.setLocation(200, 0);
    frame2.setSize(200,300);
    frame2.setVisible(true);
  }
  public static void main(String[] args) {
    Test test = new Test();
    test.gui();
    StyledDocument docs = test.textPane.getStyledDocument();//取得textPane中的StyledDocument类文档
    test.textPane2.setStyledDocument(docs);//将StyledDocument类文档传给textPane2
  }
}
<------ 树欲静而风不止 ------>

解决方案 »

  1.   

    我想做到可以追加,但现在这样做的问题是两个JTEXTPANE都同步了 请问可以解决吗
      

  2.   

    QQ的原理不是这样的,你发现QQ在文字设定的时候不能把一段话中的某个字改变字体、颜色、大小了吧,所发过去的只是一段样式统一的Document类文档,连图片都没有,Document类文档如何追加不用我说了吧?上面的例子中就有,第一行..;第二行..;第三行..就都是追加上去的,图片则是采用标记的方法来实现的,例如:"我们都有一个家,/:D名字叫中国。"这段文字的中间将出现一个大笑的图片,收到这段文字后只要查找出"/:D"所在的位置,然后单独插一个相应的图片进去就可以了。<------ 树欲静而风不止 ------>
      

  3.   

    小弟很菜,可以写个完全实现这样功能的代码比我吗?
    也可以发去我E-MAIL:[email protected]  收到立即给你分 好吗?
      

  4.   

    不好意思,我的工作也很忙,像这类问题只能给你把关键的地方点一下,主要还得你自己去摸索,否则那不就成为我的工作了吗。我喜欢分,但更喜欢钱,钱和分如果都需要用时间来换取,我选择后者。多看看帮助文档吧,你需要的全在里面。建议先找一些难度不太大的项目磨练一下,等有了好的Java思想再挑战自我。
    <------ 树欲静而风不止 ------>
      

  5.   

    其实第一次给你的例子中已经把该需要的方法全都包括了,加上第二次的思路,剩下就看你怎么样去组织、协调。
    <------ 树欲静而风不止 ------>
      

  6.   

    我觉得JAVA的桌面编程真是很一般,要做到跟QQ一样的效果真是好难