View Javadoc

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