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
| // Nicolas_75, 27 août 2006
// http://www.developpez.net/forums/showthread.php?p=1297289
// appeler le fichier Exemple064_StyledDocument.java
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.text.*;
public class Exemple064_StyledDocument extends JFrame {
private JTextArea text2; // texte initial
private JTextArea text4; // liste des mots clés
private JTextPane text7; // texte avec mots clés surlignés
public Exemple064_StyledDocument() {
// caractéristiques générales de la frame :
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// JTextArea supérieur, contenant le texte initial :
JLabel label1 = new JLabel("Texte initial :");
text2 = new JTextArea();
text2.setEditable(true);
text2.setRows(10);
text2.setColumns(40);
JScrollPane scroll2 = new JScrollPane(text2);
JPanel panel12 = new JPanel();
panel12.setLayout(new BorderLayout());
panel12.add(label1, BorderLayout.NORTH);
panel12.add(scroll2, BorderLayout.SOUTH);
this.getContentPane().add(panel12, BorderLayout.NORTH);
// initialisation du texte initial :
text2.append("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)");
// JTextArea médian, contenant les mots clés à trouver :
JLabel label3 = new JLabel("Mots clés à chercher :");
text4 = new JTextArea();
text4.setEditable(true);
text4.setPreferredSize(new Dimension(500,50));
text4.setRows(1);
text4.setColumns(40);
JScrollPane scroll4 = new JScrollPane(text4);
// initialisation des mots clés
text4.append("les la sa un");
// bouton de lancement de la recherche de mots clés :
JButton button5 = new JButton("Chercher les mots clés <== CLIQUER !");
button5.setBackground(Color.CYAN);
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lookForKeyWords();
}
});
// inclusion du JTextArea médian et du bouton dans la fenêtre :
JPanel panel345 = new JPanel();
panel345.setLayout(new BorderLayout());
panel345.add(label3, BorderLayout.NORTH);
panel345.add(scroll4, BorderLayout.CENTER);
panel345.add(button5, BorderLayout.SOUTH);
this.getContentPane().add(panel345, BorderLayout.CENTER);
// JTextArea inférieur, contenant le texte avec mots clés identifiés :
JLabel label6 = new JLabel("Texte après identification des mots-clés :");
text7 = new JTextPane();
text7.setEditable(true);
JScrollPane scroll7 = new JScrollPane(text7);
scroll7.setPreferredSize(new Dimension(300,200));
JPanel panel67 = new JPanel();
panel67.setLayout(new BorderLayout());
panel67.add(label6, BorderLayout.NORTH);
panel67.add(scroll7, BorderLayout.SOUTH);
this.getContentPane().add(panel67, BorderLayout.SOUTH);
// affichage de la frame :
this.pack();
this.setVisible(true);
}
public void lookForKeyWords() {
// récupération de la liste des mots clés
String[] keyWordsList = text4.getText().split(" ");
// construction d'une regex correspondant à ces mots clés :
StringBuffer regexBuffer = new StringBuffer("");
if (keyWordsList.length>0) {
regexBuffer.append("("+keyWordsList[0]);
int i=1;
while (i<keyWordsList.length) {
regexBuffer.append("|"+keyWordsList[i]);
i++;
}
regexBuffer.append(")");
}
String regex = regexBuffer.toString();
// à ce stade, regex == "(les|la|sa|un)"
// récupération du texte situé de part et d'autre des mots clés :
String[] wordsBetweenKeyWords = text2.getText().split(regex);
// récupération de la liste des occurrences des mots clés :
ArrayList<String> keyWordsOccurrencesListBuffer = new ArrayList<String>();
Matcher m = Pattern.compile(regex).matcher(text2.getText());
while(m.find()) {
keyWordsOccurrencesListBuffer.add(m.group());
}
String[] keyWordsOccurrencesList = new String[keyWordsOccurrencesListBuffer.size()];
keyWordsOccurrencesList = keyWordsOccurrencesListBuffer.toArray(keyWordsOccurrencesList);
// création du style par défaut et du style gras :
StyledDocument doc = text7.getStyledDocument();
Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
Style regular = doc.addStyle("regular", def);
Style s = doc.addStyle("bold", regular);
StyleConstants.setBold(s, true);
// dans la zone texte du bas, écriture du texte initial en mettant en gras les mots clés :
// on suppose que le texte initial ne commence pas et ne termine pas avec un mot clé
try {
doc.insertString(doc.getLength(), wordsBetweenKeyWords[0], doc.getStyle("regular"));
for (int i=0; i<keyWordsOccurrencesList.length; i++) {
doc.insertString(doc.getLength(), keyWordsOccurrencesList[i], doc.getStyle("bold"));
doc.insertString(doc.getLength(), wordsBetweenKeyWords[i+1], doc.getStyle("regular"));
}
} catch (BadLocationException ble) {
System.out.println("Couldn't insert text into text pane.");
ble.printStackTrace();
}
}
public static void main(String[] args) {
new Exemple064_StyledDocument();
}
} |
Partager