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 :

Menu contextuel sur JTextPane


Sujet :

AWT/Swing Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre confirmé
    Inscrit en
    Octobre 2006
    Messages
    108
    Détails du profil
    Informations forums :
    Inscription : Octobre 2006
    Messages : 108
    Par défaut Menu contextuel sur JTextPane
    Bonjour,

    J'ai créé une classe dérivée de JTextPane pour faire de la coloration syntaxique et repérer certains éléments intéressants du texte. Maintenant, je voudrais pouvoir ajouter un menu contextuel sur ces éléments du texte.

    J'ai cherché et j'ai bien vu des choses comme HyperLinkListener, mais çà ne fait pas vraiment ce que je veux et c'est pour du HTML.
    Quelqu'un aurait-il des idées sur la façon de procéder ?

    Pour tester mon code actuel: http://test04145.mutu.sivit.org/Wiki...iaCleaner.jnlp
    (il faut un compte sur Wikipédia)

    Code MediaWikiPane.java : 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
     
    package org.wikipediacleaner.gui.swing.components;
     
    import java.awt.Color;
    import java.util.ArrayList;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
     
    import javax.swing.JTextPane;
    import javax.swing.text.DefaultStyledDocument;
    import javax.swing.text.Style;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyleContext;
     
    import org.wikipediacleaner.api.data.Page;
     
     
    /**
     * A text component to colorize / edit MediaWiki text.
     */
    public class MediaWikiPane extends JTextPane {
     
      private static final long serialVersionUID = 3225120886653438117L;
      public final static String STYLE_DISAMBIGUATION_LINK = "Disambiguation";
      public final static String STYLE_EXTERNAL_LINK = "ExternalLink";
      public final static String STYLE_NORMAL_LINK = "NormalLink";
     
      private ArrayList<Page> internalLinks;
     
      /**
       * Construct a MediaWikiPane. 
       */
      public MediaWikiPane() {
        super();
        initialize();
      }
     
      /**
       * Initialize styles. 
       */
      private void initialize() {
        DefaultStyledDocument doc = new DefaultStyledDocument();
        setStyledDocument(doc);
     
        Style root = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
     
        Style normalLink = addStyle(STYLE_NORMAL_LINK, root);
        StyleConstants.setForeground(normalLink, Color.BLUE);
     
        Style disambiguationLink = addStyle(STYLE_DISAMBIGUATION_LINK, root);
        StyleConstants.setBold(disambiguationLink, true);
        StyleConstants.setForeground(disambiguationLink, Color.RED);
     
        Style externalLink = addStyle(STYLE_EXTERNAL_LINK, root);
        StyleConstants.setForeground(externalLink, new Color(128, 128, 255));
      }
     
      /* (non-Javadoc)
       * @see javax.swing.JEditorPane#setText(java.lang.String)
       */
      @Override
      public void setText(String t) {
        super.setText(t);
        resetAttributes();
      }
     
      /**
       * @return List of disambiguation links.
       */
      public ArrayList<Page> getInternalLinks() {
        return internalLinks;
      }
     
      /**
       * @param list List of disambiguation links.
       */
      public void setInternalLinks(ArrayList<Page> list) {
        internalLinks = list;
        resetAttributes();
      }
     
      /**
       * Reset attributes of the document.
       * This methode should be called after modifications are done.
       */
      private void resetAttributes() {
        // First remove every attributes
        selectAll();
        setCharacterAttributes(getStyle(StyleContext.DEFAULT_STYLE), true);
        setCaretPosition(0);
        moveCaretPosition(0);
     
        // Look for disambiguation links
        if (internalLinks != null) {
          for (int i = 0; i < internalLinks.size(); i++) {
            Page page = internalLinks.get(i);
            Pattern pattern = createPatternForInternalLink(page);
            Matcher matcher = pattern.matcher(getText());
            while (matcher.find()) {
              int start = matcher.start();
              int end = matcher.end();
              //System.err.println("Match found: " + matcher.group() + " (" + start + "," + end + ")");
              setCaretPosition(start);
              moveCaretPosition(end);
              if (page.isDisambiguationPage()) {
                setCharacterAttributes(getStyle(STYLE_DISAMBIGUATION_LINK), true);
              } else {
                setCharacterAttributes(getStyle(STYLE_NORMAL_LINK), true);
              }
            }
          }
        }
     
        setCaretPosition(0);
        moveCaretPosition(0);
      }
     
      /**
       * Creates a Pattern for matching internal links to give <code>page</code>.
       * 
       * @param page The interesting page.
       * @return Pattern.
       */
      private Pattern createPatternForInternalLink(Page page) {
        if (page == null) {
          return null;
        }
        String title = page.getTitle();
     
        // Create the regular expression
        StringBuffer expression = new StringBuffer();
        expression.append("\\[\\["); // [[
        expression.append("\\s*"); // Possible white characters
        if (title.length() > 0) {
          // First character can be upper case or lower case
          expression.append(
              "[" +
              Character.toLowerCase(title.charAt(0)) +
              Character.toUpperCase(title.charAt(0)) +
              "]");
        }
        if (title.length() > 1) {
          // The page title itself without metacharacters
          expression.append(Pattern.quote(title.substring(1)));
        }
        expression.append("\\s*"); // Possible white characters
        expression.append("(\\|[^\\|\\]]*)?"); // Possible text
        expression.append("\\]\\]"); // ]]
        //System.err.println("Regular expression: " + expression.toString());
        Pattern pattern = Pattern.compile(expression.toString());
        return pattern;
      }
    }

  2. #2
    Membre confirmé
    Inscrit en
    Octobre 2006
    Messages
    108
    Détails du profil
    Informations forums :
    Inscription : Octobre 2006
    Messages : 108
    Par défaut
    A priori résolu, en cours de finition

    Code MediaWikiPane.java : 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
     
    package org.wikipediacleaner.gui.swing.components;
     
    import java.awt.Color;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.util.ArrayList;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
     
    import javax.swing.JTextPane;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.DefaultStyledDocument;
    import javax.swing.text.Element;
    import javax.swing.text.Style;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyleContext;
     
    import org.wikipediacleaner.api.data.Page;
     
     
    /**
     * A text component to colorize / edit MediaWiki text.
     */
    public class MediaWikiPane
        extends JTextPane
        implements MouseListener {
     
      private static final long serialVersionUID = 3225120886653438117L;
     
      private ArrayList<Page> internalLinks;
     
      /**
       * Construct a MediaWikiPane. 
       */
      public MediaWikiPane() {
        super();
        initialize();
      }
     
      /**
       * Initialize styles. 
       */
      private void initialize() {
        DefaultStyledDocument doc = new DefaultStyledDocument();
        setStyledDocument(doc);
     
        Style root = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
     
        Style normalLink = addStyle(MediaWikiConstants.STYLE_NORMAL_LINK, root);
        StyleConstants.setBold(normalLink, true);
        StyleConstants.setForeground(normalLink, Color.BLUE);
        normalLink.addAttribute("MEDIAWIKI", "NORMAL_LINK");
     
        Style disambiguationLink = addStyle(MediaWikiConstants.STYLE_DISAMBIGUATION_LINK, root);
        StyleConstants.setBold(disambiguationLink, true);
        StyleConstants.setForeground(disambiguationLink, Color.RED);
        disambiguationLink.addAttribute("MEDIAWIKI", "DISAMBIGUATION_LINK");
     
        Style externalLink = addStyle(MediaWikiConstants.STYLE_EXTERNAL_LINK, root);
        StyleConstants.setForeground(externalLink, new Color(128, 128, 255));
     
        addMouseListener(this);
      }
     
      /* (non-Javadoc)
       * @see javax.swing.JEditorPane#setText(java.lang.String)
       */
      @Override
      public void setText(String t) {
        super.setText(t);
        resetAttributes();
      }
     
      /**
       * @return List of disambiguation links.
       */
      public ArrayList<Page> getInternalLinks() {
        return internalLinks;
      }
     
      /**
       * @param list List of disambiguation links.
       */
      public void setInternalLinks(ArrayList<Page> list) {
        internalLinks = list;
        resetAttributes();
      }
     
      /**
       * Reset attributes of the document.
       * This methode should be called after modifications are done.
       */
      private void resetAttributes() {
        // First remove every attributes
        selectAll();
        setCharacterAttributes(getStyle(StyleContext.DEFAULT_STYLE), true);
        setCaretPosition(0);
        moveCaretPosition(0);
     
        // Look for disambiguation links
        if (internalLinks != null) {
          for (int i = 0; i < internalLinks.size(); i++) {
            Page page = internalLinks.get(i);
            Pattern pattern = createPatternForInternalLink(page);
            Matcher matcher = pattern.matcher(getText());
            Style attr = null;
            while (matcher.find()) {
              int start = matcher.start();
              int end = matcher.end();
              setCaretPosition(start);
              moveCaretPosition(end);
              if (attr == null) {
                if (page.isDisambiguationPage()) {
                  attr = getStyle(MediaWikiConstants.STYLE_DISAMBIGUATION_LINK);
                  attr = (Style) attr.copyAttributes();
                  attr.addAttribute(
                      MediaWikiConstants.ATTRIBUTE_TYPE,
                      MediaWikiConstants.VALUE_DISAMBIGUATION_LINK);
                } else {
                  attr = getStyle(MediaWikiConstants.STYLE_NORMAL_LINK);
                  attr = (Style) attr.copyAttributes();
                  attr.addAttribute(
                      MediaWikiConstants.ATTRIBUTE_TYPE,
                      MediaWikiConstants.VALUE_NORMAL_LINK);
                }
              }
              setCharacterAttributes(attr, true);
            }
          }
        }
     
        setCaretPosition(0);
        moveCaretPosition(0);
      }
     
      /**
       * Creates a Pattern for matching internal links to give <code>page</code>.
       * 
       * @param page The interesting page.
       * @return Pattern.
       */
      private Pattern createPatternForInternalLink(Page page) {
        if (page == null) {
          return null;
        }
        String title = page.getTitle();
     
        // Create the regular expression
        StringBuffer expression = new StringBuffer();
        expression.append("\\[\\["); // [[
        expression.append("\\s*"); // Possible white characters
        if (title.length() > 0) {
          // First character can be upper case or lower case
          expression.append(
              "[" +
              Character.toLowerCase(title.charAt(0)) +
              Character.toUpperCase(title.charAt(0)) +
              "]");
        }
        if (title.length() > 1) {
          // The page title itself without metacharacters
          expression.append(Pattern.quote(title.substring(1)));
        }
        expression.append("\\s*"); // Possible white characters
        expression.append("(\\|[^\\|\\]]*)?"); // Possible text
        expression.append("\\]\\]"); // ]]
        //System.err.println("Regular expression: " + expression.toString());
        Pattern pattern = Pattern.compile(expression.toString());
        return pattern;
      }
     
      /**
       * Called when the user clicks in the text area.
       * 
       * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
       */
      public void mouseClicked(MouseEvent e) {
        if (e == null) {
          return;
        }
        int position = viewToModel(e.getPoint());
        switch (e.getButton()) {
        case MouseEvent.BUTTON3:
          Element element = getStyledDocument().getCharacterElement(position);
          System.err.println("Element type: " + element.getClass().getName());
          try {
            System.err.println("Click on: " + getText(
                element.getStartOffset(),
                element.getEndOffset() - element.getStartOffset()));
          } catch (BadLocationException e1) {
            // TODO
          }
          break;
        }
      }
     
      /* (non-Javadoc)
       * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
       */
      public void mouseEntered(@SuppressWarnings("unused") MouseEvent e) {
        //
      }
     
      /* (non-Javadoc)
       * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
       */
      public void mouseExited(@SuppressWarnings("unused") MouseEvent e) {
        //
      }
     
      /* (non-Javadoc)
       * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
       */
      public void mousePressed(@SuppressWarnings("unused") MouseEvent e) {
        //
      }
     
      /* (non-Javadoc)
       * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
       */
      public void mouseReleased(@SuppressWarnings("unused") MouseEvent e) {
        //
      }
    }

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

Discussions similaires

  1. [MFC] Menu contextuel sur CListBox
    Par rabobsky dans le forum MFC
    Réponses: 2
    Dernier message: 21/02/2006, 14h11
  2. Menu contextuelle sur une liste?
    Par _developpeur_ dans le forum Access
    Réponses: 2
    Dernier message: 24/01/2006, 14h33
  3. Afficher un menu contextuelle sur le click droit d'une image
    Par PrinceMaster77 dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 13/01/2006, 12h19
  4. Menu contextuel sur CStatic
    Par benahpets dans le forum MFC
    Réponses: 8
    Dernier message: 05/07/2005, 10h27
  5. [VB6] menu contextuel sur clique droit souris
    Par da40 dans le forum VB 6 et antérieur
    Réponses: 7
    Dernier message: 08/07/2003, 11h07

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