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
| // appeler le fichier Exemple101_StyledDocument.java
// Nicolas_75
// vendredi 14 septembre 2007
// pour http://www.developpez.net/forums/showthread.php?t=410585
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.text.*;
public class Exemple101_StyledDocument extends JFrame {
private static final String TEXT = "La terre est bleue comme une orange...\n\nLa terre est bleue comme une orange\nJamais une erreur les mots ne mentent pas\nIls ne vous donnent plus à chanter\nAu tour des baisers de s'entendre\nLes fous et les amours\nElle sa bouche d'alliance\nTous les secrets tous les sourires\nEt quels vêtements d'indulgence\nÀ la croire toute nue.\n\nLes guêpes fleurissent vert\nL'aube se passe autour du cou\nUn collier de fenêtres\nDes ailes couvrent les feuilles\nTu as toutes les joies solaires\nTout le soleil sur la terre\nSur les chemins de ta beauté.\n\nPaul ELUARD, L'Amour la poésie (1929)";
private static final String KEYWORD = "en";
private JTextPane textpane; // contiendra le texte
private StyledDocument sdoc; // StyledDocument correspondant
// pour le surlignement :
private SimpleAttributeSet yellowHighlighted = new SimpleAttributeSet();
{
StyleConstants.setBackground(yellowHighlighted, Color.yellow);
}
private SimpleAttributeSet whiteHighlighted = new SimpleAttributeSet();
// constructeur
public Exemple101_StyledDocument() {
// caractéristiques générales de la frame :
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// bouton de surlignement en jaune :
JButton buttonA = new JButton("surligne sélection en jaune");
buttonA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if ((!(sdoc==null))&&(!(textpane.getSelectedText()==null))) {
sdoc.setCharacterAttributes(textpane.getSelectionStart(), textpane.getSelectedText().length(), yellowHighlighted, false);
}
}
});
// bouton d'annulation du surlignement en jaune :
JButton buttonB = new JButton("enlève le surlignement de la sélection");
buttonB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if ((!(sdoc==null))&&(!(textpane.getSelectedText()==null))) {
sdoc.setCharacterAttributes(textpane.getSelectionStart(), textpane.getSelectedText().length(), whiteHighlighted, true);
}
}
});
// mise en place de la fenêtre
JPanel buttonPanel = new JPanel();
buttonPanel.add(buttonA);
buttonPanel.add(buttonB);
textpane = new JTextPane();
textpane.setEditable(true);
JScrollPane scroll = new JScrollPane(textpane);
scroll.setPreferredSize(new Dimension(300,200));
JPanel generalPanel = new JPanel();
generalPanel.setLayout(new BorderLayout());
generalPanel.add(buttonPanel, BorderLayout.CENTER);
generalPanel.add(scroll, BorderLayout.SOUTH);
this.getContentPane().add(generalPanel, BorderLayout.SOUTH);
// affichage de la frame :
this.pack();
this.setVisible(true);
// on affiche le texte avec les mots clés surlignés :
lookForKeyWords();
}
// méthode d'affichage du texte avec les mots clés surlignés :
public void lookForKeyWords() {
String regex = KEYWORD;
// on rajoute "--" avant et après pour que le split ci-dessous fonctionne
// même si le mot clé est en début ou en fin de texte :
String text = "--"+TEXT+"--";
// récupération du texte situé de part et d'autre des mots clés :
String[] wordsBetweenKeyWords = text.split(regex);
// maintenant, on peut enlever les tirets :
wordsBetweenKeyWords[0] = wordsBetweenKeyWords[0].substring(2);
int indexOfLast = wordsBetweenKeyWords.length-1;
int sizeOfLast = wordsBetweenKeyWords[indexOfLast].length();
wordsBetweenKeyWords[indexOfLast]
= wordsBetweenKeyWords[indexOfLast].substring(0, sizeOfLast-2);
// récupération de la liste des occurrences des mots clés :
ArrayList<String> keyWordsOccurrencesListBuffer = new ArrayList<String>();
Matcher m = Pattern.compile(regex).matcher(text);
while(m.find()) {
keyWordsOccurrencesListBuffer.add(m.group());
}
String[] keyWordsOccurrencesList = new String[keyWordsOccurrencesListBuffer.size()];
keyWordsOccurrencesList = keyWordsOccurrencesListBuffer.toArray(keyWordsOccurrencesList);
// dans la zone texte, écriture du texte initial en surlignant les mots clés :
sdoc = textpane.getStyledDocument();
try {
sdoc.remove(0,sdoc.getLength());
sdoc.insertString(sdoc.getLength(), wordsBetweenKeyWords[0], null);
int k;
for (int i=0; i<keyWordsOccurrencesList.length; i++) {
sdoc.insertString(sdoc.getLength(), keyWordsOccurrencesList[i], yellowHighlighted);
sdoc.insertString(sdoc.getLength(), wordsBetweenKeyWords[i+1], null);
}
textpane.setCaretPosition(0);
} catch (BadLocationException ble) {
System.out.println("Couldn't insert text into text pane. This should not happen!");
ble.printStackTrace();
}
}
public static void main(String[] args) {
new Exemple101_StyledDocument();
}
} |
Partager