View Javadoc

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