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

Graphisme Java Discussion :

JTextPane avec styles de texte différents.


Sujet :

Graphisme Java

  1. #1
    Membre éclairé Avatar de Razgriz
    Profil pro
    Professeur / chercheur en informatique / mathématiques
    Inscrit en
    Avril 2006
    Messages
    391
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Professeur / chercheur en informatique / mathématiques

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Par défaut JTextPane avec styles de texte différents.
    Salut à tous,

    voilà en ce moment je cherche à créér un JTextPane sur lequel je saurai faire des append(text) comme dans une JTextArea, jusque là rien de bien compliqué, mais en plus je voudrai surtout pouvoir changer de style de texte à chaque fois que je veux faire un append, et ça ça ne marche pas.
    Avec les classes ci-dessous le style de texte ne change jamais...

    La classe pour les styles, très simple :
    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
     
    /**
     * File DefaultStyle.java
     * Created on 17 mai 2008
     */
     
    package util.graphics.text;
     
    import java.awt.Color;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.DefaultStyledDocument;
    import javax.swing.text.Style;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyleContext;
     
    /**
     * 
     * @author Evenstar
     */
    public class SimpleStyle extends DefaultStyledDocument
    {
        private StyleContext context;
        private Style defaultStyle;
        private String current;
     
        public SimpleStyle()
        {
            this(new StyleContext());
        }
     
        public SimpleStyle(StyleContext context) 
        {
            super(context);
     
            this.context = context;
            this.current = StyleContext.DEFAULT_STYLE;
            this.defaultStyle = context.getStyle(current);
        }
     
        public String getCurrentStyleName()
        {
            return current;
        }
     
        public  void setCurrentStyle(String styleName)
        {
            this.current = styleName;
        }
     
        public void setTextStyle(int start, int length, String styleName)
        {
            setCharacterAttributes (start, length,getStyle (styleName), true);
        }
     
        public  void addStyle(String styleName, Color textColor)
        {
            Style newStyle = context.addStyle(styleName, defaultStyle);
            StyleConstants.setForeground(newStyle, textColor);
        }
     
        public void addStyle(String styleName, int fontsize, String fontname, 
                Color textColor, boolean isBold, boolean isItalic, boolean isUnderline)
        {
            Style newStyle = context.addStyle(styleName, defaultStyle);
     
            StyleConstants.setFontSize(newStyle, fontsize);
            StyleConstants.setFontFamily(newStyle, fontname);
            StyleConstants.setForeground(newStyle, textColor);
            StyleConstants.setBold(newStyle, isBold);
            StyleConstants.setItalic(newStyle, isItalic);
            StyleConstants.setUnderline(newStyle, isUnderline);
        }
     
        public void insertString(int offset, String text, AttributeSet a) throws BadLocationException 
        {
            super.insertString(offset, text, getStyle(current));
            setTextStyle(offset, text.length(), current);
        }
    }
    La classe héritée pour le TextPane, simple elle aussi :
    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
     
    /**
     * File SimpleTextPane.java
     * Created on 17 mai 2008
     */
    package util.graphics.text;
     
    import javax.swing.JTextPane;
    import javax.swing.text.BadLocationException;
     
    /**
     * 
     * @author Evenstar
     */
    public class SimpleTextPane extends JTextPane 
    {
        private SimpleStyle style;
     
        public SimpleTextPane()
        {
            this(new SimpleStyle());
        }
     
        public  SimpleTextPane(SimpleStyle style)
        {
            super(style);
            this.style = style;
        }
     
        public void append(String text)
        {
            try 
            {
                String txt = this.getText();
                if(txt != null)
                    style.insertString(txt.length(), text, null);
                else
                {
                    style.insertString(0, text, null);
                }
            } 
            catch (BadLocationException ex) 
            {
                ex.printStackTrace();
            }
        }
     
        public void append(String text, String styleName)
        {
            String old = style.getCurrentStyleName();
            style.setCurrentStyle(styleName);
     
            try
            {
                style.insertString(this.getText().length(), text, null);
            }
            catch(BadLocationException ex)
            {
                ex.printStackTrace();
            }
     
            style.setCurrentStyle(old);
        }
    }
    Et la classe de test qui dessine une fenêtre bidon :
    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
     
    /**
     * File TextPaneTest.java
     * Created on 17 mai 2008
     */
     
    package test;
     
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.DefaultStyledDocument;
    import javax.swing.text.Style;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyleContext;
    import util.graphics.text.SimpleStyle;
    import util.graphics.text.SimpleTextPane;
     
    /**
     *
     * @author Absil Romain
     */
    public class TextPaneTest 
    {
     
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) 
        {
            new TextFrame();
        }
    }
     
    class TextFrame extends JFrame
    {
        //private OutStyle style;
     
        public TextFrame()
        {
            setSize(800, 600);
            setTitle("Title");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            final SimpleStyle style = new SimpleStyle();
            style.addStyle("error", Color.RED);
     
            SimpleTextPane pane = new SimpleTextPane();
            add(new JScrollPane(pane), BorderLayout.CENTER);
     
     
     
    //        style = new OutStyle(new StyleContext());
    //        pane.setDocument(style);
     
            JButton change = new JButton("Change style");
            change.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e)
                {
                    if(style.getCurrentStyleName().equals("error"))
                        style.setCurrentStyle(StyleContext.DEFAULT_STYLE);
                    else
                        style.setCurrentStyle("error");
                }
            });
            add(change, BorderLayout.SOUTH);
     
            setVisible(true);
     
            pane.append("Texte normal\n");
            try
            {
                Thread.sleep(1000L);
            }
            catch(InterruptedException ex)
            {
            }
     
            style.setCurrentStyle("error");
            pane.append("error");
     
     
        }
    }
     
    class OutStyle extends DefaultStyledDocument
    {
        private String styleType = "normal";
     
        public OutStyle(StyleContext context)
        {
            super(context);
            initStyle(context);
        }
     
        public void insertString(int offs, String str, AttributeSet a)
                throws BadLocationException
        {
            try
            {
                if (str.equals("error"))
                    super.insertString(offs, str, getStyle("error"));
                else
                    super.insertString(offs, str, getStyle("normal"));
            }
            catch (BadLocationException ex)
            {
                ex.printStackTrace();
            }
        }
     
        public void setStyleType(String styleType)
        {
            if(styleType.equals("error"))
                this.styleType = "error";
            else
                this.styleType = "normal";
        }
     
        public String getStyleType()
        {
            return styleType;
        }
     
        public void initStyle(StyleContext styles)
        {
            Style def = styles.getStyle (StyleContext.DEFAULT_STYLE);
     
            Style normal = styles.addStyle("normal", def);
            StyleConstants.setFontFamily(normal, "Courier");
            StyleConstants.setFontSize(normal, 11);
            StyleConstants.setForeground(normal, Color.BLACK);
            StyleConstants.setBold(normal, false);
     
            Style error = styles.addStyle("error", normal);
            StyleConstants.setForeground(error, Color.RED);
            StyleConstants.setBold(error, true);
        }
    }

    Franchement je ne trouve pas. Notez que j'ai essayé de faire des
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    setCharacterAttributes (positionDepart, longueur, style, true)
    dans les append pour forcer la mise à jour du style mais ça fait rien...

    Quelqu'un a-t-il une idée de comment procéder?

    N.B. : si vous copiez/collez le code faites attentions aux déclarations package.

  2. #2
    Membre éclairé Avatar de Razgriz
    Profil pro
    Professeur / chercheur en informatique / mathématiques
    Inscrit en
    Avril 2006
    Messages
    391
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations professionnelles :
    Activité : Professeur / chercheur en informatique / mathématiques

    Informations forums :
    Inscription : Avril 2006
    Messages : 391
    Par défaut
    Ok oubliez-ça j'ai résolu mon problème.
    Pour ceux qui en auraient besoin voici la classe finale (le JTextPane) qui fait tout ce que je veux (la javadoc est manquante : tous les getters et setters concernant directement la forme du texte sont appliqués sur le style par défaut, pas sur le style courant).

    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
    255
    256
    257
    258
    259
    260
    261
    262
     
    /**
     * File SimpleTextPane.java
     * Created on 17 mai 2008
     */
    package util.graphics.text;
     
    import java.awt.Color;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.StringReader;
    import java.util.Scanner;
    import javax.swing.JTextPane;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    import javax.swing.text.Style;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyleContext;
    import javax.swing.text.StyledDocument;
    import javax.swing.text.rtf.RTFEditorKit;
     
    public class SimpleTextPane extends JTextPane
    {
     
        public Style def = StyleContext.getDefaultStyleContext().getStyle(
                StyleContext.DEFAULT_STYLE);
        public Style style;
     
        public String current;
     
        public SimpleTextPane()
        {
            super();
            style = addStyle("default", def);
            current = "default";
        }
     
        public SimpleTextPane(StyledDocument doc)
        {
            super(doc);
            style = addStyle("default", def);
            current = "default";
        }
     
        public  void addStyle(String name, Color color)
        {
            Style newStyle = addStyle(name, style);
            StyleConstants.setForeground(newStyle, color);
        }
     
        public  void addStyle(String name, String fontName, int size, Color color, 
                boolean bold, boolean italic, boolean underline, boolean strike)
        {
            Style newStyle = addStyle(name, style);
     
            StyleConstants.setFontFamily(newStyle, fontName);
            StyleConstants.setFontSize(newStyle, size);
            StyleConstants.setForeground(newStyle, color);
            StyleConstants.setBold(newStyle, bold);
            StyleConstants.setItalic(newStyle, italic);
            StyleConstants.setUnderline(newStyle, underline);
            StyleConstants.setStrikeThrough(newStyle, strike);
        }
     
        public void append(String text)
        {
            append(text, current);
        }
     
        public void append(String text, Color color)
        {
            Color c = this.getFontColor();
            StyleConstants.setForeground(style, color);
            append(text, "default");
            StyleConstants.setForeground(style, c);
        }
     
        public void append(String text, String style)
        {
            try
            {
                Document doc = getDocument();
                doc.insertString(doc.getLength(), text, getStyle(style));
                setCaretPosition(getDocument().getLength());
            }
            catch (BadLocationException e)
            {
                e.printStackTrace();
            }
        }
     
        public  void insertString(int offset, String text)
        {
            insertString(offset, text, current);
        }
     
        public void insertString(int offset, String text, Color color)
        {
            Color c = this.getFontColor();
            StyleConstants.setForeground(style, color);
            insertString(offset, text, "default");
            StyleConstants.setForeground(style, c);
        }
     
        public void insertString(int offset, String text, String style)
        {
            try
            {
                Document doc = getDocument();
                doc.insertString(offset, text, getStyle(style));
                setCaretPosition(getDocument().getLength());
            }
            catch (BadLocationException e)
            {
                e.printStackTrace();
            }
        }
     
        public void erase(int offset, int length)
        {
            this.select(offset, length);
            this.replaceSelection("");
        }
     
        public Style getStyle()
        {
            return style;
        }
     
        public String getCurrentStyle()
        {
            return current;
        }
     
        public Color getTextBackground()
        {
            return StyleConstants.getBackground(style);
        }
     
        public Color getFontColor()
        {
            return StyleConstants.getForeground(style);
        }
     
        public int getFontSize()
        {
            return StyleConstants.getFontSize(style);
        }
     
        public String getFontName()
        {
            return StyleConstants.getFontFamily(style);
        }
     
        public boolean isBold()
        {
            return StyleConstants.isBold(style);
        }
     
        public boolean isItalic()
        {
            return StyleConstants.isItalic(style);
        }
     
        public boolean isStrike()
        {
            return StyleConstants.isStrikeThrough(style);
        }
     
        public boolean isUnderLine()
        {
            return StyleConstants.isUnderline(style);
        }
     
        public void setCurrentStyle(String style)
        {
            this.current = style;
        }
     
        public void setTextBackground(Color color)
        {
            StyleConstants.setBackground(style, color);
            this.setCharacterAttributes(style, true);
        }
     
        public void setBold(boolean bold)
        {
            StyleConstants.setBold(style, bold);
            this.setCharacterAttributes(style, true);
        }
     
        public void setColor(Color color)
        {
            StyleConstants.setForeground(style, color);
            this.setCharacterAttributes(style, true);
        }
     
        public void setFont(String fontName)
        {
            StyleConstants.setFontFamily(style, fontName);
            this.setCharacterAttributes(style, true);
        }
     
        public void setFontSize(int size)
        {
            StyleConstants.setFontSize(style, size);
            this.setCharacterAttributes(style, true);
        }
     
        public void setItalic(boolean italic)
        {
            StyleConstants.setItalic(style, italic);
            this.setCharacterAttributes(style, true);
        }
     
        public void setStrikeThrough(boolean strikeThrough)
        {
            StyleConstants.setStrikeThrough(style, strikeThrough);
            this.setCharacterAttributes(style, true);
        }
     
        public void setUnderLine(boolean underline)
        {
            StyleConstants.setUnderline(style, underline);
            this.setCharacterAttributes(style, true);
        }
     
        public void saveAsRTFFile(File dest) 
                throws IOException
        {
            RTFEditorKit rtf = new RTFEditorKit();
            FileOutputStream fout = new FileOutputStream(dest);
            try
            {
                rtf.write(fout, getDocument(), 0, getDocument().getLength());
            }
            catch(BadLocationException ex)
            {
                ex.printStackTrace();
            }
            fout.close();
        }
     
        public void readRTFFile(File src) throws IOException, BadLocationException
        {
            StringBuilder sb = new StringBuilder();
            Scanner sc = new Scanner(src);
            while (sc.hasNext())
                sb.append(sc.nextLine() + "\r\n");
            sc.close();
            RTFEditorKit rtf = new RTFEditorKit();
            try
            {
                rtf.read(new StringReader(sb.toString()), getDocument(), 0);
            }
            catch(BadLocationException ex)
            {
                ex.printStackTrace();
            }
        }
    }

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Ajouter texte avec style de texte dans word
    Par pimos dans le forum VBA Word
    Réponses: 8
    Dernier message: 16/04/2009, 11h48
  2. Pb table dans div avec style sur le texte
    Par snoop dans le forum Balisage (X)HTML et validation W3C
    Réponses: 6
    Dernier message: 23/06/2006, 10h07
  3. Changer la police d'un texte autrement qu'avec style
    Par Death83 dans le forum Général JavaScript
    Réponses: 8
    Dernier message: 14/03/2006, 13h45
  4. Remplir 3 champs textes différents avec une liste déroulante
    Par azorol dans le forum Général JavaScript
    Réponses: 3
    Dernier message: 20/12/2005, 00h04
  5. [JTextComponent] Afficher du texte avec style et image
    Par jean_bobi dans le forum Composants
    Réponses: 9
    Dernier message: 30/10/2005, 13h47

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