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

    Default buttons not working

    hello
    when i save my items and load them non of my buttons work i cant delete add or sort items. before i save they work after i load nothing works can someone point out the problem please thanks

    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");
        
        
        JTable tab = new JTable();
        
    // The DefaultTableModel will allow the contents of the
    // JTable to be manipulated.
        DefaultTableModel tabMod = new DefaultTableModel();
    
        
    
        private Component fr;
    
        private String SF;
    
        
        JFileChooser SaveFileAs = new JFileChooser();  
        JFileChooser LoadFile = 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
    
    			saveRecords();
    		}
    
                    
            }
            });
             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
    
    			LoadRecords();
    		}
    
                  
            }
            });
            
            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();
       
        }
        
    // 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 saveRecords (){
            if(SaveFileAs.showSaveDialog((Component) fr) != JFileChooser.APPROVE_OPTION)
    		{
    			return;
    		}
    
    		try
    		{
    			File f = SaveFileAs.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 (IOException e){
    		System.out.println("tablesave i/o error: " +
                                    e.getMessage());
                        }
        }
    
    
    
    
            public void LoadRecords (){
           if(LoadFile.showOpenDialog((Component) fr) != JFileChooser.APPROVE_OPTION)
                      {
    
            }
    
             try
                {
                File f = LoadFile.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) {
               System.out.println("tableload i/o error: " +
                                    e.getMessage());
                        }
        }
           
       
        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
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    It looks like you've come a long way since you've started this program of yours, and so I think that you deserve kudos for your significant progression and obvious hard work. I've gone through some of your code and have a few suggestions:

    1. First and foremost, your main problem as I see it is that you're trying to serialize the entire table model en bloc. Don't do this as it is a gross over-simplification of what can or should be done. I believe that data members of your model may not be fully serializable and that this may be the main cause your problems. You may be better off if you serialize just the data held by the model, such as the Vectors held in your DefaultTableModel, and nothing more. Then when you write out, you write out the Vectors, and when you read in, you don't create a new table model, but rather empty out the data from the current model, and then insert rows from the Vectors read in.

    2. You have a duplication of data with your arraylist. You can just use your table model as the data repository and skip using the arraylist. The only thing that you have yet to implement is sorting, and there are ways of sorting table rows based on column contents which you can find out about here: table sorting.

    3. Make all class fields private unless there's a definite (and decent) reason not to.

    4. When you use anonymous action listeners, such as the ones added to btnSave and btnLoad, there's no need to check that the source found from e.getSource() == the button of interest. This listener is being added to one and only one button and will only get activated if that one button is pressed. So the actionPerformed methods for these two button's listeners can be one line each, i.e., instead of
    Java Code:
        btnSave.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            JComponent b = (JComponent) event.getSource();
            if (b == btnSave) { 
              saveRecords();
            }
          }
        });
    do
    Java Code:
        btnSave.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            saveRecords();
          }
        });
    5. you seem to be trying to add btnSave and btnLoad to 2 JPanels here:
    Java Code:
        panAdd.add(btnSave); 
        panDelSort.add(btnSave);
        panAdd.add(btnLoad); 
        panDelSort.add(btnLoad);
    Only add a component to one container.

    6. Are you sure that you want to append ".txt" to the end of any file name? These are most definitely not text files, and if you save / load / save / load data, you'll eventually end up with a file name looking like myFile.txt.txt.txt.txt

    7. If you nest streams, you only need to close the outer-most stream. This close method call should be in the finally block of your try/catch/finally blocks. Check that the stream is not null before closing.

    8. edit: one more issue is your deleting of rows. I'm concerned that your use of a forward for loop while deleting table rows (or items in an arraylist) will cause problems (especially when deleting multiple rows or items) as when you delete a vector or arraylist item, the indexes of the collection will change. You may be better off iterating backwards through the table model or arraylist and deleting this way.

    That's about all I could do. HTH and best of luck!
    Last edited by Fubarable; 08-15-2009 at 09:30 PM.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Not sure if this is still an issue for you, but I've found this problem interesting and in further searching for different solutions, I found another interesting link here:
    Swing - Serializable DefaultTableModel

    In particular, look at reply 2 by camickr where he explains one of the reasons for a table model not to be serialized, and its solution:
    Java Code:
    tab.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);

Similar Threads

  1. Where To Get Pop Up Buttons
    By hitmen in forum AWT / Swing
    Replies: 7
    Last Post: 03-26-2009, 04:05 AM
  2. Buttons and TextFields
    By Xystus777 in forum New To Java
    Replies: 27
    Last Post: 03-17-2009, 01:26 AM
  3. Demonstration of Buttons
    By Java Tip in forum SWT
    Replies: 0
    Last Post: 07-11-2008, 04:44 PM
  4. How to use SWT Buttons
    By Java Tip in forum SWT
    Replies: 0
    Last Post: 07-11-2008, 04:44 PM
  5. Replies: 8
    Last Post: 05-28-2008, 07:00 AM

Posting Permissions

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