У меня есть JEditorPane с текстом/html, и я хочу, чтобы опция вставляла (через CTRL + V) текст как обычный текст ИЛИ как форматированный текст. Пока что вставка по умолчанию работает с форматированным текстом. Теперь я создал класс, в который могу вставить текст как обычный текст. Он сопоставлен с CTRL+V.
Моя идея состоит в том, чтобы сопоставить форматированную (стандартную) вставку с CTRL+SHIFT+V, чтобы у меня была возможность выбирать между двумя методами
Мой класс по вставке обычного текста
class PasteAction extends AbstractAction {
/**
*
*/
private static final long serialVersionUID = 1L;
private final JEditorPane textPane;
public PasteAction(JEditorPane textPane) {
this.textPane = textPane;
}
@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 | IOException e) {
e.printStackTrace();
}
return null;
}
}
Сопоставление
JEditorPane textareaLogText = new JEditorPane ();
PasteAction pasteAction = new PasteAction(textareaLogText); // to allow only plaintext to be added
textareaLogText.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), "paste"); // to allow only plaintext to be added
textareaLogText.getActionMap().put("paste", pasteAction); // to allow only plaintext to be added
textareaLogText.setContentType("text/html");
Есть идеи?
РЕДАКТИРОВАТЬ: Иногда это проще простого, и полезно прочитать документацию по JEditorPane.
Простой editorpane.paste(); делает свое дело.
Ниже вы можете найти решение для поиска функция.
JEditorPane textareaLogText = new JEditorPane ();
// to allow only plaintext to be added
PasteAction pasteAction = new PasteAction(textareaLogText);
InputMap inputMap = textareaLogText.getInputMap(JComponent.WHEN_FOCUSED);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK), "pasteUnFormatted");
textareaLogText.getActionMap().put("pasteUnFormatted", pasteAction);
// to allow formatted text
PasteFormattedAction pasteFormattedAction = new PasteFormattedAction(textareaLogText);
InputMap inputMap2 = textareaLogText.getInputMap(JComponent.WHEN_FOCUSED);
inputMap2.put(KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK | ActionEvent.SHIFT_MASK), "pasteFormatted");
textareaLogText.getActionMap().put("pasteFormatted", pasteFormattedAction);
class PasteFormattedAction extends AbstractAction {
/**
*
*/
private static final long serialVersionUID = 1L;
private JTextComponent textComponent;
public PasteFormattedAction(JTextComponent textComponent) {
this.textComponent = textComponent;
}
@Override
public void actionPerformed(ActionEvent e) {
textComponent.paste();
}
}
class PasteAction extends AbstractAction {
/**
*
*/
private static final long serialVersionUID = 1L;
private final JEditorPane textPane;
public PasteAction(JEditorPane textPane) {
this.textPane = textPane;
}
@Override
public void actionPerformed(ActionEvent e) {
try {
System.out.println("PasteAction actionPerformed");
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 | IOException e) {
e.printStackTrace();
}
return null;
}
}
Подробнее здесь: https://stackoverflow.com/questions/783 ... -actionmap