KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > pmd > util > designer > CodeEditorTextPane


1 package net.sourceforge.pmd.util.designer;
2
3 import net.sourceforge.pmd.util.LineGetter;
4
5 import javax.swing.*;
6 import java.awt.Dimension JavaDoc;
7 import java.awt.event.ActionEvent JavaDoc;
8 import java.awt.event.ActionListener JavaDoc;
9 import java.io.BufferedReader JavaDoc;
10 import java.io.File JavaDoc;
11 import java.io.FileReader JavaDoc;
12 import java.io.FileWriter JavaDoc;
13 import java.io.IOException JavaDoc;
14 import java.util.StringTokenizer JavaDoc;
15
16 public class CodeEditorTextPane extends JTextPane implements LineGetter, ActionListener JavaDoc {
17
18     private static final String JavaDoc SETTINGS_FILE_NAME = System.getProperty("user.home") + System.getProperty("file.separator") + ".pmd_designer";
19     private static final String JavaDoc LINE_SEPARATOR = System.getProperty("line.separator");
20
21     public CodeEditorTextPane() {
22         setPreferredSize(new Dimension JavaDoc(400, 200));
23         setText(loadCode());
24     }
25
26     public String JavaDoc getLine(int number) {
27         int count = 1;
28         for (StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(getText(), "\n"); st.hasMoreTokens();) {
29             String JavaDoc tok = st.nextToken();
30             if (count == number) {
31                 return tok;
32             }
33             count++;
34         }
35         throw new RuntimeException JavaDoc("Line number " + number + " not found");
36     }
37
38     public void actionPerformed(ActionEvent JavaDoc ae) {
39         FileWriter JavaDoc fw = null;
40         try {
41             fw = new FileWriter JavaDoc(new File JavaDoc(SETTINGS_FILE_NAME));
42             fw.write(getText());
43         } catch (IOException JavaDoc ioe) {
44         } finally {
45             try {
46                 if (fw != null)
47                     fw.close();
48             } catch (IOException JavaDoc ioe) {
49                 ioe.printStackTrace();
50             }
51         }
52     }
53
54     private String JavaDoc loadCode() {
55         BufferedReader JavaDoc br = null;
56         try {
57             br = new BufferedReader JavaDoc(new FileReader JavaDoc(new File JavaDoc(SETTINGS_FILE_NAME)));
58             StringBuffer JavaDoc text = new StringBuffer JavaDoc();
59             String JavaDoc hold;
60             while ((hold = br.readLine()) != null) {
61                 text.append(hold).append(LINE_SEPARATOR);
62             }
63             return text.toString();
64         } catch (IOException JavaDoc e) {
65             e.printStackTrace();
66             return "";
67         } finally {
68             try {
69                 if (br != null) br.close();
70             } catch (IOException JavaDoc e) {
71                 e.printStackTrace();
72             }
73         }
74     }
75 }
76
Popular Tags