Tips Organiser

Java Snippet

Project - Tips Organiser


The purpose of this project was to organise a whole bunch of tips/snippets obtained from everywhere. Ever looked at a newsgroup, or the Sun Forum etc, and someone's posted a neat way of doing something, so you print it out to keep and read later. Ever bookmarked an interesting article in a magazine, or an interesting bit of code (not full working code)  in a book, only to find you have hundreds of these tips, or bookmarks sticking out, so you can't find anything. Well, not without a great deal of effort.

This project is very similar to the Code Samples Organiser, particularly entering/retrieving data, although this is a bit more complex.

For example you may have printed out a handy tip using FileWriter. You'd enter FileWriter into the textfield, then click the button with T0001 displayed. T0001 will appear in the textarea and you can add any additional comments, before clicking "Add". You'd then write on the top of the tip document T0001, then file the document (T0002 would then go on top of T0001, T003 on top of T002 etc). After adding the T0001 to the textarea, the button label changes to T0002.

The only way to record the tip numbers in the "TipsIndex" is (a) have data in the textfield (for a new entry), then click the "T" button or (b) click on an item in the JList, so there's data in the textarea (this way you can have multiple tips in a single subject), then click the "T" button . This is the only way to record the "T" number and to increment it.

For  books and article tips/snippets, just make a reference to the book/magazine and page number. No need to add a "T" number. One idea could be to add an entry called "Books" then list each book in your library and give it a short code
e.g.
"PJP" - "Professional Java Programming - Brett Spell"
"JPR" - "Java Programmer's Reference - Grant Palmer"

so, a listing for FileWriter may include JPR p342.

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

Change the language headers to whatever suits - the directories will automatically be created.. "TipsIndex" is the only hard-coded header, so it is the only one necessary to be retained.

 

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
 
class TipsOrganiser extends JFrame implements ActionListener, ItemListener,
                                   KeyListener, ListSelectionListener
{
  String languages[] = {"Java","VB","VBscript","C","C++","Excel",
                        "Outlook","Windows","misc","TipsIndex"};
  ArrayList headers[] = new ArrayList[languages.length];
  JRadioButton rb[] = new JRadioButton[languages.length];
  DefaultListModel listModel = new DefaultListModel();
  String nextTipID = "T0001";
  JList list = new JList(listModel);
  JTextField tf = new JTextField(18);
  JButton addBtn = new JButton(" Add ");
  JButton clrBtn = new JButton("Clr");
  JButton tipBtn;
  JTextArea ta = new JTextArea(23,30);
  JScrollPane sp1 = new JScrollPane(list);
  JScrollPane sp2 = new JScrollPane(ta);
  boolean unSaved = false;
  boolean fromRadioButtonChange = false;
  boolean fromClearBtn = true;
  boolean indexOnly = false;
  String currentDirectory;
  int currDirElement = 0;
  String currentListText = "";
  int currentListItem = 0;
  int nextTipNum = 1;
 
  public TipsOrganiser()
  {
    super("Tips Organiser");
    setSize(650,525);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container window = getContentPane();
    window.setLayout(new BorderLayout());
    JPanel top = new JPanel(new FlowLayout());
    ButtonGroup bg = new ButtonGroup();
    for(int i = 0; i < rb.length; i++)
    {
      rb[i] = new JRadioButton(languages[i]);
      rb[i].addItemListener(this);
      bg.add(rb[i]);
      top.add(rb[i]);
      headers[i] = new ArrayList();
    }
    getArrayListHeadersInfo();
    getSetNextTipID();
    list.addListSelectionListener(this);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    sp1.setPreferredSize(new Dimension(255,450));
    addBtn.addActionListener(this);
    clrBtn.addActionListener(this);
    tipBtn = new JButton(nextTipID);
    tipBtn.addActionListener(this);
    JPanel mid = 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,400));
    split.resetToPreferredSizes();
    mid.add(split);
    bottom.add(tf);
    bottom.add(addBtn);
    bottom.add(clrBtn);
    bottom.add(tipBtn);
    window.add(top,BorderLayout.NORTH);
    window.add(mid,BorderLayout.CENTER);
    window.add(bottom,BorderLayout.SOUTH);
    setLocation(200,100);
    setResizable(false);
    rb[0].setSelected(true);
    setVisible(true);
    checkDirectories();
    fromRadioButtonChange = false;
  }
 
  private void checkDirectories()                   //CHECK DIRECTORIES EXIST
  {
    for(int i = 0; i < languages.length; i++)
    {
      File dir = new File(languages[i]);
      if(!dir.exists()) dir.mkdir();
    }
  }
 
  private void getArrayListHeadersInfo()            //LOAD HEADERS INFO TO ARRAYLISTS
  {
    for(int i = 0; i < headers.length; i++)
    {
      try
      {
        File indexFile = new File(languages[i]+".txt");
        if(indexFile.exists())
        {
          BufferedReader br = new BufferedReader(new FileReader(languages[i]+".txt"));
          String line = "";
          while ((line = br.readLine()) != null)
         {
           headers[i].add(line);
          }
          br.close();
        }
      }
      catch(FileNotFoundException fnfe)
      {
        JOptionPane.showMessageDialog(null,""+languages[i]+" file not found");
      }
      catch(IOException ioe)
      {
        JOptionPane.showMessageDialog(null,"Unexpected error - terminating");
        System.exit(0);
      }
    }
  }
 
  private void getSetNextTipID()                 //READ IN, SET NEXT TIP ID
  {
    try
    {
      File nextTipNumFile = new File("NextTipNum.txt");
      if(nextTipNumFile.exists())
      {
        BufferedReader br = new BufferedReader(new FileReader("NextTipNum.txt"));
        nextTipNum = Integer.parseInt(br.readLine());
        br.close();
        String nextNum = "000"+nextTipNum;
        nextTipID = "T"+nextNum.substring(nextNum.length()-4);
      }
    }
    catch(FileNotFoundException fnfe)
    {
      JOptionPane.showMessageDialog(null,"NextTipNum.txt - file not found");
 
    }
    catch(IOException ioe)
    {
      JOptionPane.showMessageDialog(null,"Unexpected error - terminating");
      System.exit(0);
    }
    catch(Exception e)
    {
      JOptionPane.showMessageDialog(null,"error parsing next tip number from file");
    }
  }
 
  private void addHeadersToList(int num)            //ADD SELECTED HEADER INFO TO JLIST
  {
    listModel.clear();
    Collections.sort(headers[num]);
    for(int i = 0; i < headers[num].size(); i++)
    {
      listModel.addElement(headers[num].get(i));
    }
  }
 
  public void valueChanged(ListSelectionEvent lse)   //JLIST_CLICK()
  {
    if(!fromRadioButtonChange && !indexOnly)
    {
      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)     //CHANGE SELECTED "LANGUAGE"
  {
    if(unSaved) checkUnsaved();
    indexOnly = false;
    for(int i = 0; i < rb.length; i++)
    {
      if(rb[i].isSelected())
      {
        addHeadersToList(i);
        currentDirectory = languages[i];
        currDirElement = i;
        fromRadioButtonChange = true;
        clearText();
        break;
      }
    }
    if(currentDirectory.equals("TipsIndex")) indexOnly = true;
  }
 
  private void clearText()                      //CLEAR TEXT FIELD/AREA
  {
    if(unSaved) checkUnsaved();
    fromClearBtn = true;
    ta.setText("");
    tf.setText("");
    addBtn.setText(" Add ");
    list.clearSelection();
    fromClearBtn = false;
  }
 
  public void actionPerformed(ActionEvent ae)     //JBUTTON_CLICK()
  {
    if(ae.getSource() == clrBtn) clearText();
    else if(ae.getSource() == tipBtn) saveTipIDs();
    else
    {
      if(addBtn.getText().equals(" Add "))
      {
        if(!tf.getText().equals(""))
        {
          tf.setText(tf.getText().substring(0,1).toUpperCase()+tf.getText().substring(1));
          if(recordExists(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);
        }
      }
    }
  }
 
  private boolean recordExists(String str)       //CHECK IF RECORD EXISTS
  {
    for(int i = 0; i < headers[currDirElement].size(); i++)
    {
      if(headers[currDirElement].get(i).toString().toLowerCase().equals(str.toLowerCase()))
      {
        return true;
      }
    }
    return false;
  }
 
  private void checkUnsaved()                     //CHECK IF CHANGED DATA IS TO BE SAVED
  {
    int yesNo = JOptionPane.showConfirmDialog(null, "Save changes to "+
                    currentListText+ " ?");
    if(yesNo == 0)
    {
      saveFile(currentDirectory+"\\"+currentListText+".txt",false);
    }
    unSaved = false;
    addBtn.setText(" Add ");
  }
 
  private void saveTipIDs()                      //SAVE TIP INDEX AND IDs
  {
    String saveData = "";
    try
    {
      if(!ta.getText().equals(""))
      {
        saveData = nextTipID+" | "+currentDirectory+" | "+list.getSelectedValue();
        ta.setText(ta.getText()+nextTipID+" ");
      }
      else if(!tf.getText().equals(""))
      {
        saveData = nextTipID+" | "+currentDirectory+" | "+tf.getText();
        ta.setText(nextTipID+" ");
      }
      else
      {
        JOptionPane.showMessageDialog(null,"Both Textfield and TextArea empty, new tip unsuccessful");
        return;
      }
 
      for(int i = 0; i < languages.length; i++)
      {
        if(languages[i].equals("TipsIndex"))
        {
          headers[i].add(saveData);
          break;
        }
      }
      FileWriter fw = new FileWriter("TipsIndex.txt",true);
      fw.write(saveData+"\r\n");
      fw.close();
 
      nextTipNum++;
      String nextNum = "000"+nextTipNum;
      nextTipID = "T"+nextNum.substring(nextNum.length()-4);
 
      fw = new FileWriter("NextTipNum.txt");
      fw.write(""+nextTipNum);
      fw.close();
      tipBtn.setText(nextTipID);
    }
    catch(IOException ioe)
    {
      int yesNo = JOptionPane.showConfirmDialog(null,
               "Error writing to Tip/ID files\nContinue?");
      if(yesNo != 0) System.exit(0);
    }
  }
 
  private void saveFile(String filePath, boolean appendFlag)    //SAVE FILE
  {
    try
    {
      FileWriter fw = new FileWriter(filePath,appendFlag);
      if(appendFlag) //adding a header detail
      {
        fw.write(tf.getText() + "\r\n");
        for(int i = 0; i < languages.length; i++)
        {
          if(currentDirectory.equals(languages[i]))
          {
            headers[i].add(tf.getText());
            addHeadersToList(i);
            break;
          }
        }
      }
      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)                 //UNSAVED
  {
    if(!fromClearBtn && 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 TipsOrganiser();}
}


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