I have a JTextArea
and I am using a Highlighter
to apply some syntax highlighting to some of my text as per my SSCCE below:
import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.text.*;public class SSCCE extends JFrame { public SSCCE() { final JTextArea aMain = new JTextArea(); aMain.setFont(new Font("Consolas", Font.PLAIN, 11)); aMain.setMargin(new Insets(5, 5, 5, 5)); aMain.setEditable(false); add(aMain); aMain.setText("The quick brown fox jumped over the lazy dog."); Highlighter h = aMain.getHighlighter(); try { h.addHighlight(10, 15, new DefaultHighlighter.DefaultHighlightPainter(new Color(0xFFC800))); } catch (BadLocationException e) { e.printStackTrace(); } aMain.getActionMap().put("Copy", new AbstractAction() { public void actionPerformed(ActionEvent e) { aMain.copy(); } }); aMain.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), "Copy"); setTitle("SSCCE"); setSize(350, 150); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { new SSCCE(); } }); }}
When the user selects a portion of text and presses CTRL+C then I am calling the copy()
method of the JTextArea
class. This copies the text onto the system clipboard as Plain Text and I lose any highlighting I have applied to my text. I am looking for the ability to copy the style information which includes the highlights as either "text/html" or "text/rtf". I believe I need to use the Transferable
and DataFlavor
classes, but I am struggling putting something together - I don't know how to get the data from the JTextArea
in the correct format to place onto the clipboard.
I am basically trying to copy the highlighting and then paste it into Microsoft Word or similar application with the highlighting intact. Is the style data available in the correct format or do I manually have to construct a HTML markup by enumerating all the highlights?