最近搞開發需要用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>標籤內的內容
// 判斷body中是否存在<div>標籤
}else if(element.child(0).tagName().equals("div")){p = element.child(0);// 如果存在則使用<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羣。