hi there i was wondering if someone could help me out. im doin an assigment where i have to create a CD database with a GUI. at the moment im having problems with my search engine. I enter 4 cd's from any artist. close the window, open the search for artist window, type in a particular artists name click find, my results will appear on a
Jtextarea screen. but the results will only show the details of the last cd input, multiplied by the number of cd's in the collection.

if someone could point out my problem i might be able to fix it. at the moment im stumped.

thanks very much kev.
ps the code is attached below.

Recommended Answers

All 28 Replies

Member Avatar for iamthwee

Please post your code here.

i posted an attachment in the first thread it was a java file. ill do the same as a txt file below.

Member Avatar for iamthwee

Erm I meant just copy and past the code into the message box window you are typing in.

sorry about that mis understanding. heres my code below.

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.util.Vector;



// This class is the main menu.

class Mainmenu extends JFrame implements ActionListener {

   JButton butAdd = new JButton("Add a CD"); 
   JButton butArtist = new JButton("Search by Artist");
   JButton butGenre = new JButton("Search by Genre");
   JButton butYear = new JButton ("Search by Year");
   JButton butLength = new JButton ("Search by Length");    
   JButton butExit = new JButton("Exit");
   
   // creating the main window code. 
   public Mainmenu() {
       
           super("Kev's CD Database");
           setSize(700,75);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       
       
        Container centerPanel = getContentPane(); 
       
        FlowLayout Layout = new FlowLayout();
        centerPanel.setLayout(Layout);
       
       
        butAdd.addActionListener(this);
        butArtist.addActionListener(this);
        butGenre.addActionListener(this);
        butYear.addActionListener(this);
        butLength.addActionListener(this);
        butExit.addActionListener(this);
        
        centerPanel.add(butAdd); 
         centerPanel.add(butArtist); 
         centerPanel.add(butGenre);
         centerPanel.add(butYear); 
        centerPanel.add(butLength); 
         centerPanel.add(butExit); 
     
    
        
        
        setContentPane(centerPanel);
    
        setVisible(true); }
        
        // the actions that are performed when the button is clicked. 
        public void actionPerformed(ActionEvent event) { 
         
         if (event.getSource () == butAdd) {
             AddCD addCD = new AddCD();    
         }
        if (event.getSource () == butArtist) {
            ArtistCD artist = new ArtistCD();
        }
             
         if (event.getSource () == butGenre) {
         //    GenreCD results = new GenreCD();
       }
        if (event.getSource () == butYear) {
        //    YearCD results = new YearCD();
         }
         if (event.getSource () == butLength) {
     //        LengthCD results = new LengthCD();
         }
        if (event.getSource() == butExit) {
           System.exit(0);
        }
         
    }    
     
        
   

}

//Class containing the code for adding a CD. 
class AddCD extends JFrame implements ActionListener{
    
    //stating whats goin to tbe in the window. 5 txt lines.
    
    JLabel labCDName = new JLabel("CD Name");
    JTextField txtCDName = new JTextField("",20);
    
    JLabel labCDArtist = new JLabel("The Artist");
    JTextField txtCDArtist = new JTextField("",20);
    
    JLabel labCDGenre = new JLabel("The Genre");
    JTextField txtCDGenre = new JTextField("",20);
    
    JLabel labCDYear = new JLabel("The Year");
    JTextField txtCDYear = new JTextField("",20);
    
    JLabel labCDLength = new JLabel("The Length of CD");
    JTextField txtCDLength = new JTextField("",20);
    
   // two buttons.
   
    JButton butAdd = new JButton("Add CD"); 
    JButton butClose = new JButton("Close");
    
    //temp folder to store info. 
    
    CD tempCD = new CD();

    
    public AddCD() {

        // creating the window to add the cd's
        super("Add a CD"); 
        setSize(275,310); 
         setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    
        Container content = getContentPane(); 
        
        FlowLayout layout = new FlowLayout(); 
          content.setLayout(layout); 
        
        // adds the buttons to the window. 
        content.add(labCDName);
        content.add(txtCDName);
        content.add(labCDArtist);
        content.add(txtCDArtist);
        content.add(labCDGenre);
        content.add(txtCDGenre);
        content.add(labCDYear);
        content.add(txtCDYear);
        content.add(labCDLength);
        content.add(txtCDLength);
        content.add(butClose);
        content.add(butAdd); 
            
        // adds a listener to the buttons    
        butAdd.addActionListener(this); 
        butClose.addActionListener(this);
        
        // show the window
         setContentPane(content);     
         setVisible(true);
        
    }
    
    // 
    public void actionPerformed(ActionEvent event) { 
         if (event.getSource() == butAdd) {
            // read the contents of the JTextFields
            tempCD.Title = txtCDName.getText();
            tempCD.Artist = txtCDArtist.getText();
            tempCD.Genre = txtCDGenre.getText();
            tempCD.Year = txtCDYear.getText();
            tempCD.Length = txtCDLength.getText();
             // add the CD to the collection
            Java2.vCDs.add(tempCD);
            System.out.println( Java2.vCDs.size() + "CD(s) in your collection." );
            
        }
           // closing the window
        if (event.getSource() == butClose) {
            dispose();
    }
    
}

}


// searching for results by artist. 
class ArtistCD extends JFrame implements ActionListener{
    
    JTextArea artist = new JTextArea(""); 
    JLabel labFind = new JLabel("Which Artist");
    JTextField txtFind = new JTextField("",20);    
    JButton butFind = new JButton("Find");
    JButton butClose = new JButton("Close");
    
    CD findTXT = new CD();
    
    public ArtistCD() {
        
        // 
        super("Add a CD"); 
        setSize(300,1000); 
         setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    
        Container content = getContentPane(); 
        
        FlowLayout layout = new FlowLayout(); 
          content.setLayout(layout); 
        
        //add the buttons and textBoxes
        content.add(artist);
        content.add(butClose);    
        content.add(butFind);
        content.add(labFind);
        content.add(txtFind);
        //adds listener to buttons
        butFind.addActionListener(this); 
        butClose.addActionListener(this);
            
        // show the window
         setContentPane(content);     
         setVisible(true);
     
    }
        public void actionPerformed(ActionEvent event) {
        //if the find button has been clicked.     
        if (event.getSource() == butFind) {
            findTXT.Artist = txtFind.getText();
            
        
        for (int i=0; i<Java2.vCDs.size();i++) {
            CD tempFindTXT = (CD)Java2.vCDs.get(i);
            if (tempFindTXT.Artist.equals(findTXT.Artist)){
            
            artist.append(tempFindTXT.Title);
            artist.append("\n"); 
            artist.append(tempFindTXT.Artist);
            artist.append("\n");
            artist.append(tempFindTXT.Genre);
            artist.append("\n");        
            artist.append(tempFindTXT.Year);
            artist.append("\n");    
            artist.append(tempFindTXT.Length);
            artist.append("\n");    
            artist.append("********************");
            artist.append("\n");
            
            }
        }
      }
        
           // closing the window
        if (event.getSource() == butClose) {
            dispose();
         }
      }
}
    
    
    



// Main Class 
public class Java2 {

    static Vector vCDs = new Vector();
        
    public static void main (String[] args) {

        Mainmenu start = new Mainmenu();
    }
}
// CD Class
class CD {
    String Artist;
    String Title;
    String Genre;
    String Year;
    String Length;
    
}
Member Avatar for iamthwee

Ok I assume it compiles and works... You've told us what happens but what do you want the output to be?

yes it compiles with no errors and runs. i want to be able to input multiple cd's by so many artists.
then when searching for a particular artist i want their cd info to be displayed.

at the moment when i search for a particular artist the last cd information inputed is displayed many times overs( so if 5 cd's are in the database it will be displayed 5 times so on).

thanks

kev.

Member Avatar for iamthwee

So you are saying when you search for an artist, let's assume you have artist X stored five times in your database (with different songs of course), only the last entry shows, instead of all five?

So I'm guessing your problem must reside somewhere here:-

public void actionPerformed(ActionEvent event) {
        //if the find button has been clicked.     
        if (event.getSource() == butFind) {
            findTXT.Artist = txtFind.getText();
            
        
        for (int i=0; i<Java2.vCDs.size();i++) {
            CD tempFindTXT = (CD)Java2.vCDs.get(i);
            if (tempFindTXT.Artist.equals(findTXT.Artist)){
            
            artist.append(tempFindTXT.Title);
            artist.append("\n"); 
            artist.append(tempFindTXT.Artist);
            artist.append("\n");
            artist.append(tempFindTXT.Genre);
            artist.append("\n");        
            artist.append(tempFindTXT.Year);
            artist.append("\n");    
            artist.append(tempFindTXT.Length);
            artist.append("\n");    
            artist.append("********************");
            artist.append("\n");
            
            }
        }
      }

yes only the last entry shows, but will be displayed 5 times.

its very strange and im not 100% sure where the problem lying. ive been staring at this code for hours and can't see any problems as to why this is happening.

thanks
kev.

Member Avatar for iamthwee
public void actionPerformed(ActionEvent event) {
        //if the find button has been clicked.   
        String crap = "";  
        if (event.getSource() == butFind) {
             crap = txtFind.getText();
            
        
        for (int i=0; i<Java2.vCDs.size();i++) {
            CD tempFindTXT = (CD)Java2.vCDs.get(i);
            if (tempFindTXT.Artist.equals(crap)){
            
            artist.append(tempFindTXT.Title);
            artist.append("\n"); 
            artist.append(tempFindTXT.Artist);
            artist.append("\n");
            artist.append(tempFindTXT.Genre);
            artist.append("\n");        
            artist.append(tempFindTXT.Year);
            artist.append("\n");    
            artist.append(tempFindTXT.Length);
            artist.append("\n");    
            artist.append("********************");
            artist.append("\n");
            
            }
        }
      }

I don't have my compiler to hand but what happens if you do the above?

compiled with no errors and ran.

tried out what you said still have the same problem. entered 3 cd's by the same artist searched only showed last cd details 3 times.

still confused. any ideas whats causing this error??

thanks
kev.

ps-: tried with your edited version still the same problems.

Member Avatar for iamthwee

>entered 3 cd's by the same artist searched only showed last cd details 3 times.

Yeah something else is the problem.

It's hard to visualise with actually running it!

Member Avatar for iamthwee

Where is your information for the artists stored? In a text file or within the program? Never mind I see you are adding them dynamically as you run the form. Hmmm

Member Avatar for iamthwee

Before you do the search part.

Can you do a "system.out.println" from the beginning to the end of the vector to see if all different items are stored there.

yeah its been stored in to a vector while the program is running.
is there a possibility theres a problem with saving the information??


thanks
kev.

will give it a shot.

Member Avatar for iamthwee

will give it a shot.

Possibly, it might be saving the last entry five times over? Instead of the individual ones? I'm not sure how the vector.add() method works. I've always had the "use an ArrayList over vector mantra drilled in to me." so I have never actually used vectors.

Of course it might not be that either.

the code below shows me data is being inputed.

public void actionPerformed(ActionEvent event) { 
         if (event.getSource() == butAdd) {
            // read the contents of the JTextFields
            tempCD.Title = txtCDName.getText();
            tempCD.Artist = txtCDArtist.getText();
            tempCD.Genre = txtCDGenre.getText();
            tempCD.Year = txtCDYear.getText();
            tempCD.Length = txtCDLength.getText();
             // add the CD to the collection
            Java2.vCDs.add(tempCD);
            System.out.println( Java2.vCDs.size() + "CD(s) in your collection." );

it must be inputing correctly as if you input 1 cd and search the information is returned.


thanks
kev.

Possibly, it might be saving the last entry five times over? Instead of the individual ones? I'm not sure how the vector.add() method works. I've always had the "use an ArrayList over vector mantra drilled in to me." so I have never actually used vectors.

Of course it might not be that either.

yeah i have a friend whose is the same arraylist over vectors.
nearly tearing out my hair lol.

thanks for all your help.
kev.

Member Avatar for iamthwee

And what happens when you input more than one cd, is all the information returned before you hit the search button?

Do something like

for (i=vector =0; i< vector.size; i++)
{
print (vector.name)
print (vector.song)
print("\n")
}

To make sure it is returning all the correct info.

Member Avatar for iamthwee

I've gotta go now...

I've gotta go now...

no worries ta for your help.

thanks
kev.

And what happens when you input more than one cd, is all the information returned before you hit the search button?

Do something like

for (i=vector =0; i< vector.size; i++)
{
print (vector.name)
print (vector.song)
print("\n")
}

To make sure it is returning all the correct info.

ive added a printline so it prints what ever is entered into the vector and all the info is inputed so the problem is with my code recalling from the vector.

Had similar problem few months ago

Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.

Basicly if you try to re-use structure which store String variables it will only remeber last entry. I was lucky because I was geting data from somwhere else and coudl create array as the size was known before array initialized.

Let me illustrate

//NamesInVector.java
import java.util.*;

public class NamesInVector
{
	public static void main(String[] args)
	{
		Vector v = new Vector();
		Names names = new Names();
		
		names.setFirstName("peter");
		names.setLastName("Budo");
		v.add(names);
		
		Names test = (Names) v.get(0);
		System.out.println(test.getFirstName() + "\n" + test.getLastName());
                //prints peter, new line, budo
		
		names.setFirstName("some");
		names.setLastName("any");
		v.add(names);
		
		for(int i = 0; i < v.size(); i++)
		{
			test = (Names) v.get(i);
			System.out.println(test.getFirstName() + "\n" + test.getLastName());
                       /* prints some, \n, any, \n, some, \n, any insted of peter and budo as first names*/
		}
	}	
}
//Names.java
public class Names
{
	public String firstName;
	public String lastName;
	
	public void setFirstName(String str)
	{
		firstName = str;
	}
	
	public String getFirstName()
	{
		return firstName;
	}
		
	public void setLastName(String str)
	{
		lastName = str;
	}
		
	public String getLastName()
	{
		return lastName;
	}
}

But this will take care of your problem

//NamesInVector.java
import java.util.*;

public class NamesInVector
{
	public static void main(String[] args)
	{
		Vector v = new Vector();
		Names[] names = new Names[2];
		
		names[0] = new Names();
		names[0].setFirstName("peter");
		names[0].setLastName("Budo");
		v.add(names[0]);
		
				
		
		names[0] = new Names();
		names[0].setFirstName("some");
		names[0].setLastName("any");
		v.add(names[0]);
		
		names[0] = new Names();
		names[0].setFirstName("trouble");
		names[0].setLastName("maker");
		v.add(names[0]);
		
		Names test = new Names();

		for(int i = 0; i < v.size(); i++)
		{
			test = (Names) v.get(i);
			System.out.println(test.getFirstName() + "\n" + test.getLastName());
		}
	}	
}

Sorry for such feable examples but couldn't make it any better, little tired at midnight

hey thanks for your help. im sorry but i dont know how to fit it in my code. im currently adding the information to the vector via my program. im just confused as this method seems to work for alot of ppl i know doin the same assignment. i cant figure out why this is happening.

anyways thanks for your help

kev.

Hi Peter,

The problem you faced was due to modification of original values of the object. Since you modified the value by "some" and "any". It prints "some" and "any" all the times.

For example
As you modifies the value as "some" and "any", now don't add this name object to vector. Now you have only one name object in vector.
You print the output now. Still you will get the same output. It will print "some" and "any" insted of "Peter" and "Budo"

This is due to"Java passes object references by value."

The example you had given for correction of your problem

[U]names[0] = new Names();[/U]        
names[0].setFirstName("peter");
names[0].setLastName("Budo");
v.add(names[0]);
 
 
 
[U]names[0] = new Names();[/U]
names[0].setFirstName("some");
names[0].setLastName("any");
v.add(names[0]);
 
names[0] = new Names();
names[0].setFirstName("trouble");
names[0].setLastName("maker");
v.add(names[0]);

Here everytime you had created new object that's why you did't faced the problem.

This is the mistake you are doing viper.

hey thanks but this still doesnt help me. im editing the vector via my program. all cd info is being added from a window and being read into the vector. it is not being added by the code.

Vectors are supposed to expand everytime you input information but currently mine isnt it is overridding i want to know how to stop this.

// 
    public void actionPerformed(ActionEvent event) { 
         if (event.getSource() == butAdd) {
            // read the contents of the JTextFields
            tempCD.Title = txtCDName.getText();
            tempCD.Artist = txtCDArtist.getText();
            tempCD.Genre = txtCDGenre.getText();
            tempCD.Year = txtCDYear.getText();
            tempCD.Length = txtCDLength.getText();
             // add the CD to the collection
            Java2.vCDs.add(tempCD);
            System.out.println( Java2.vCDs.size() + "CD(s) in your collection." );
            System.out.println("Info Inputed:");
            System.out.println("CD Name: " + tempCD.Title);
            System.out.println("CD Artist: " + tempCD.Artist);
            System.out.println("CD Year: " + tempCD.Year);
	    System.out.println("CD Length: " + tempCD.Length);
	    System.out.println("CD Genre: " + tempCD.Genre);

this should in theory read from the txt fields and add information to vCDs (thevector).

if (event.getSource() == butFind) {
            findTXT.Artist = txtFind.getText();
            
            
        
        for (int i=0; i<Java2.vcd.size();i++) {
            CD tempFindTXT = (CD)Java2.vcd.get(i);
            if (tempFindTXT.Artist.equals(findTXT.Artist)){
            
            artist.append("\n");
            artist.append(tempFindTXT.Title);
            artist.append("\n"); 
            artist.append(tempFindTXT.Artist);
            artist.append("\n");
            artist.append(tempFindTXT.Genre);
            artist.append("\n");        
            artist.append(tempFindTXT.Year);
            artist.append("\n");    
            artist.append(tempFindTXT.Length);
            artist.append("\n");    
            artist.append("********************");
            artist.append("\n");

this code should read from the vector and add all information to a jtextarea but currently it isnt. see problem above.

thanks

kev.

Here everytime you had created new object that's why you did't faced the problem.

This is the mistake you are doing viper.

I know where was problem, but viper didn't get it
Provided examples been done on purpose to let him think about it :P

hey thanks for everyones help but ive sorted the problem.

to fix the problem all i had to do was close the window after adding a cd. this is a simple as you add a dispose(); to the addCD button.

sorted :D

thanks

kev.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.