最近搞开发需要用JTextPane来做文件的复制粘贴,找了很多资料都没有提到图文混合的情况下如何来进行。于是上网查找了很多资料,找到的资料很少做的也都很肤浅。不能对word文档进行粘贴操作。没办法只有自己分析java代码了。费了很长时间终于实现了,下面是粘贴代码(这里需要指出的是我这里的JTextPane内容的格式是使用HTML来编码展现的):
//判断是否有选中的文字如果有则删除
if (editorPane.getSelectedText() != null) {
int start = editorPane.getSelectionStart();
int length = editorPane.getSelectedText().length();
try {
editorPane.getDocument().remove(start, length);
} catch (BadLocationException e) {
logger.error(e);
}
}
//获取系统粘贴缓存
Clipboard clb = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clb.getContents(null);
//取出所有内容
DataFlavor[] data=contents.getTransferDataFlavors();
下面是个循环再循环中判断哪些是需要的数据,例如word中复制的数据。这里使用到了Jsoup来解析,因为复制过来的word数据是HTML格式的。
for(int i=0;i<data.length;i++){
DataFlavor dataFlavor=data[i];
//取出数据的元信息判断有用的数据
if(dataFlavor.getHumanPresentableName().equals("text/html")&&dataFlavor.getRepresentationClass().getName().equals("java.lang.String")||dataFlavor.getHumanPresentableName().equals("Plain Text")&&dataFlavor.getRepresentationClass().getName().equals("java.io.InputStream")){
if(dataFlavor!=null){
try {
Object obj = null;
//从数据源信息中拿到word数据
try {
obj = dataFlavor.getReaderForText(contents);
} catch (Exception e1) {
logger.error(e1);
}
//判断数据类型是否对应
if(obj instanceof StringReader){
//强制转换后读取成字符串
StringReader reader=(StringReader) obj;
StringBuffer buffer=new StringBuffer();
int c;
while((c=reader.read())!=-1){
buffer.append((char)c);
}
//因为读取出来的数据是整片的html文档,我们只需要body中的数据。这里使用Jsoup来进行解析
org.jsoup.nodes.Document docx = Jsoup.parse(buffer.toString());
//获取body标签中的数据
org.jsoup.nodes.Element element = docx.body();
String str = "";
try {
org.jsoup.nodes.Element p;
// 判断body中是否存在<p>标签
if (element.child(0).tagName().equals("p")) {
p = element.child(0);// 如果存在则使用<p>标签内的内容
}else if(element.child(0).tagName().equals("div")){p = element.child(0);// 如果存在则使用<div>标签内的内容// 判断body中是否存在<div>标签
} else {p = element;// 如果不存在则使用<body>中的内容}str=p.html();} catch (Exception e) {str = "";continue;}//获取光标当前位置 int pos=editorPane.getCaretPosition();
//将内容插入到光标后 try { HTMLEditorKit kit = (HTMLEditorKit) editorPane.getEditorKit(); HTMLDocument doc = (HTMLDocument) editorPane.getDocument(); doc.insertBeforeStart(doc.getCharacterElement(pos), str); } catch (BadLocationException e) { logger.error(e); } } } }catch (IOException e) { logger.error(e); } } }else{ //这里用于处理非文字的对象 if (contents != null && contents.getTransferDataFlavors().length == 1) { // 判断是否是图片 if (contents.isDataFlavorSupported(DataFlavor.imageFlavor)) { // sendImage(Screenshot.getClipboard()); BufferedImage image = Screenshot.getClipboard(); WriteToImage(image); // 判断是否是文件 } else if (contents .isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { try { List files = (List) contents .getTransferData(DataFlavor.javaFileListFlavor); Iterator iterator = files.iterator(); while (iterator.hasNext()) { File file = (File) iterator.next(); String path = file.getAbsolutePath().toUpperCase(); // 判断文件是否是图片 if (path.endsWith(".GIF") || path.endsWith(".JPG") || path.endsWith(".PNG")) { HTMLEditorKit kit = (HTMLEditorKit) editorPane .getEditorKit(); HTMLDocument doc = (HTMLDocument) editorPane .getDocument(); // 粘贴图片的位置 // imageMap.put(editorPane.getCaretPosition(), // file.getAbsolutePath()); kit.insertHTML(doc, editorPane.getCaretPosition(), "<img id='" + file.hashCode() + "' src='file:///" + file.getAbsolutePath() + "' />", 0, 0, HTML.Tag.IMG); /*StringReader in=new StringReader("<img id='" + file.hashCode() + "' src='file:///" + file.getAbsolutePath() + "' />"); kit.read(in, doc, editorPane.getCaretPosition());*/ } } } catch (UnsupportedFlavorException e) { logger.error(e); } catch (IOException e) { logger.error(e); } catch (BadLocationException e) { logger.error(e); } } } }
复制操作的代码比较简单这里就不多说了,直接代码:
//判断是否有选取的复制内容
if(editorPane.getSelectedText()!=null){ HTMLEditorKit kit = (HTMLEditorKit) editorPane.getEditorKit(); HTMLDocument doc = (HTMLDocument) editorPane.getDocument();
//获取开始坐标 int start = editorPane.getSelectionStart();
//获取长度 int length = editorPane.getSelectedText().length();
//获取序列化的HTML内容 StringWriter buf = new StringWriter(); try { kit.write(buf, doc, start, length); } catch (IOException e) { logger.error(e); } catch (BadLocationException e) { logger.error(e); } if(buf!=null){ str=buf.toString(); }
//将内容放到系统剪切板 Clipboard clipboard = editorPane.getToolkit().getSystemClipboard(); Transferable tText = new StringSelection(str); clipboard.setContents(tText, null); }
如果对java界面方面有兴趣的朋友欢迎加入4601398QQ群。