CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 23
  1. #1
    Join Date
    Oct 2006
    Posts
    24

    Need Button advice

    I have this code w/in my program:

    Code:
        btnFirst.addActionListener(new ActionListener(){
    	      public void actionPerformed(ActionEvent ae){
            DVD dvd = (DVD)dvds.get(list.getSelectedIndex(0));
    	        			//int index = list.getSelectedIndex();
    	        			//if (index=0) index = dvds.size();
    	        			//int index = (list.getSelectedIndex(0));
    	        			list.setSelectedIndex(index);
         }
       });
    I've tried several variations so that the button is grabbing the first DVD in my array which of course is "0" but I don't know where to put the zero, I have stuff commented out because I copied a button I have for "next".

    Thanks!

  2. #2
    Join Date
    Apr 2001
    Location
    South Africa, Jo'burg
    Posts
    680

    Re: Need Button advice

    Hi,

    Firstly without all your code it is hard to help, I don't know what type the variable dvds is? You say it is an array but it looks more like a List of some type. If you want to just get the first entry then doing it like this should work:

    Code:
    DVD dvd = (DVD)dvds.get(0);
    Although I'm not sure why you would only want to get the first entry each time you click the button

    It seems that what you had was correct, it looks like you have a JList that is populated with data from your List/Array. So then you would be able to get the exact entry that is selected in the JList by saying:
    Code:
    DVD dvd = (DVD)dvds.get(list.getSelectedIndex());
    Which is what you had and seems like the most logical thing to do.

    Hope This Helps
    Byron Tymvios

    Please use [ CODE ] and [/ CODE ] tags when posting code! See THIS on how to use code tags.

  3. #3
    Join Date
    Oct 2006
    Posts
    24

    Re: Need Button advice

    That helped ALOT!

    Can you help me make a "Save" Button work?

    If I have a list:

    Code:
        dvds.add(new DVD("Batman","Action","9583",17.00,7,5.95,124.95));
        dvds.add(new DVD("Cinderella","Family","2734",19.00,8,7.60,159.60));
        dvds.add(new DVD("Friends","Comedy","9824",18.00,5,4.50,94.50));
        dvds.add(new DVD("Lost","Drama","9382",25.00,2,2.50,52.50));
        dvds.add(new DVD("OfficeSpace","Comedy","9821",20.00,5,5.00,105.00));
        dvds.add(new DVD("StarWars","Action","1245",10.00,5,5.00,55.00));
        dvds.add(new DVD("Superman","Action","3652",20.00,10,10.00,210.00));
    How can I have a save button save this to a file that a load button can load it later?

    THANK YOU!

  4. #4
    Join Date
    Apr 2001
    Location
    South Africa, Jo'burg
    Posts
    680

    Re: Need Button advice

    Well firstly you need to decide how you are going to save it to a file, are you going to serialize the objects directly to the file or are you going to take the approach of writing the text out to a file and keeping one record per line.

    I would suggest maybe writing out the records as text to the file as serializing them will mean that any changes to the class whose objects you are serializing will cause problems.

    What you could do is write another class that deals with writing records to a file, have a method that takes a List/Array or whatever you are using (you still haven't said what you are using) and in that method loop over the collection and write each record out, after the record start a new line and so on. The field positions has to be consistent ie: if the name comes first and the year second then it must be like that for all rows.

    In this same class you can have another method for reading records which will return a collection of your chosen type. You read in the records line by line and after reading in each line split the fields up and create your objects that you will add to your collection.

    If you have further problems let me know
    Byron Tymvios

    Please use [ CODE ] and [/ CODE ] tags when posting code! See THIS on how to use code tags.

  5. #5
    Join Date
    Oct 2006
    Posts
    24

    Re: Need Button advice

    Here is my code. Hopefully this will give you a better idea of what is the best approach. Any examples you can provide me etc would be great.

    Do not mind all my // it's because of me trying to make things work, trial and error os that the code is just a copy of some other button for now.

    Oh and this part I just modified but it won't work any ideas?

    Code:
     btnSearch.addActionListener(new ActionListener(){
    		public void actionPerformed(ActionEvent ae){
    			String Search =
    			JOptionPane.showInputDialog("Enter name of Movie");
    		//	int x =0;
    		for(int x = 0; x < dvds.size(); x++)
    		{
      		DVD dvd = (DVD)dvds.get(x);
      //if(dvd.title.equals(dvd.title))// or
      		if(dvd.title.equalsIgnoreCase(dvd.title))
      		{
       	list.setSelectedIndex(x);
       	break;
     	}
    	}
    		if(x = dvds.size()) System.out.println("not found");
    		}
       });
    thanks!

    Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.JFrame.*;
    import java.io.*;
    class Testing
    {
      java.util.List<DVD> dvds = new java.util.ArrayList<DVD>();
    
    
    
      JTextField tfTitle = new JTextField(15);
      JTextField tfGenre = new JTextField(15);
      JTextField tfProductNumber = new JTextField();
      JTextField tfPrice = new JTextField();
      JTextField tfQuantity = new JTextField();
      JTextField tfRestockFee = new JTextField();
      JTextField tfInventoryValue = new JTextField();
      DefaultListModel dlm = new DefaultListModel();
      JList list = new JList(dlm);
      public void buildGUI()
      {
        JButton btnLoadfile = new JButton("Load File");
        JButton btnAdd = new JButton("Add");
        JButton btnModify = new JButton("Modify");
        JButton btnDelete = new JButton("Delete");
        JButton btnSearch = new JButton("Search");
        JButton btnSave = new JButton("Save");
        JButton btnFirst = new JButton ("First");
        JButton btnPrevious = new JButton ("Previous");
        JButton btnNext = new JButton ("Next");
        JButton btnLast = new JButton ("Last");
        JPanel p1 = new JPanel(new BorderLayout());
        JPanel p = new JPanel(new GridLayout(7,2));
        p.add(new JLabel("DVD Title: "));
        p.add(tfTitle);
        p.add(new JLabel("Genre: "));
        p.add(tfGenre);
        p.add(new JLabel("Product Number: "));
        p.add(tfProductNumber);
        p.add(new JLabel("Price per Unit: "));
        p.add(tfPrice);
        p.add(new JLabel("Quantity on Hand: "));
        p.add(tfQuantity);
        p.add(new JLabel("Restocking Fee (5%): "));
        p.add(tfRestockFee);
        p.add(new JLabel("Inventory Value: "));
        p.add(tfInventoryValue);
        p1.add(p,BorderLayout.CENTER);
        JPanel p2 = new JPanel();
        JPanel p3 = new JPanel();
        p2.add(btnLoadfile);
        p2.add(btnAdd);
        p2.add(btnModify);
        p2.add(btnDelete);
        p2.add(btnSearch);
        p2.add(btnSearch);
        p2.add(btnSave);
        p3.add(btnFirst);
        p3.add(btnPrevious);
        p3.add(btnNext);
        p3.add(btnLast);
        p1.add(p2,BorderLayout.NORTH);
        p1.add(p3,BorderLayout.SOUTH);
        JFrame f = new JFrame("DVD Inventory");
        JLabel label = new JLabel ( new ImageIcon("test.gif"));
        f.getContentPane().add(label, BorderLayout.SOUTH);
        f.getContentPane().add(p1,BorderLayout.NORTH);
        JScrollPane sp = new JScrollPane(list);
        f.getContentPane().add(sp,BorderLayout.CENTER);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setLocationRelativeTo(null);
        dvds.add(new DVD("Batman","Action","9583",17.00,7,5.95,124.95));
        dvds.add(new DVD("Cinderella","Family","2734",19.00,8,7.60,159.60));
        dvds.add(new DVD("Friends","Comedy","9824",18.00,5,4.50,94.50));
        dvds.add(new DVD("Lost","Drama","9382",25.00,2,2.50,52.50));
        dvds.add(new DVD("OfficeSpace","Comedy","9821",20.00,5,5.00,105.00));
        dvds.add(new DVD("StarWars","Action","1245",10.00,5,5.00,55.00));
        dvds.add(new DVD("Superman","Action","3652",20.00,10,10.00,210.00));
        setList();
        f.setVisible(true);
        //f.setIconImage(new ImageIcon("Images/test.gif").getImage());
        btnAdd.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            dvds.add(new DVD(tfTitle.getText(),tfGenre.getText(),tfProductNumber.getText(),
                                    Double.parseDouble(tfPrice.getText()),
                                   Integer.parseInt(tfQuantity.getText()),
                                   Double.parseDouble(tfRestockFee.getText()),
                                   Double.parseDouble(tfInventoryValue.getText())));
            setList();
            clearTextFields();
                  }
        });
        btnDelete.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            int index = list.getSelectedIndex();
            dvds.remove(index);
            setList();
            clearTextFields();
          }
        });
    
            btnModify.addActionListener(new ActionListener(){
    	      public void actionPerformed(ActionEvent ae){
    	    int index = list.getSelectedIndex();
            dvds.remove(index);
    	        dvds.add(new DVD(tfTitle.getText(),tfGenre.getText(),tfProductNumber.getText(),
    	                                Double.parseDouble(tfPrice.getText()),
    	                               Integer.parseInt(tfQuantity.getText()),
    	                               Double.parseDouble(tfRestockFee.getText()),
    	                               Double.parseDouble(tfInventoryValue.getText())));
    	        setList();
    	        clearTextFields();
    	              }
        });
            btnFirst.addActionListener(new ActionListener(){
    		      public void actionPerformed(ActionEvent ae){
    	        DVD dvd = (DVD)dvds.get(0);
    		        			list.setSelectedIndex(0);
    	     }
    	   });
    	        btnLast.addActionListener(new ActionListener(){
    			      public void actionPerformed(ActionEvent ae){
    			        DVD dvd = (DVD)dvds.get(6);
    			        			list.setSelectedIndex(6);
    		      }
    	    });
    
     // btnSave.addActionListener(new ActionListener(){
    //		public void actionPerformed(ActionEvent ae){
    //
    //		      try
    //		      {
    //		        File file = new File("TestSave.txt");
    //		        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
    //		        out.println("a line");
    //		        out.println("another line");
    //		        out.close();//<---------very important
    //		      }
    //		      catch(IOException ioe){ioe.printStackTrace();}
    //		    }
    //		  }
    
    		    //dvds.add(new DVD(tfTitle.getText(),tfGenre.getText(),tfProductNumber.getText(),
    		    //                            Double.parseDouble(tfPrice.getText()),
    		    //                           Integer.parseInt(tfQuantity.getText()),
    		    //                           Double.parseDouble(tfInventoryValue.getText())));
    //		        setList();
    //		        clearTextFields();
    //		              }
     //   });
        btnSearch.addActionListener(new ActionListener(){
    		public void actionPerformed(ActionEvent ae){
    			String Search =
    			JOptionPane.showInputDialog("Enter name of Movie");
    		//	int x =0;
    		for(int x = 0; x < dvds.size(); x++)
    		{
      		DVD dvd = (DVD)dvds.get(x);
      //if(dvd.title.equals(dvd.title))// or
      		if(dvd.title.equalsIgnoreCase(dvd.title))
      		{
       	list.setSelectedIndex(x);
       	break;
     	}
    	}
    		if(x = dvds.size()) System.out.println("not found");
    		}
       });
    
        btnPrevious.addActionListener(new ActionListener(){
    	      public void actionPerformed(ActionEvent ae){
    	        DVD dvd = (DVD)dvds.get(list.getSelectedIndex());
    	        			int index = list.getSelectedIndex()-1;
    	        			 if (index <0) index = dvds.size()-1;
    	        			list.setSelectedIndex(index);
          }
        });
         btnNext.addActionListener(new ActionListener(){
    		      public void actionPerformed(ActionEvent ae){
    				  	   DVD dvd = (DVD)dvds.get(list.getSelectedIndex());
    				  	    //int index = list.getSelectedIndex()+1;
    				  	    int index = (list.getSelectedIndex()+1) % dvds.size();
    	        			list.setSelectedIndex(index);
    
         }
        });
    
        list.addListSelectionListener(new ListSelectionListener(){
          public void valueChanged(ListSelectionEvent lse){
            if(lse.getValueIsAdjusting() == false)
            {
              int index = list.getSelectedIndex();//<---
              if(index > -1)//<---
              {
                DVD dvd = (DVD)dvds.get(index);//<---
                tfTitle.setText(dvd.title);
                tfGenre.setText(dvd.genre);
                tfProductNumber.setText(dvd.productNumber);
                tfPrice.setText(""+dvd.price);
                tfQuantity.setText(""+dvd.quantity);
                tfRestockFee.setText(""+dvd.restockFee);
                tfInventoryValue.setText(""+dvd.inventoryValue);
              }
            }
          }
        });
    
    }
    
      public void setList()
      {
        dlm.clear();
        for(int x = 0, y = dvds.size(); x < y; x++)
        {
          dlm.addElement((DVD)dvds.get(x));
        }
      }
      public void clearTextFields()
      {
        tfTitle.setText("");
        tfGenre.setText("");
        tfProductNumber.setText("");
        tfPrice.setText("");
        tfQuantity.setText("");
        tfRestockFee.setText("");
        tfInventoryValue.setText("");
        tfTitle.requestFocusInWindow();
      }
    
    
      public static void main(String[] args)
      {
        EventQueue.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
          }
        });
      }
    }
    class DVD
    {
      String title;
      String genre;
      String productNumber;
      double price;
      int quantity;
      double restockFee;
      double inventoryValue;
      public DVD(String t,String g, String pn, double p, int q, double r, double i)
      {
        title = t; genre = g; productNumber = pn; price = p; quantity = q; restockFee = r; inventoryValue = i;
      }
      public String toString(){return title;}
    }
    Last edited by llsmr777; November 1st, 2006 at 04:43 PM.

  6. #6
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Need Button advice

    Quote Originally Posted by llsmr777
    Oh and this part I just modified but it won't work any ideas?
    It's because you're comparing 'dvd.title' with itself instead of with 'search'

    The best performance improvement is the transition from the nonworking state to the working state ...
    J. Osterhout
    Please use &#91;CODE]...your code here...&#91;/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  7. #7
    Join Date
    Oct 2006
    Posts
    24

    Re: Need Button advice

    You mean on this line:

    if(dvd.title.equalsIgnoreCase(dvd.title))

    Actually the error I get is on this line:

    if(x = dvds.size()) System.out.println("not found");

    And if I remove this line - it compiles. then when I run the application and hit search a box comes up as expected asking me to enter the movie name but then when I enter the movie name - it does't go to the movie I've typed.

    Thanks!

  8. #8
    Join Date
    Dec 2005
    Posts
    251

    Re: Need Button advice

    Quote Originally Posted by llsmr777
    if(x = dvds.size()) System.out.println("not found");
    maybe you mean:
    Code:
    if(x == dvds.size()) System.out.println("not found");

  9. #9
    Join Date
    Oct 2006
    Posts
    24

    Re: Need Button advice

    Actually this is what I have now and it compiles but when I run it, it doesn't do what I want it to do. When I enter a DVD it just goes to "0" the first DVD and then when I enter a DVD name that is not on the list - no error message comes up like I've specified.

    Code:
    btnSearch.addActionListener(new ActionListener(){
    		public void actionPerformed(ActionEvent ae){
    			String Search =
    			JOptionPane.showInputDialog("Enter name of Movie");
    		int x =0;
    	//	for (x=0; x=1; x=2; x=3, x=4, x=5,x=6, x=7; x<(7);x++)
    	//	for (x=0; x=1; x=2; x=3; x=4; x=5;x=6; x=7;)
    		for (x=0; x<(7);x++)
    		//for(int x = 0; x < dvds.size(); x++)
    		{
      		DVD dvd = (DVD)dvds.get(x);
      //if(dvd.title.equals(dvd.title))// or
      		if(dvd.title.equalsIgnoreCase(dvd.title))
      		{
       	list.setSelectedIndex(x);
       	break;
     	}
    	}
    	if(x == dvds.size()) JOptionPane.showInputDialog("Movie not found.");
    
    		}
       });

  10. #10
    Join Date
    Apr 2001
    Location
    South Africa, Jo'burg
    Posts
    680

    Re: Need Button advice

    Thats because you are comparing the title of the dvd to itself:
    Code:
    if(dvd.title.equalsIgnoreCase(dvd.title))
    which will always return true since you are comparing the title of the same dvd. Then after it has returned true and entered the if statement you break which will exit the for loop, so all you are doing is going through the first iteration of the for loop, entering the if statement which will always return true then exiting the whole for loop via the break statement. So you will never even get to the second iteration. Try removing the break statement and see what happens.
    Byron Tymvios

    Please use [ CODE ] and [/ CODE ] tags when posting code! See THIS on how to use code tags.

  11. #11
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Need Button advice

    Quote Originally Posted by llsmr777
    Actually this is what I have now and it compiles but when I run it, it doesn't do what I want it to do.
    If you took the trouble to step through the code by hand, away from the computer, you'd spot these errors far quicker.

    The value of a prototype is in the education it gives you, not in the code itself...
    A. Cooper
    Please use &#91;CODE]...your code here...&#91;/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  12. #12
    Join Date
    Oct 2006
    Posts
    24

    Re: Need Button advice

    I promise I have been stepping through it but I hardly even undersatnd java. Most of my code is via examples and just trying to modify it.

    I have tried so many variations but I can't get it to find the DVD. I finally got the message DVD not found but even if I enter a valid DVD it doesn't find it?

  13. #13
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: Need Button advice

    Quote Originally Posted by llsmr777
    but I hardly even undersatnd java. Most of my code is via examples and just trying to modify it.
    Rather than spending hour upon hour randomly changing bits of code and then posting questions here and waiting for answers. You could have used the time to work through a tutorial of two by now and you would now have a much better understanding of Java; you would be a lot less frustrated; you wouldn't need to be trying to change someone elses code to get it to do what you want and you would be able to write your own code and know how to debug it. That's not to say you won't still get stuck from time to time but at least you'll have the knowledge to post precise questions and be better equiped to understand the answers.

    My advice is to leave your program for a short while and learn the basics, then when you return to your program you'll find you can complete it fairly quickly.

  14. #14
    Join Date
    Oct 2006
    Posts
    24

    Re: Need Button advice

    I have gone through the tutorials several times actually not the entire thing of course because it's quite long. And I still can't even code based on examples.

    I know that I should be comparing what the user inputs in my enter movie dialog but I dont know how to call that.

    I will try to go to the tutorials yet again

  15. #15
    Join Date
    Oct 2006
    Posts
    24

    Re: Need Button advice

    Is this not correct?

    if(dvd.title.equalsIgnoreCase(Search));

    Is my code wrong in my for loop maybe?

Page 1 of 2 12 LastLast

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured