[英]copy jTextPane text to clipboard
I have a form which contains a jTextPane
and a jButton
, I've set the jTextPane
Accessible Description
to text/html
, now I want when I click on the jButton
to copy the content of the jTextPane
to my clipboard, I tried this code :我有一个包含
jTextPane
和 jButton 的jButton
,我已将jTextPane
Accessible Description
设置为text/html
,现在我想当我单击 jButton 将jButton
的内容jTextPane
到我的剪贴板时,我尝试了以下代码:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
StringSelection stringSelection = new StringSelection (jTextPane1.getText());
Clipboard clpbrd = Toolkit.getDefaultToolkit ().getSystemClipboard ();
clpbrd.setContents (stringSelection, null);
}
but when I past, it past the text as an HTML format.但是当我过去时,它以 HTML 格式过去的文本。
How can I solve this probelm ?我该如何解决这个问题?
First of all, there are 2 clipboards in Java (a local one and a system one, which you are using).首先,Java 中有 2 个剪贴板(您正在使用的一个本地剪贴板和一个系统剪贴板)。 Here 's an example that uses the system clipboard.
这是一个使用系统剪贴板的示例。 Take a look and try this getClipboardContents method:
看看并尝试这个 getClipboardContents 方法:
public String getClipboardContents(Clipboard clipboard) {
String result = "";
if (clipbloard != null){
//odd: the Object param of getContents is not currently used
Transferable contents = clipboard.getContents(null);
boolean hasTransferableText =
(contents != null) &&
contents.isDataFlavorSupported(DataFlavor.stringFlavor);
if ( hasTransferableText ) {
try {
result = (String)contents.getTransferData(DataFlavor.stringFlavor);
}
catch (UnsupportedFlavorException ex){
//highly unlikely since we are using a standard DataFlavor
System.out.println(ex);
ex.printStackTrace();
}
catch (IOException ex) {
System.out.println(ex);
ex.printStackTrace();
}
}
}
return result;
}
When I use Ctrl+CI get text copied to the clipboard without HTML.当我使用 Ctrl+CI 时,将文本复制到没有 HTML 的剪贴板。 You can use the default Action with the following code:
您可以将默认操作与以下代码一起使用:
Action copy = new ActionMapAction("Copy", textPane, "copy-to-clipboard");
JButton copyButton = new JButton(copy);
See Action Map Action for more information on how this works.有关其工作原理的更多信息,请参阅操作映射操作。
first you need to select all the text in the textpane and then copy.首先,您需要选择文本窗格中的所有文本,然后复制。
private void btnCopyActionPerformed(java.awt.event.ActionEvent evt) {
textPaneLogs.selectAll();
textPaneLogs.setFocusable(true);
textPaneLogs.copy();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.