Results 1 to 3 of 3
  1. #1
    daud is offline Member
    Join Date
    Aug 2009
    Posts
    7
    Rep Power
    0

    Default improving my code

    how can i improve my code, is there a better way to store records, also how do i add new records and save the new changes made to existing records any tutorials? any other improvements? thanks in advance.

    Java Code:
    package amended;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInput;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutput;
    import java.io.ObjectOutputStream;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    
    // This program allows a list of itemss to be maintained i.e.
    // added, deleted and sorted.  The items are displayed in
    // a JTable and also maintained in an ArrayList.
    
    
    
    class Item implements Comparable {
        private int value;
        private String itemname;
        private String notes;
        private String filename;
        private String choice;
        
        public Item(int v, String i, String n, String f, String c) {
            value = v;
            itemname = i;
            notes = n;
            filename = f;
            choice = c;
        }
        public Item() {
           this(0, "", "", "", "");
        }
        public int getValue() {
            return value;
        }
        public String getItemName() {
            return itemname;
        }
         public String getNotes() {
            return notes;
        }
          public String getFileName() {
            return filename;
        }
           public String getChoice() {
            return choice;
        }
    // compareTo() allows Item instances in a container
    // (e.g. an ArrayList) to be sorted by Collections.sort().
        
    // It can only sort things in one order (e.g. ascending order of
    // name).  Need to investigate the use of Comparator objects to
    // allow different sort orders to be defined.
        
        public int compareTo(Object o) {
            Item temp = (Item) o;
            
    // Strings already implement compareTo() so just use that
            return (itemname.compareTo(temp.itemname));
        }
    }
    public class MyItems extends JFrame implements
           java.io.Serializable {
        
    // A container for the Item instances
        ArrayList items = new ArrayList();
        
    // GUI bits and bobs
        JPanel panInput = new JPanel(new GridLayout(2,1)),
                panAdd = new JPanel(),
                panDelSort = new JPanel();
        String[] choiceStrings = { "New", "used"};
    
        JTextField txtItemName = new JTextField(030);            
            JTextField txtValue = new JTextField(04);
                JTextField txtNotes = new JTextField(040);
                JTextField txtFileName = new JTextField(010);
                JComboBox choiceList = new JComboBox(choiceStrings);
    
        JButton btnAdd = new JButton("Add"),            
                btnDelete = new JButton("Delete"),
                btnSort = new JButton("Sort Products"),
                btnSave = new JButton("Save"),
                btnLoad = new JButton("Load");
        private Object fr;
        
        JTable tab = new JTable();
        
    // The DefaultTableModel will allow the contents of the
    // JTable to be manipulated.
        DefaultTableModel tabMod = new DefaultTableModel();
    
        private String SF;
        
        JFileChooser FileChooser1 = new JFileChooser();  
        JFileChooser FileChooser2 = new JFileChooser();  
    
        
        public MyItems() {
            super("Item list");
            tab.setModel(tabMod);
            tabMod.addColumn("Item Name");
            tabMod.addColumn("Notes on item");
            tabMod.addColumn("Item value");
            tabMod.addColumn("new/second hand item");
            tabMod.addColumn("Image file");
            
            btnAdd.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    addItem();
                }
            });
             btnSave.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    JComponent b = (JComponent)event.getSource();
    
                    if(b == btnSave)
    		{
    			//This is the function in which the exception is thrown
    
    			tablesave();
    		}
    
                    amendItem();
            }
            });
             btnLoad.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    JComponent b = (JComponent)event.getSource();
    
                    if(b == btnLoad)
    		{
    			//This is the function in which the exception is thrown
    
    			tableload();
    		}
    
                    amendItem();
            }
            });
            btnDelete.setToolTipText("Select the records to delete first");
            btnDelete.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    deleteItem();
                }
            });
            btnSort.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    sortItems();
                }
            });
            
           
            panAdd.add(new JLabel("Item Name:"));
            panAdd.add(txtItemName);
            
            panAdd.add(new JLabel("Item Notes:"));
            panAdd.add(txtNotes);
            
            panAdd.add(new JLabel("Price"));
            panAdd.add(txtValue);
            
            panAdd.add(new JLabel("File Name"));
            panAdd.add(txtFileName);
            
            panAdd.add(new JLabel("New/second hand"));
            panAdd.add(choiceList);
            
            panAdd.add(btnAdd);
            panDelSort.add(btnDelete);
            
            panAdd.add(btnSave);
            panDelSort.add(btnSave);
            panAdd.add(btnLoad);
            panDelSort.add(btnLoad);
            panDelSort.add(btnSort);
            panInput.add(panAdd);
            panInput.add(panDelSort);
            getContentPane().add(panInput, BorderLayout.PAGE_END);
            getContentPane().add(new JScrollPane(tab));
            
        }
    // Delete a product from the ArrayList and from the JTable
        public void deleteItem() {
            int [] rows = tab.getSelectedRows();
            for (int i = 0; i < rows.length; i++) {
                tabMod.removeRow(rows[i] - i); // delete from JTable
                items.remove(rows[i] - i); // delete from ArrayList
            }
        }
        
    // Sort the items in the ArrayList and then
    // reload them into the JTable in the sorted order
        
        public void sortItems() {
            Collections.sort(items); // sorts into name order
            loadItemsIntoTable();
        }
        public void amendItem() {
            int [] rows = tab.getSelectedRows();
            for (int i = 0; i < rows.length; i++) {
                tabMod.removeRow(rows[i] - i); // delete from JTable
                items.remove(rows[i] - i); // delete from ArrayList
            }
        }
        
    // Add a new items to the ArrayList and the JTable
        public void addItem() {
            String [] row = new String [5];
            Item newIte = new Item
                    (Integer.parseInt(txtValue.getText()), 
                    txtItemName.getText(), txtNotes.getText(), (String) choiceList.getSelectedItem (), txtFileName.getText());
            
            items.add(newIte); // add to the ArrayList
            row[0] = newIte.getItemName();
            row[1] = newIte.getNotes();
            row[2] = Integer.toString(newIte.getValue());
            row[3] = newIte.getFileName();
            row[4] = newIte.getChoice();
            tabMod.addRow(row); // add to the JTable
        }
      
            public void tablesave ()
    {
    
    if(FileChooser1.showSaveDialog((Component) fr) != JFileChooser.APPROVE_OPTION)
    		{
    			return;
    		}
    
    		try
    		{
    			File f = FileChooser1.getSelectedFile();
    			SF = (f.toString() + ".txt");
    			FileOutputStream fStream = new FileOutputStream(SF);
    			ObjectOutput stream = new ObjectOutputStream(fStream);
    
    			//The below two command lines saves the table model and table column data
    			//as an object using the user specified file name
    			stream.writeObject(tab.getModel());
    			stream.writeObject(tab.getColumnModel());
    			stream.flush();
    			stream.close();
    			fStream.close();
    		}
    
    		catch (Exception e)
    		{
    			
    		}
    
    	}
    
    
    
    
    public void tableload ()
    {
    
    if(FileChooser2.showOpenDialog((Component) fr) != JFileChooser.APPROVE_OPTION)
    {
    
    }
    
    try
    {
    File f = FileChooser2.getSelectedFile();
    FileInputStream fStream = new FileInputStream(f);
    ObjectInput stream = new ObjectInputStream(fStream);
    Object obj = stream.readObject();
    if(obj instanceof TableModel)
    {
    tab.setModel((TableModel) obj);
    }
    stream.close();
    fStream.close();
    }
    
    catch (Exception e)
    {
    
    }
            }
           
       
        public void loadItemsIntoTable() {
            tabMod.setRowCount(0);
            
            String [] row = new String [5];
            for (Iterator i = items.iterator(); i.hasNext();) {
                Item temp = (Item) i.next();
                row[0] = temp.getItemName();
                row[1] = temp.getNotes();
                row[2] = Integer.toString(temp.getValue());
                row[3] = temp.getItemName();
                row[4] = temp.getChoice();
                tabMod.addRow(row);
            }
        }
        public static void main(String [] a){
            MyItems me = new MyItems();
            me.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0) ;
                }
            });
            me.pack();
            me.setVisible(true);
        }
    }

  2. #2
    dlorde is offline Senior Member
    Join Date
    Jun 2008
    Posts
    339
    Rep Power
    7

    Default

    In general, think about consistent indentation, adherence to the Java naming conventions, use of generics - particularly with collections, and catching specific exceptions and handling them - you should never leave an empty 'catch' block - if you are deliberately not handling an exception, either log a message or put in a comment explaining why. When you use IO classes, e.g. streams, declare your IO class variables before the 'try' block, initialise them inside the 'try' block, and close them in a 'finally' block - handling any exceptions that can be thrown. With wrapped streams, you only need to close the outermost stream wrapper, and it will close the inner ones.

    Try to give all your variables, methods, and method parameters meaningful names.

    It's generally considered poor practice to declare and initialise multiple objects in a single statement - consider declaring & initialising each separately.

    More specifically, you should consider using a TableRowSorter instead of sorting and replacing the table model data. The table model is where the data should be stored - there's no reason to keep a separate list. If you want the data stored in a different form to that provided by DefaultTableModel, provide your own by overriding AbstractTableModel.

    Do something with Object 'fr' - if it's used as a Component, declare it as such and initialise it.
    Last edited by dlorde; 08-14-2009 at 12:42 PM.

  3. #3
    emceenugget is offline Senior Member
    Join Date
    Sep 2008
    Posts
    564
    Rep Power
    7

    Default

    as far as how to store records, there are always other ways to do it, but they get more and more complex, and also depend on operations you want to perform on the records. look up data structures. i'd recommend checking out a binary search tree first, then a self-balancing bst before even attempting the more complex structures.

    you can also use the 'hashmap' class...
    Last edited by emceenugget; 08-14-2009 at 10:47 PM. Reason: added another note

Similar Threads

  1. Convert java code to midlet code
    By coldvoice05 in forum New To Java
    Replies: 1
    Last Post: 08-12-2009, 12:14 PM
  2. Convert java code to midlet code
    By coldvoice05 in forum Advanced Java
    Replies: 1
    Last Post: 08-09-2009, 02:21 PM
  3. Why doesn't this code accept my code?
    By PeterFeng in forum New To Java
    Replies: 5
    Last Post: 02-03-2009, 02:39 PM
  4. Any method for improving of java thread
    By code453 in forum Java Applets
    Replies: 0
    Last Post: 12-20-2007, 09:29 AM
  5. Replies: 1
    Last Post: 04-26-2007, 04:52 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •