问题
I'm having trouble copying HTML from JEditorPane to system clipboard and then pasting into other applications:
- OpenOffice 3.2 - Says "Requested clipboard format isn't available"
- Thunderbird 3.13 - Does nothing on paste
- Firefox 3.6.9 - Accepts plain text but for example in GMail "Compose mail" does nothing on paste
I'm running WinXP by the way. In other applications like text-editors, MS Outlook, MS Word etc. it works as expected, ie I get plain text with HTML tags stripped or formatted text according to which mimetype the application wants.
Anyone has an idea what's wrong? Is it a problem in Swing or in OpenOffice/Mozilla?
See test application below and try out. I've also tried with a custom Transferable but as soon as I provide a DataFlavor with mimetype="text/html" it stops to work in applications mentioned above.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/**
* Demonstrates problem with copy/paste between JEditorPane and OpenOffice/Thunderbird/Firefox.
*
* @author martin
*/
public class HtmlCopyDemo extends JFrame
{
public HtmlCopyDemo()
{
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
setSize(400, 400);
final JEditorPane editor = new JEditorPane();
editor.setContentType("text/html");
editor.setText("<html><head></head><body>Here's some <b>formatted</b> <i>text</i></body></html>");
add(editor, BorderLayout.CENTER);
JPanel panel = new JPanel(new FlowLayout());
add(panel, BorderLayout.NORTH);
JButton button = new JButton("Copy");
panel.add(button);
button.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
editor.selectAll();
editor.copy();
}
});
final JComboBox combo = new JComboBox(new Object[]{"text/html", "text/plain"});
panel.add(combo);
combo.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String text = editor.getText();
editor.setContentType((String) combo.getSelectedItem());
editor.setText(text);
}
});
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
new HtmlCopyDemo().setVisible(true);
}
});
}
}
回答1:
It's most likely a problem on the receiver end. (I can't be 100% sure since I don't have your environment.)
Add Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
to your button's actionPerformed
and I can see the clipboard has the right stuff with full html:
<html>
<head>
</head>
<body>
Here's some <b>formatted</b> <i>text</i>
</body>
</html>
Pasting into Word 2007 works correctly.
来源:https://stackoverflow.com/questions/3727271/problem-copying-html-from-jeditorpane-to-external-applications