Code Samples Organiser

Java Snippet

Project - Code Samples Organiser

The purpose of this project was to create an index of keywords, phrases etc, based on my own snippets of sample code.

For example (probably from a newsgroup) the first time I came across a working example of FileWriter - I copied the code, retaining the class name "Assignment2", then, later, when I wanted to use/copy the FileWriter code into a project, I couldn't recall where the sample code was. Not a big deal, I just grabbed a couple of books and found the info I needed, but it would have been far simpler to go straight to Assignment2 for the info.

There are two sections to this program (determined by the radio buttons "Samples" and "Index").

1) Samples - to add a new listing, enter the filename into the textfield, then enter the code into the textarea and click "Add". To view what code is in a filename, just click on the filename in the JList and the code will be displayed in the textarea. If changes are made to the details in the textarea, "Add" will change to "Save", and there's a bit of error handling if you forget to save.

2) Indexes - this is the important part - for every sample code added to "Samples", dissect the code and add the kewords to the index. For example, I might add a listing to the index "FileWriter", and in the textarea "Assignment2" as the sample code filename containing a working example. If I then create a sample code file called FileReadWrite, I'd add FileReadWrite to the sample code section, change to indexes section, then click on FileWriter and add FileReadWrite underneath Assignment2. Also any import statements required for the keyword can be noted e.g. click on the index for FileWriter - "import java.io.*;" might be displayed in the textarea. Note: I would also have created, or added to, a FileReader index listing "FileReadWrite".

So, using the previous example, if I wanted to find a working example of FileWriter, I'd go to the index, click on FileWriter and see at least one code listing of "Assignment2", then click the "samples" radio button, locate and click on Assignment2 in the JList, and the working example of a FileWriter would be in the textarea.

The first character of any data in the textfield will automatically change to uppercase - required for sorting in the JList.

At this point there is no "delete" functionality.

 

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
 
class CodeSamplesOrganiser extends JFrame implements ActionListener, ItemListener,
                                   KeyListener, ListSelectionListener
{
  ArrayList indexes = new ArrayList();
  ArrayList samples = new ArrayList();
  JRadioButton rbIndex = new JRadioButton("Index");
  JRadioButton rbSample = new JRadioButton("Samples");
  DefaultListModel listModel = new DefaultListModel();
  JList list = new JList(listModel);
  JTextField tf = new JTextField(18);
  JButton addBtn = new JButton(" Add ");
  JButton clrBtn = new JButton("Clr");
  JTextArea ta = new JTextArea(23,30);
  JScrollPane sp1 = new JScrollPane(list);
  JScrollPane sp2 = new JScrollPane(ta);
  boolean unSaved = false;
  boolean fromRadioButtonChange = false;
  String currentDirectory;
  String currentListText = "";
  int currentListItem = 0;
 
  public CodeSamplesOrganiser()
  {
    super("Code Samples Organiser");
    getIndexSampleInfo();
    setSize(650,525);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container window = getContentPane();
    window.setLayout(new BorderLayout());
    rbIndex.addItemListener(this);
    rbSample.addItemListener(this);
    ButtonGroup bg = new ButtonGroup();
    bg.add(rbIndex);
    bg.add(rbSample);
    list.addListSelectionListener(this);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    sp1.setPreferredSize(new Dimension(255,450));
    addBtn.addActionListener(this);
    clrBtn.addActionListener(this);
    JPanel top = new JPanel();
    JPanel bottom = new JPanel(new FlowLayout());
    ta.addKeyListener(this);
    JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,sp1,sp2);
    split.setDividerLocation(200);
    split.setPreferredSize(new Dimension(650,450));
    split.resetToPreferredSizes();
    top.add(split);
    bottom.add(rbSample);
    bottom.add(rbIndex);
    JLabel lbl = new JLabel("                                                    ");
    bottom.add(lbl);
    bottom.add(tf);
    bottom.add(addBtn);
    bottom.add(clrBtn);
    window.add(top,BorderLayout.NORTH);
    window.add(bottom,BorderLayout.SOUTH);
    setLocation(200,100);
    setResizable(false);
    rbSample.setSelected(true);
    setVisible(true);
    File indexDir = new File("Indexes");
    if(!indexDir.exists()) indexDir.mkdir();
    File samplesDir = new File("Samples");
    if(!samplesDir.exists()) samplesDir.mkdir();
    fromRadioButtonChange = false;
  }
 
  private void getIndexSampleInfo()    //load index and sample code 'headers' into arraylist
  {
    try
    {
      File indexFile = new File("Indexes.txt");
      if(indexFile.exists())
      {
        BufferedReader br = new BufferedReader(new FileReader("Indexes.txt"));
        String line = "";
        while ((line = br.readLine()) != null)
       {
         indexes.add(line);
        }
        br.close();
      }
    }
    catch(FileNotFoundException fnfe)
    {
      JOptionPane.showMessageDialog(null,"Indexes file not found");
    }
    catch(IOException ioe)
    {
      JOptionPane.showMessageDialog(null,"Unexpected error - terminating");
      System.exit(0);
    }
 
    try
    {
      File samplesFile = new File("Samples.txt");
      if(samplesFile.exists())
      {
        BufferedReader br = new BufferedReader(new FileReader("Samples.txt"));
        String line = "";
        while ((line = br.readLine()) != null)
       {
         samples.add(line);
        }
        br.close();
      }
    }
    catch(FileNotFoundException fnfe)
    {
      JOptionPane.showMessageDialog(null,"Samples file not found");
    }
    catch(IOException ioe)
    {
      JOptionPane.showMessageDialog(null,"Unexpected error - terminating");
      System.exit(0);
    }
  }
 
  private void addIndexesToList()              //add index 'headers' to JList
  {
    listModel.clear();
    Collections.sort(indexes);
    for(int i = 0; i < indexes.size(); i++)
    {
      listModel.addElement(indexes.get(i));
    }
  }
 
  private void addSamplesToList()              //add sample code 'headers' to JList
  {
    listModel.clear();
    Collections.sort(samples);
    for(int i = 0; i < samples.size(); i++)
    {
      listModel.addElement(samples.get(i));
    }
  }
 
  public void valueChanged(ListSelectionEvent lse)             //JLIST_CLICK()
  {
    if(!fromRadioButtonChange)
    {
      if(unSaved) checkUnsaved();
      if(list.getSelectedValue() != null){
        currentListItem = list.getSelectedIndex();
        currentListText = list.getSelectedValue().toString();
        try
        {
          BufferedReader br = new BufferedReader(new FileReader(
                       currentDirectory+"\\"+list.getSelectedValue()+".txt"));
          String line = "";
          String fileData = "";
          while ((line = br.readLine()) != null)
         {
           fileData += line + "\n";
          }
          br.close();
          ta.setText(fileData);
        }
        catch(IOException ioe)
        {
          JOptionPane.showMessageDialog(null,"Unexpected error - terminating");
          System.exit(0);
        }
      }
    }
    fromRadioButtonChange = false;
    ta.setCaretPosition(0);
  }
 
  public void itemStateChanged(ItemEvent ie)        //JRADIOBUTTON_CHANGE()
  {
    if(unSaved) checkUnsaved();
    if(rbIndex.isSelected())
    {
      addIndexesToList();
      currentDirectory = "Indexes";
    }
    else if(rbSample.isSelected())
    {
      addSamplesToList();
      currentDirectory = "Samples";
    }
    fromRadioButtonChange = true;
    clearText();
  }
 
  private void clearText()                                //CLEAR TEXT
  {
    if(unSaved) checkUnsaved();
    ta.setText("");
    tf.setText("");
    addBtn.setText(" Add ");
    list.clearSelection();
  }
 
  public void actionPerformed(ActionEvent ae)             //JBUTTON_CLICK()
  {
    if(ae.getSource() == clrBtn) clearText();
    else
    {
      if(addBtn.getText().equals(" Add "))
      {
        if(!tf.getText().equals(""))
        {
          tf.setText(tf.getText().substring(0,1).toUpperCase()+tf.getText().substring(1));
          if(currentDirectory.equals("Indexes"))
          {
            if(recordExists(indexes,tf.getText()))
            {
              JOptionPane.showMessageDialog(null,"Record already exists, nothing added");
              return;
            }
          }
          else if(recordExists(samples,tf.getText()))
          {
            JOptionPane.showMessageDialog(null,"Record already exists, nothing added");
            return;
          }
          int save = 0;
          if(ta.getText().equals(""))
          {
            save = JOptionPane.showConfirmDialog(null,"File data empty. Continue?");
          }
          if(save == 0)
          {
            saveFile(currentDirectory+".txt",true);
            saveFile(currentDirectory+"\\"+ tf.getText()+".txt",false);
            list.setSelectedValue(tf.getText(),true);
            list.ensureIndexIsVisible(list.getSelectedIndex());
            tf.setText("");
          }
        }
        else
        {
          JOptionPane.showMessageDialog(null,"Text field empty - unable to add");
        }
      }
      else  //button text = "Save"
      {
        int save = 0;
        if(ta.getText().equals(""))
        {
          save = JOptionPane.showConfirmDialog(null,"File data empty. Continue?");
        }
        if(save == 0)
        {
          saveFile(currentDirectory+"\\"+ list.getSelectedValue()+".txt",false);
        }
      }
      unSaved = false;
      addBtn.setText(" Add ");
    }
  }
 
  private boolean recordExists(ArrayList al, String str)
  {
    for(int i = 0; i < al.size(); i++)
    {
      if(al.get(i).toString().toLowerCase().equals(str.toLowerCase())) return true;
    }
    return false;
  }
 
  private void checkUnsaved()                             //CHECK TO SAVE UNSAVED DATA
  {
    int yesNo = JOptionPane.showConfirmDialog(null, "Save changes to "+
                    currentListText+ " ?");
    if(yesNo == 0)
    {
      saveFile(currentDirectory+"\\"+currentListText+".txt",false);
    }
    unSaved = false;
    addBtn.setText(" Add ");
  }
 
  private void saveFile(String filePath, boolean appendFlag)      //SAVE
  {
    try
    {
      FileWriter fw = new FileWriter(filePath,appendFlag);
      if(appendFlag)                                     //adding a header detail
      {
        fw.write(tf.getText() + "\r\n");
        if(currentDirectory.equals("Indexes"))
        {
          indexes.add(tf.getText());
          addIndexesToList();
        }
        else
        {
          samples.add(tf.getText());
          addSamplesToList();
        }
      }
      else                                               //adding data to a header file
      {
        fw.write(ta.getText().replaceAll("\n","\r\n"));
      }
      fw.close();
      unSaved = false;
    }
    catch(IOException ioe)
    {
      int yesNo = JOptionPane.showConfirmDialog(null,
               "Error writing to "+ filePath+"\nContinue?");
      if(yesNo != 0) System.exit(0);
    }
  }
 
  public void keyPressed(KeyEvent ke)                           //SET UNSAVED FLAG
  {
    if(tf.getText().equals("") && list.getSelectedIndex() >= 0)
    {
      unSaved = true;
      addBtn.setText("Save");
    }
  }
 
  public void keyReleased(KeyEvent ke){};
  public void keyTyped(KeyEvent ke){};
  public static void main(String args[]){new CodeSamplesOrganiser();}
}


back    top    main page    vb snippets page      java snippets page     vbscript snippets page   email    Page last modified