如果您不想使用 DefaultEditorKit,而只想将文本复制粘贴到 HtmlEditorKit,您可以尝试编写自己的粘贴代码,
textPane.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), "paste");
textPane.getActionMap().put("paste", pasteAction);
class PasteAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
try {
int offset = textPane.getSelectionStart();
Document sd=textPane.getDocument();
String value = getClipboard();
sd.remove(textPane.getSelectionStart(), textPane.getSelectionEnd()-textPane.getSelectionStart());
textPane.getDocument().insertString(offset, value , null);
if (value != null) {
textPane.setCaretPosition(offset + value.length());
}
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
并使用此代码从剪贴板中获取纯文本,
public String getClipboard() throws ClassNotFoundException, UnsupportedFlavorException {
Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
DataFlavor htmlStringFlavor = new DataFlavor("text/plain; class=java.lang.String");
try {
if (t != null && t.isDataFlavorSupported(htmlStringFlavor)) {
String text = (String) t.getTransferData(htmlStringFlavor);
return text;
}
} catch (UnsupportedFlavorException e) {
} catch (IOException e) {
}
return null;
}
如果您有菜单项、工具栏或其他触发器,请不要忘记将“粘贴”操作绑定到它们。