2

我无法将 HTML 从 JEditorPane 复制到系统剪贴板,然后粘贴到其他应用程序中:

  • OpenOffice 3.2 - 说“请求的剪贴板格式不可用”
  • Thunderbird 3.13 - 粘贴时什么都不做
  • Firefox 3.6.9 - 接受纯文本,但例如在 GMail 中“撰写邮件”在粘贴时不执行任何操作

顺便说一句,我正在运行 WinXP。在文本编辑器、MS Outlook、MS Word 等其他应用程序中,它按预期工作,即我得到带有 HTML 标记的纯文本,或者根据应用程序想要的 mimetype 格式化文本。

有人知道出了什么问题吗?这是 Swing 还是 OpenOffice/Mozilla 的问题?

请参阅下面的测试应用程序并尝试。我也尝试过使用自定义Transferable,但是一旦我提供了具有 mimetype="text/html" 的DataFlavor,它就停止在上述应用程序中工作。

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);
            }
        });
    }
}
4

1 回答 1

0

这很可能是接收端的问题。(我不能 100% 确定,因为我没有你的环境。)

添加Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();到您的按钮actionPerformed,我可以看到剪贴板具有完整的 html 的正确内容:

<html>
  <head>

  </head>
  <body>
    Here's some <b>formatted</b> <i>text</i>
  </body>
</html>

粘贴到 Word 2007 可以正常工作。

于 2010-09-16T14:27:08.287 回答