Results 1 to 7 of 7
  1. #1
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default copying in flavors

    There are several issues here.
    But for the moment I am getting the text from the pane incorrectly (see line 94)?
    From line 90 you'll find the interesting noteworthy part.
    The text pane will be used to copy RTF from and to (and later images too!)
    The menu is there to make edit selections (do not know if things are implemented
    in a correct maner).
    The menu also shows some limited text style actions that produce RTF which I need
    to get on the clip board

    Java Code:
    import java.awt.datatransfer.*;
    import java.awt.event.*;
    import java.io.*;
    import java.io.IOException;
    import javax.swing.*;
    import javax.swing.text.*;
    
    /**
     * @author willem
     */
    public final class CopyPasteTest {
        private JTextPane textpane;
        private static final DataFlavor rtfFlavor = 
                                new DataFlavor("text/rtf", "Rich Formatted Text");
        private static final DataFlavor flavors[] =
                                              {DataFlavor.imageFlavor, rtfFlavor};
    
        private Image image;
        private Clipboard cb;
        private ActionListener editlistener;
        private ActionMap actionmap;
    
        public CopyPasteTest(JFrame frame) {
             //Create clip board object
            cb = Toolkit.getDefaultToolkit().getSystemClipboard();     
            editlistener  = new doCopyPasteListener();
            JMenuBar mb = new JMenuBar();
            frame.setJMenuBar(mb);
            mb.add(createEditMenu());
    
            Container contentPane = frame.getContentPane();
            contentPane.add(createTextPane(), BorderLayout.CENTER);
        }
    
        public static void main(String[] args){
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setTitle("Copytest");
            frame.setBounds(100, 30, 600, 400);
            CopyPasteTest copytest = new CopyPasteTest(frame);
            frame.setVisible(true);
        }
    
        public JScrollPane createTextPane() {
            textpane = new JTextPane();
            actionmap = textpane.getActionMap();
      
            JScrollPane spane = new JScrollPane(textpane);
            spane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
            spane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            spane.setPreferredSize(new Dimension(780, 830));
            return spane;
        }
    
        public JMenu createEditMenu() {
            JMenu editMenu = new JMenu("EDIT");
            JMenuItem menuItem = new JMenuItem(new DefaultEditorKit.CutAction());
            menuItem.setText("Cut");
            menuItem.setMnemonic(KeyEvent.VK_T);
            menuItem.addActionListener(editlistener);
            editMenu.add(menuItem);
    
            menuItem = new JMenuItem(new DefaultEditorKit.CopyAction());
            menuItem.setText("Copy");
            menuItem.setMnemonic(KeyEvent.VK_C);
            menuItem.addActionListener(editlistener);
            editMenu.add(menuItem);
    
            menuItem = new JMenuItem(new DefaultEditorKit.PasteAction());
            menuItem.setText("Paste");
            menuItem.setMnemonic(KeyEvent.VK_P);
            menuItem.addActionListener(editlistener);
            editMenu.add(menuItem);
            editMenu.addSeparator();
    
            menuItem = new JMenuItem(new doBoldAction());
            menuItem.setText("Bold");
            menuItem.setMnemonic(KeyEvent.VK_P);
            editMenu.add(menuItem);
    
            menuItem = new JMenuItem(new doSizeAction());
            menuItem.setText("size 24");
            menuItem.setMnemonic(KeyEvent.VK_P);
            editMenu.add(menuItem);
    
            return editMenu;
        }
    
        class doCopyPasteListener implements ActionListener{
            public void actionPerformed(ActionEvent evt) {
                String ac = evt.getActionCommand();
                Object sc = evt.getSource();
                if (ac.equals("Paste")) {
                    Object data[] = {new ByteArrayInputStream(textpane.getText().getBytes())};
                    Transferable p = new DataTransferClass(data,flavors);
                    cb.setContents(p, null);
                }
    
                if (ac.equals("Copy")) {
             
                }
            }
        }
    
        class doBoldAction extends TextAction {
            public doBoldAction() {super("BoldAction"); }
            public void actionPerformed(ActionEvent ae) {      
                Action boldaction = actionmap.get("font-bold");
                boldaction.actionPerformed( null );
            }
        }
    
        class doSizeAction extends TextAction {
            public doSizeAction() {super("SizeAction"); }
            public void actionPerformed(ActionEvent ae) {
                Action sizeaction = actionmap.get("font-size-24");
                sizeaction.actionPerformed( null );
            }
        }
    
        class DataTransferClass implements Transferable{      
            private Object datatrans[];
            private DataFlavor flavorstrans[];
    
            DataTransferClass(Object data[], DataFlavor flavors[]) {
                datatrans = data;
                flavorstrans = flavors;
            }
    
            // the Transferable interface methods:
            public DataFlavor[] getTransferDataFlavors() {
                return flavorstrans;
            }
    
            public boolean isDataFlavorSupported(DataFlavor flavor) {
                //   return flavors[0].equals(df);
                if (flavor.equals(flavorstrans[0]) ||
                                    (flavor.getMimeType().contains("text/rtf"))) {
                    return true;  
                } else return false;
            }
    
            public Object getTransferData(DataFlavor flavor)
                                throws UnsupportedFlavorException, IOException {
                    if ((flavor.getMimeType().contains("text/rtf"))) {
                        return datatrans[0];
                    } else return null;
            }
        }
    }
    Last edited by willemjav; 03-25-2014 at 10:44 PM.

  2. #2
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: copying in flavors

    Here is an important (advanced) thread to chew on:

    Cut, copy and Paste in JTextPane

    It got never responded!

  3. #3
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: copying in flavors

    Captain kirk to Enterprise: "we are reaching the final frontier of the Java-internal-text-Univers....."
    "Dr. Spock what is next?"

  4. #4
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,079
    Rep Power
    6

    Default Re: copying in flavors

    Are you having any kind of problem or not, I don't really understand what you're after here.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  5. #5
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: copying in flavors

    The point here is: how to copy text together with the text style (font-family, size, style and color)
    over the clipboard. That was also the question of the previous cited post of 5 years ago!
    The author of that post wrote a method that prepares an object, with text and text-style, to be
    pushed on the clipboard. The hearth of his (large) program is the method copyDocument which
    returns that object (a DefaultStyledDocument). I studied and remodeled that method and you'll
    find it at the bottom of this post!

    Now the question remains: his application does copy the text together with it's style onto a second,
    created, text component (using TransferHandler, Transferable, ClipboardOwner)! But when one
    goes outside the (Java) application only text is copied without the styles (rtf-format).

    Some remarks about the method:
    1) the text styles are internal saved into a tree;
    2) the tree's root is: rootElement = src.getDefaultRootElement(); where src is the StyledDocument;
    3) from the one root (here) one goes into the paragraph branches and at a JTextPane each
    line break (\n) is a new paragraph branch: paragraphElement = rootElement.getElement(index);
    (The index is each paragraph block);
    4) from each paragraph branch grows a styleElement branch which emerges when one creates a new
    style like font-family, size etc. See: styleElement = paragraphElement.getElement(lindex);

    Captain kirk to Mr Zulu: why are the coordinates not working when getting into a parallel universe outside Java!

    Java Code:
    public static DefaultStyledDocument copyDocument(StyledDocument src,
                                            int selectionStart, int selectionEnd) {
            System.out.println("copyDocument/ selection start: " + selectionStart
                    + " end: " + selectionEnd);
            Element rootElement, paragraphElement = null, styleElement;
            SimpleAttributeSet copyAttrs;
            int startOffset, endOffset;
            String copy_string;
    
            rootElement = src.getDefaultRootElement();
            DefaultStyledDocument copyDoc = new DefaultStyledDocument();
    
            System.out.println("Root Element Count is: " 
                            + rootElement.getElementCount()); System.out.println();
            for (int lpParagraph=0; lpParagraph<rootElement.getElementCount();
                                                                    lpParagraph++){
                paragraphElement = rootElement.getElement(lpParagraph);
                System.out.println("Paragraph no: " + lpParagraph);
                
                if(paragraphElement.getStartOffset() < selectionEnd &&
                       paragraphElement.getEndOffset() > selectionStart)  {
                    
                	for (int lpText=0; lpText<paragraphElement.getElementCount();
                                                                        lpText++) {
                        System.out.println("Text elements: " + lpParagraph + "/"
                                                                        + lpText);
                        //Insert a Element in the new Document
                        styleElement = paragraphElement.getElement(lpText);
                	    if(styleElement.getStartOffset() < selectionEnd &&
                       		styleElement.getEndOffset() > selectionStart){
                            copyAttrs = new 
                                   SimpleAttributeSet(styleElement.getAttributes());
                    	//Find the value of startOffset and endOffset
                    	if(styleElement.getStartOffset() < selectionStart){
                                startOffset = selectionStart;
                   	 	}else{
                                startOffset = styleElement.getStartOffset();
                    	}
                    	if(styleElement.getEndOffset() > selectionEnd){
                                endOffset = selectionEnd;
                    	}else{
                                endOffset = styleElement.getEndOffset();
                    			}
                    	try{
                                copy_string = src.getText(startOffset,
                                                            endOffset-startOffset);
                                System.out.println("<" + copy_string + ">");
                                copyDoc.insertString(copyDoc.getLength(),
                                                           copy_string, copyAttrs);
                    	}catch (BadLocationException e){
                                System.out.println("wont be called?");
                    	}
                        }
    		} // end of second textstyle loop
                }
            } // end of the first paragraph loop
            //Modify the Style of the paragraph
            copyAttrs = new SimpleAttributeSet(paragraphElement.getAttributes());
            startOffset = paragraphElement.getStartOffset();
            endOffset = paragraphElement.getEndOffset();
            copyDoc.setParagraphAttributes(startOffset, (endOffset-startOffset),
                                                                copyAttrs, true);
            System.out.println("the returned copy doc: " + copyDoc);
            System.out.println("end of copy"); System.out.println();
            System.out.println();
            return copyDoc;
        }
    Last edited by willemjav; 03-27-2014 at 07:21 PM.

  6. #6
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: copying in flavors

    It is really amazing that such basic thing like copying styled text among applications is such pain in the neck!
    At least the five year old post of Gudradain gives me some hope because he managed to use (if I get i right)
    the local clipboard (versus the system clipboard). I will keep searching because I really like to resolve this one:
    SO ANY HELP IS WELCOME!!!


    Next find a small sample of a image copy that WORKS:

    Java Code:
    import java.awt.BorderLayout;
    import java.awt.Image;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.io.IOException;
    
    import javax.swing.AbstractButton;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.TransferHandler;
    
    public class MainClass {
      public static void main(String args[]) {
        JFrame frame = new JFrame("Drag Image");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
        Icon icon = new ImageIcon("image.jpg");
        JLabel label = new JLabel(icon);
        label.setTransferHandler(new ImageSelection());
        MouseListener listener = new MouseAdapter() {
          public void mousePressed(MouseEvent me) {
            JComponent comp = (JComponent) me.getSource();
            TransferHandler handler = comp.getTransferHandler();
            handler.exportAsDrag(comp, me, TransferHandler.COPY);
          }
        };
        label.addMouseListener(listener);
        frame.add(new JScrollPane(label), BorderLayout.CENTER);
    
        frame.setSize(300, 150);
        frame.setVisible(true);
      }
    }
    
    class ImageSelection extends TransferHandler implements Transferable {
    
      private static final DataFlavor flavors[] = { DataFlavor.imageFlavor };
    
      private Image image;
    
    
      @Override
      public int getSourceActions(JComponent c) {
        return TransferHandler.COPY;
      }
    
      @Override
      public boolean canImport(JComponent comp, DataFlavor flavor[]) {
        if (!(comp instanceof JLabel) && !(comp instanceof AbstractButton)) {
          return false;
        }
        for (int i = 0, n = flavor.length; i < n; i++) {
          for (int j = 0, m = flavors.length; j < m; j++) {
            if (flavor[i].equals(flavors[j])) {
              return true;
            }
          }
        }
        return false;
      }
    
      @Override
      public Transferable createTransferable(JComponent comp) {
        image = null;
    
        if (comp instanceof JLabel) {
          JLabel label = (JLabel) comp;
          Icon icon = label.getIcon();
          if (icon instanceof ImageIcon) {
            image = ((ImageIcon) icon).getImage();
            return this;
          }
        } else if (comp instanceof AbstractButton) {
          AbstractButton button = (AbstractButton) comp;
          Icon icon = button.getIcon();
          if (icon instanceof ImageIcon) {
            image = ((ImageIcon) icon).getImage();
            return this;
          }
        }
        return null;
      }
    
      @Override
      public boolean importData(JComponent comp, Transferable t) {
        if (comp instanceof JLabel) {
          JLabel label = (JLabel) comp;
          if (t.isDataFlavorSupported(flavors[0])) {
            try {
              image = (Image) t.getTransferData(flavors[0]);
              ImageIcon icon = new ImageIcon(image);
              label.setIcon(icon);
              return true;
            } catch (UnsupportedFlavorException ignored) {
            } catch (IOException ignored) {
            }
          }
        } else if (comp instanceof AbstractButton) {
          AbstractButton button = (AbstractButton) comp;
          if (t.isDataFlavorSupported(flavors[0])) {
            try {
              image = (Image) t.getTransferData(flavors[0]);
              ImageIcon icon = new ImageIcon(image);
              button.setIcon(icon);
              return true;
            } catch (UnsupportedFlavorException ignored) {
            } catch (IOException ignored) {
            }
          }
        }
        return false;
      }
    
      public Object getTransferData(DataFlavor flavor) {
        if (isDataFlavorSupported(flavor)) {
          return image;
        }
        return null;
      }
    
      public DataFlavor[] getTransferDataFlavors() {
        return flavors;
      }
    
      public boolean isDataFlavorSupported(DataFlavor flavor) {
        return flavors[0].equals(flavor);
      }
    }

  7. #7
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: copying in flavors

    It is really a pity that Hardwired is not around anymore! What happened to him?

Similar Threads

  1. Batch copying
    By DELTA_ in forum New To Java
    Replies: 4
    Last Post: 12-21-2011, 08:53 PM
  2. Copying files
    By Scarlet Sphere in forum New To Java
    Replies: 13
    Last Post: 12-15-2011, 04:16 AM
  3. need help copying (what is in address bar)
    By 3ammary in forum New To Java
    Replies: 0
    Last Post: 01-08-2011, 02:42 PM
  4. add to a zip file without copying it.
    By yurabita in forum New To Java
    Replies: 5
    Last Post: 08-21-2010, 03:16 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •