Results 1 to 4 of 4
  1. #1
    willemjav is online now Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,066
    Rep Power
    8

    Default ones again RTF and Java

    I am still struggling with RTF stuff and Java and won't let it go that easy!
    Down you'll find two formats of styled text.
    1) is the RTF-format and
    2) is the Java internal styled attribute format.
    When importing or exporting styled text from and to a Java application one needs to go from 1) to 2) and visa versa…..
    How could that be done without using the buggy rtfEditorKit of Java?

    (I know how to get 1) from the clipboard and I know how to get 2) on the clipboard)


    1) {\rtf1\ansi\ansicpg1252\cocoartf1038\co etc.



    2) The getStyledText method************************
    source: class javax.swing.text.DefaultStyledDocumenttext/ selection start: 0 /end: 59
    Paragraph Count is: 3

    Paragraph no: 0
    0/0 Text string out: <This line is black,
    >
    Number of Attributes: 4
    Name: family=Courier New
    Name: name=base
    Name: size=24
    Name: LeftIndent=10.0

    Paragraph no: 1
    1/0 Text string out: <this line is red and>
    Number of Attributes: 5
    Name: foreground=java.awt.Color[r=255,g=0,b=0]
    Name: family=Courier New
    Name: name=base
    Name: size=24
    Name: LeftIndent=10.0

    etc.

  2. #2
    willemjav is online now Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,066
    Rep Power
    8

    Default Re: ones again RTF and Java

    what about this IT'S easy - Downloads

  3. #3
    willemjav is online now Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,066
    Rep Power
    8

  4. #4
    willemjav is online now Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,066
    Rep Power
    8

    Default Re: ones again RTF and Java

    I have solved most of the problem of getting styled text from and to the clipboard,
    by using the "popular" RTF format! Mann I really worked hard on this, see for yourself
    and run the small test application!

    The problems that remain are:
    1) how to insert text when copying FROM the clipboard!
    2) how to select (a partial selection) text to be copied to
    the clipboard! pls swing experts give me some feedback!

    I am using the buggy RTFEditorKit but only for the copying!
    I do not install the kit at the JTextPane!


    Java Code:
    import java.awt.*;
    import java.awt.datatransfer.*;
    import java.awt.event.*;
    import java.io.*;
    import java.io.IOException;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.rtf.RTFEditorKit;
    
    /**
     * @author willem
     */
    public final class CopyPasteTest {
        private JTextPane textpane;
        private static final DataFlavor rtfFlavor = 
                new DataFlavor("text/rtf", "Rich Text Format");
        private static final DataFlavor flavors[] = {rtfFlavor};
        private static final String text = "Some text lines in order to tryout\n"
                + "copying styled text from and to the clipboard.\n"
                + "I am using the buggy RTFEditorKit but only for the copying! \n"
                + "I do not install the kit at the JTextPane!";
        private static final String rtfString = "";
    
        private  Clipboard cb;
        private StyledEditorKit rtfEditor;
        private StyledDocument doc;
        private ActionMap actionmap;
    
    
        public CopyPasteTest(JFrame frame) {
            //create the textpane
            textpane = new JTextPane();
            doc = textpane.getStyledDocument();    
            rtfEditor = new RTFEditorKit();
            actionmap = textpane.getActionMap();
            actionmap.put("font-color-Red",
               new StyledEditorKit.ForegroundAction("font-color-Red", Color.RED));
            actionmap.put("font-color-Blue",
               new StyledEditorKit.ForegroundAction("font-color-Blue", Color.BLUE));
            Style baseStyle = doc.addStyle("base", null);
            StyleConstants.setFontFamily(baseStyle, "Courier New");
            StyleConstants.setFontSize(baseStyle, 24);
            StyleConstants.setLeftIndent(baseStyle, 10f);
            try {
                doc.insertString(0, text, doc.getStyle("base"));
            } catch(BadLocationException e) {
                System.err.printf("bad location error: %s%n", e.getMessage());
            }
            doc.setCharacterAttributes(0, doc.getLength(), baseStyle, false);
    
            //Create clip board object
            cb = Toolkit.getDefaultToolkit().getSystemClipboard();
    
            JPanel ButtonPanel = new JPanel();
            JButton button = new JButton("RED TEXT");
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e){
                    emptyClipboard();
                    Action reddaction = actionmap.get("font-color-Red");
                    reddaction.actionPerformed( null );
                }
            });
            ButtonPanel.add(button);
    
            button = new JButton("BLUE TEXT");
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e){
                    Action reddaction = actionmap.get("font-color-Blue");
                    reddaction.actionPerformed( null );
                }
            });
            ButtonPanel.add(button);
    
            button = new JButton("COPY TO CLIPBOARD");
            button.addActionListener(new ActionListener() {
                
                public void actionPerformed(ActionEvent e){
                    emptyClipboard();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    try {
                        rtfEditor.write(baos, doc, 0, doc.getLength());
                    } catch (IOException ex) {
                        System.err.println("io exception: " + ex);
                    } catch (BadLocationException ex) {
                        System.err.println("BadLocationException: " + ex);
                    }
                    String s = baos.toString();
                    Object[] data = {new ByteArrayInputStream(s.getBytes())};
                    cb.setContents(new DataTransferClass(data, flavors), null);
                    System.out.println("\n<" + s + ">");
                }
            });
            ButtonPanel.add(button);
    
            button = new JButton("GET FROM CLIPBOARD"); // OK
            button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e){   
                    InputStream data = null;
                    try {
                        if (cb.isDataFlavorAvailable(rtfFlavor)) {
                            data = (InputStream) cb.getData(rtfFlavor);
                            StyledDocument doctemp = new DefaultStyledDocument();
                            rtfEditor.read(data, doc, 0);
                        }
                    } catch (IOException ex) {
                        System.err.println("io exception: " + ex);
                    } catch (BadLocationException ex) {
                        System.err.println("BadLocationException: " + ex);
                    }
                      catch (UnsupportedFlavorException ex) {
                        System.err.println("UnsupportedFlavor exception: " + ex);
                    }
                }
            });
            ButtonPanel.add(button);
    
            Container contentPane = frame.getContentPane();
            contentPane.add(textpane, BorderLayout.CENTER);
            contentPane.add(ButtonPanel, BorderLayout.SOUTH);
        }
    
        public static void main(String[] args){
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setTitle("Copytest");
            frame.setBounds(100, 30, 700, 400);
            new CopyPasteTest(frame);
            frame.setVisible(true);
        }
    
        //======================================================
        static 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() {
                System.out.println("getTransferDataFlavors() " + flavorstrans);
                return flavorstrans;
            }
    
            public boolean isDataFlavorSupported (DataFlavor df){
                System.out.println("isDataFlavorSupported");
                if(df.getMimeType().contains("text/rtf") ||
                                        df.getMimeType().contains("text/plain")){
                    System.out.println("isDataFlavorSupported is true!");
                    return true;
                }
                else{
                    return false;
                }
            }
    
            public Object getTransferData(DataFlavor flavor)
                                throws UnsupportedFlavorException, IOException {
                System.out.println("getTransferData " + flavor);
                    if ((flavor.getMimeType().contains("text/rtf"))) {
                        System.out.println("getTransferData data out: "
                                + datatrans[0]);
                        return datatrans[0];
                    } else return null;
            }
        }
    
        public void emptyClipboard() {
            cb.setContents(new Transferable() {
                public DataFlavor[] getTransferDataFlavors() {
                    return new DataFlavor[0];
                }
                public boolean isDataFlavorSupported(DataFlavor flavor) {
                    return false;
                }
                public Object getTransferData(DataFlavor flavor)
                                                throws UnsupportedFlavorException {
                      //  throw new UnsupportedFlavorException(flavor);
                      return null;
                }
            }, null);
        }
    }
    Last edited by willemjav; 04-06-2014 at 06:16 PM.

Posting Permissions

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