IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

AWT/Swing Java Discussion :

copy/paste dans un composant text avec html


Sujet :

AWT/Swing Java

  1. #1
    Membre averti Avatar de xixi31
    Inscrit en
    Juin 2005
    Messages
    423
    Détails du profil
    Informations personnelles :
    Âge : 43

    Informations forums :
    Inscription : Juin 2005
    Messages : 423
    Points : 414
    Points
    414
    Par défaut copy/paste dans un composant text avec html
    Bonjour à tous,

    Je rencontre quelques problèmes sur l'utilisation d'un bloc de texte avec un document de type HTMLDocument :

    Mon code est le suivant :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
     
     
        public static void main(String[] args)
        {
            javax.swing.JFrame frame = new javax.swing.JFrame();
            frame.setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE);
     
            JTextPane pane = new JTextPane();
            pane.setContentType("text/html");
     
            System.out.println("editor kit : " + pane.getEditorKit());
            System.out.println("document : " + pane.getDocument());
     
            frame.getContentPane().add(new javax.swing.JScrollPane(pane));
     
     
            frame.setSize(200, 200);
            frame.setVisible(true);
        }
    si je tape : "abcdefghijklmnop", je copie "ghijklm" et si je veux coller entre le o et le p, j'obtiens le résultat suivant :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    abcdefghijklmno
    ghijklm
    p
    ???

    En gros, il semble que le mécanisme standard insert la portion de code collé dans un nouveau paragraphe.

    Avez-vous déjà traité le copier/coller pour les documents html?
    auteur de Awl (http://awl-wizard.sourceforge.net), librairie de développement d'assistant en Java.
    auteur de Blackdog (http://www.blackdog-project.org), lecteur/gestionnaire audio en Java.

  2. #2
    Rédacteur/Modérateur

    Avatar de bouye
    Homme Profil pro
    Information Technologies Specialist (Scientific Computing)
    Inscrit en
    Août 2005
    Messages
    6 840
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 47
    Localisation : Nouvelle-Calédonie

    Informations professionnelles :
    Activité : Information Technologies Specialist (Scientific Computing)
    Secteur : Agroalimentaire - Agriculture

    Informations forums :
    Inscription : Août 2005
    Messages : 6 840
    Points : 22 854
    Points
    22 854
    Billets dans le blog
    51
    Par défaut
    Ne perds pas espoir si vite et continue tes recherches. S'il n'y a pas de reponse, cela peut tout simplement venir du fait que personne ne s'est penche sur ce genre de probleme (+ le fait que vos grandes vacances ont commencees).
    Merci de penser au tag quand une réponse a été apportée à votre question. Aucune réponse ne sera donnée à des messages privés portant sur des questions d'ordre technique. Les forums sont là pour que vous y postiez publiquement vos problèmes.

    suivez mon blog sur Développez.

    Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the universe is winning. ~ Rich Cook

  3. #3
    Expert éminent sénior
    Avatar de SheikYerbouti
    Profil pro
    Inscrit en
    Mai 2003
    Messages
    6 760
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2003
    Messages : 6 760
    Points : 11 862
    Points
    11 862
    Par défaut
    ... et également sur le fait que l'utilisation du HTMLEditorKit n'interresse pratiquement personne. Nombre de mes questions sur ce sujet sont restées sans réponse, et la doc est aussi minimaliste sur le point...
    Rédacteur Oracle (Oracle ACE)
    Guide Oracle ,Guide PL/SQL, Guide Forms 9i/10g, Index de recherche
    Je ne réponds pas aux questions techniques par MP
    Blogs: Forms-PL/SQL-J2EE - Forms Java Beans

  4. #4
    Membre averti Avatar de xixi31
    Inscrit en
    Juin 2005
    Messages
    423
    Détails du profil
    Informations personnelles :
    Âge : 43

    Informations forums :
    Inscription : Juin 2005
    Messages : 423
    Points : 414
    Points
    414
    Par défaut
    merci pour votre soutien .

    Après diverses recherches, il semble que ce soit du à la classe HTMLWriter qui est appelé par la méthode write de l'EditorKit.
    Cette class, HTMLWriter, doit insérer dans un Writer une portion du document Html et c'est elle qui provoque la création d'un document html partiel du type :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
     
            <html>
                <body>
                    <p>
                        cd
                    </p>
                </body>
            </html>
    lorsque l'on tente de copier une chaine 'cd' dans un document de type HtmlDocument...
    bon, si la solution, c'est de surcharger TransferHandler, EditorKit et créer son propre HTMLWriter.....

    Quoi qu'il en soit, c'est vrai que les composants text avec du contenu html , ca ne déchaine pas les foules
    auteur de Awl (http://awl-wizard.sourceforge.net), librairie de développement d'assistant en Java.
    auteur de Blackdog (http://www.blackdog-project.org), lecteur/gestionnaire audio en Java.

  5. #5
    Futur Membre du Club
    Profil pro
    Inscrit en
    Avril 2007
    Messages
    6
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Avril 2007
    Messages : 6
    Points : 6
    Points
    6
    Par défaut copier/coller JTextPane
    Je suis également a la recherche d'une solution pouvant répondre à ce probleme. Dans le cas ou le style du texte copié ne t'interesse pas, la méthode insertString répond aisément au probleme. Dans le cas contraire, ... si qqun a une solution efficace, je suis preneur.

  6. #6
    Membre à l'essai
    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    19
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 19
    Points : 18
    Points
    18
    Par défaut
    Bon voici la solution a ce petit problème.

    L'important c'est de surcharger TransferHandler. Pour ce faire, on doit aller jouer profondément dans la structure des HTMLDocument.

    Voici mon programme

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    package Clipboard;
     
    import javax.swing.JTextPane;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import java.awt.BorderLayout;
     
    import javax.swing.TransferHandler;
    import javax.swing.JComponent;
    import java.awt.datatransfer.DataFlavor;
    import java.awt.datatransfer.Transferable;
    import java.awt.datatransfer.Clipboard;
     
    import java.awt.datatransfer.UnsupportedFlavorException;
    import java.awt.datatransfer.ClipboardOwner;
    import java.io.IOException;
    import javax.swing.text.StyledDocument;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.html.HTMLDocument;
    import javax.swing.text.Element;
    import javax.swing.text.SimpleAttributeSet;
     
     
    public class JTextPaneHTMLTransfer2 {
     
        public static void main(String [] args){
            //1 -- Create a JTextPane
            JFrame myFrame = new JFrame("MyTextEditor");
            myFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
            JTextPane myTextPane = new JTextPane();
            myTextPane.setTransferHandler(new JTextPaneHTMLTransferHandler());
            myTextPane.setContentType("text/html");
            JScrollPane myScrollPane = new JScrollPane(myTextPane);
            myFrame.add(myScrollPane, BorderLayout.CENTER);
            myFrame.setSize(400,300);
            myFrame.setVisible(true);
     
        }
    }
     
    class JTextPaneHTMLTransferHandler extends TransferHandler{
     
        DataFlavor htmlFlavor = DataFlavor.stringFlavor;
     
        public JTextPaneHTMLTransferHandler(){
            System.out.println("Constructor of TransferHandler");
            try{
                htmlFlavor = new DataFlavor("text/html;class=java.lang.String");
            }catch (Exception e){
                System.out.println("Flavor creation failed");
            }
        }
     
        public void exportToClipboard(JComponent comp, Clipboard clip, int action) {
            System.out.println("method exportToClipboard");
            super.exportToClipboard(comp, clip, action);
        }
     
        public int getSourceActions(JComponent c) {
            System.out.println("method getSourceActions");
            return COPY_OR_MOVE;
        }
     
        protected Transferable createTransferable(JComponent c){
            System.out.println("method createTransferable");
            JTextPane aTextPane = (JTextPane)c;
     
            int start = aTextPane.getSelectionStart();
            int end = aTextPane.getSelectionEnd();
            StyledDocument aSDoc = aTextPane.getStyledDocument();
            StyledDocument transferDoc = copyHTMLDocument(aSDoc, start, end);
     
            return new HTMLSelection(transferDoc);
        }
     
        public static HTMLDocument copyHTMLDocument(StyledDocument src, int selectionStart, int selectionEnd) { 
            System.out.println("copyDocument Commence");
            Element rootElement, root2Element, paragraphElement, textElement; 
            SimpleAttributeSet copyAttrs;
            int startOffset, endOffset;
            String copy_string;
     
            rootElement = src.getDefaultRootElement();
            HTMLDocument copyDoc = new HTMLDocument();
     
            for (int lpRoot2=0; lpRoot2<rootElement.getElementCount(); lpRoot2++){
                root2Element = rootElement.getElement(lpRoot2);
                for (int lpParagraph=0; lpParagraph<root2Element.getElementCount(); lpParagraph++){
                    paragraphElement = root2Element.getElement(lpParagraph);
     
                    //Check if the paragraph need to be copy
                    if(paragraphElement.getEndOffset() < selectionStart){
                        System.out.println("Continue paragraph");
                        continue; //Go to the next paragraph
                    }
                    if(paragraphElement.getStartOffset() > selectionEnd){
                        System.out.println("Break paragraph");
                        break; //Exit the boucle
                    }
     
                    for (int lpText=0; lpText<paragraphElement.getElementCount(); lpText++) {
                        System.out.println("Text Boucle");
                        //Insert a Element in the new Document    
                        textElement = paragraphElement.getElement(lpText);
     
                        //Check if the Element need to be copy
                        if(textElement.getEndOffset() < selectionStart){
                            System.out.println("Continue text");
                            continue; //Go to the next Element
                        }
                        if(textElement.getStartOffset() > selectionEnd){
                            System.out.println("Break text");
                            break; //Exit the boucle
                        }
     
                        copyAttrs = new SimpleAttributeSet(textElement.getAttributes());
     
                        //Find the value of startOffset and endOffset
                        if(textElement.getStartOffset() < selectionStart){
                            startOffset = selectionStart;
                        }else{
                            startOffset = textElement.getStartOffset();
                        }
                        if(textElement.getEndOffset() > selectionEnd){
                            endOffset = selectionEnd;
                        }else{
                            endOffset = textElement.getEndOffset();
                        }
     
                        try{
                            copy_string = src.getText(startOffset, (endOffset-startOffset));
                            copyDoc.insertString(copyDoc.getLength(), copy_string, copyAttrs);
                        }catch (BadLocationException e){
                            System.out.println("Pogner une exception");
                        }
                    }
                }
            }
     
            return copyDoc;
        }
     
        public boolean canImport(JComponent comp, DataFlavor[] transferFlavors){
            System.out.println("method canImport");
            System.out.println(HTMLSelection.HTMLDocFlavor);
            System.out.println();
            boolean retour = false;
            for(int i=0; i<transferFlavors.length; i++){
                System.out.println(transferFlavors[i]);
                if(HTMLSelection.HTMLDocFlavor.equals(transferFlavors[i])){
                    retour = true;
                }
            }
     
            return retour;
        }
     
        public boolean importData(JComponent comp, Transferable t){
            System.out.println("method importData");
            if(canImport(comp, t.getTransferDataFlavors())){
                System.out.println("canImport is true");
                StyledDocument transferDoc = null;
                try{
                    transferDoc = (StyledDocument)t.getTransferData(HTMLSelection.HTMLDocFlavor);
                }catch (Exception e){
                    System.out.println("transferString failed");
                }
                JTextPane srcTextPane = (JTextPane)comp;
     
                srcTextPane.replaceSelection("");
                int pos = srcTextPane.getSelectionStart();
                insertHTMLDocument(transferDoc, pos, srcTextPane);
     
                return true;
            }
            System.out.println("canImport is false");
            return false;
        }
     
        //Insert a Document in a another Document
        public static void insertHTMLDocument(StyledDocument srcSDoc, int srcPos, JTextPane theTextPane){
            StyledDocument theSDoc = theTextPane.getStyledDocument();
            Element rootElement, paragraphElement, textElement;
            SimpleAttributeSet copyAttrs;
            int startOffset, endOffset;
            int pos = srcPos;
            String copy_string;
     
            rootElement = srcSDoc.getDefaultRootElement();
            rootElement = rootElement.getElement(0);
     
            for (int lpParagraph=0; lpParagraph<rootElement.getElementCount(); lpParagraph++){
                paragraphElement = rootElement.getElement(lpParagraph);
     
                for (int lpText=0; lpText<paragraphElement.getElementCount(); lpText++) {
                    textElement = paragraphElement.getElement(lpText);
                    copyAttrs = new SimpleAttributeSet(textElement.getAttributes());
                    startOffset = textElement.getStartOffset();
                    endOffset = textElement.getEndOffset();
                    //A Verifier
                    try{
                        copy_string = srcSDoc.getText(startOffset, (endOffset-startOffset));
                        theSDoc.insertString(pos, copy_string, copyAttrs);
                    }catch (BadLocationException e){
                        System.out.println("Pogner une exception");
                    }
                    pos += endOffset-startOffset;
                }
            }
            try{
                theSDoc.remove(pos-1, 1);
            }catch(BadLocationException e){
                System.out.println("Didn't work");
            }
        }
     
    }
     
    class HTMLSelection implements Transferable, ClipboardOwner{
        private HTMLDocument dataDoc;
        public static DataFlavor HTMLDocFlavor = new DataFlavor(HTMLDocument.class, "HTMLDocFlavor");
        private DataFlavor [] supportedFlavors = {HTMLDocFlavor};
     
        public HTMLSelection(StyledDocument dataDoc){
            System.out.println("Constructeur StringTransferSelection avec HTMLDoc");
            this.dataDoc = (HTMLDocument)dataDoc;
        }
     
        public DataFlavor[] getTransferDataFlavors(){
            System.out.println("method getTransferDataFlavors");
            return supportedFlavors;
        }
     
        public boolean isDataFlavorSupported(DataFlavor flavor){
            //System.out.println("method isDataFlavorSupported");
            if(flavor.equals(HTMLDocFlavor)){
                return true;
            }
            return false;
        }
     
        public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException{
            System.out.println("method getTransferData");
            if(flavor.equals(HTMLDocFlavor)){
                return dataDoc;
            }else{
                throw new UnsupportedFlavorException(flavor);
            }
        }
     
        public void lostOwnership(Clipboard clipboard, Transferable contents){
            System.out.println("method lostOwnership");
        }
    }

Discussions similaires

  1. Réponses: 3
    Dernier message: 09/02/2007, 18h51
  2. [vb6]:Ajuster des données dans un fichier text avec un timer
    Par gaetan.tranvouez dans le forum VB 6 et antérieur
    Réponses: 25
    Dernier message: 28/07/2006, 12h13
  3. Réponses: 9
    Dernier message: 22/05/2006, 12h21
  4. Probleme d'affichage du curseur dans un chp texte avec firef
    Par dadovb dans le forum Général JavaScript
    Réponses: 1
    Dernier message: 20/10/2005, 12h31
  5. [Débutant] SWT: composant Texte avec \n
    Par bonnefr dans le forum SWT/JFace
    Réponses: 3
    Dernier message: 18/05/2004, 11h44

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo