I have 3 things left I want to do to this app, I saved the hardest for last ... now I am wondering why.
First is a search button. I want to be able to Search on my cd name field.
I have been reading and playing with this since yesterday, I thought I had it, started coding it in, and the logic fails me.

This is what I wrote that I think should work.

cdNameField.addCaretListener(new CaretListener()
{
     public void careUpdate(CaretEvent e)
     {
      JTextField f = (JTextField)e.getSource();
      final String s = f.getText();

       SwingUtilites.invokeLate(new Runnable()
         {
          public void run()
           {
            try 
             {
              for(int i-0; i < listModel.getSize(); i++
              {
               String item = (String)listModel.elementAt(i);
               String sub = item.substring(0, s.lenght());
    
                if(sub.equalsIgnoreCase(s))
                 {
                   Inventorylist.setSelectedIndex(i);
                   Inventorylist.scrollRectToVisible(Inventorylist.getCellBounds(i,i));
                      break;
                  }
                }
               }
          }
       });
     }
});

Now I have never done this, and most of that is just from what I have read.
When I started putting it in to my code I noticed two things.
1st - This listener seems to be a CaretListener .... how will that work with my ActionListener and my SEARCH button?
2nd - I already have a runnable for my panel. Does the code from this runnable next inside my current one, or can I have more than one in the same app?
Here is my code - any help, as always will be appreciated.

import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.text.*;
import java.lang.*;
import javax.swing.JFrame;

public class Inventory2 extends JFrame
{
	private JLabel cdNameLabel; // name label 
	private JLabel artistLabel; // item number label 
	private JLabel nstockLabel; // units in stock label 
	private JLabel priceLabel; // price each label 
	private JLabel itemLabel; // item number label 
	private JTextField cdNameField; // name display 
	private JTextField artistField; // artist display 
	private JFormattedTextField nstockField; // units in stock display 
	private JFormattedTextField priceField; // price each display 
	private JTextField itemField; // item number display 
	private NumberFormat nstockFormat; // format field and parse numbers 
	private NumberFormat priceFormat; // format field and parse numbers 
	private JButton btnAdd; // first button 
	private JButton btnPrev; // previous button 
	private JButton btnNext; // next button 
	private JButton btnDel; // last button 
	private JButton btnFirst; // first button
	private JButton btnLast; // last button
	private JButton btnModify; // modify button
	private JButton btnSave; // save button
	private JButton btnSearch; // search button
	private JPanel buttonJPanel; // JPanle to hold buttons 
	private JPanel fieldJPanel; // JPanel to hold labels and displays 
	private JPanel fontJPanel; // JPanel to display logo 
	private int currCD; 
	private double total = 0; // variable for total inventory 
	private JList Inventorylist; // JList to take place of old array
	private DefaultListModel listModel;
	private JScrollPane jScrollPanel;  
	private float Invtotal = .00f;
	
	 DecimalFormat formatter = new DecimalFormat("0.00");
	
	public Inventory2() // create class and method to perform GUI build 
	{ 
		initComponents(); 
	} 

	private void initComponents() 
	{ 
			
		// create label names 
		cdNameLabel = new JLabel("CD Name:"); 
		artistLabel = new JLabel("Artist:");
		nstockLabel = new JLabel("In Stock:"); 
		priceLabel = new JLabel("Each Item Cost:$"); 
		itemLabel = new JLabel("Item Number:"); 
 
		
		// initial fields
		cdNameField = new JTextField(25);
		cdNameField.setEditable(true);
		artistField = new JTextField(15);
		artistField.setEditable(true);
		nstockField = new JFormattedTextField(nstockFormat);
		nstockField.setEditable(true);
		nstockField.setColumns(5);
		priceField = new JFormattedTextField(priceFormat);
		priceField.setEditable(true);
		priceField.setColumns(5);
		itemField = new JTextField(4);
		itemField.setEditable(true);
				
		// JList
		jScrollPanel = new JScrollPane();
		Inventorylist = new JList(); 
		currCD = 0;
	
				
		// buttons 
		btnAdd = new JButton(); 
		btnNext = new JButton(); 
		btnPrev = new JButton(); 
		btnDel = new JButton();
		btnLast = new JButton();
		btnFirst = new JButton();
		btnModify = new JButton(); 
		btnSave = new JButton();
		btnSearch = new JButton();
		
		getContentPane().setLayout(new FlowLayout());
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		
		// add shapesJPanel to frame    
		ShapesJPanel logo = new ShapesJPanel();
		logo.setPreferredSize(new Dimension(200,200));
		getContentPane().add( logo );

		// place textFields and labels
		
		//artist
		artistLabel.setText("Artist"); 
		getContentPane().add(artistLabel); 

		artistField.setMinimumSize(new Dimension(70,20)); 
		artistField.setPreferredSize(new Dimension(70,20));
		getContentPane().add(artistField); 
		
		// cd name
		cdNameLabel.setText("CD Name"); 
		getContentPane().add(cdNameLabel); 

		cdNameField.setMinimumSize(new Dimension(70,20)); 
		cdNameField.setPreferredSize(new Dimension(70,20));
		getContentPane().add(cdNameField);
		
		// copies in stock
		nstockLabel.setText("Copies In Stock"); 
		getContentPane().add(nstockLabel); 

		nstockField.setMinimumSize(new Dimension(5,20)); 
		nstockField.setPreferredSize(new Dimension(5,20));
		getContentPane().add(nstockField); 
		
		//price of cd
		priceLabel.setText("Price: $"); 
		getContentPane().add(priceLabel); 

		priceField.setMinimumSize(new Dimension(20,20)); 
		priceField.setPreferredSize(new Dimension(20,20));
		getContentPane().add(priceField); 
		
		//item number of cd
		itemLabel.setText("Item Number"); 
		getContentPane().add(itemLabel); 

		itemField.setMinimumSize(new Dimension(5,20)); 
		itemField.setPreferredSize(new Dimension(5,20));
		getContentPane().add(itemField); 
		


		// add listeners
		
		btnAdd.setText("Add");
		btnAdd.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				btnAddActionPerformed(evt);
			}
		});
		getContentPane().add(btnAdd);
		 
		// PREVIOUS
		btnPrev.setText("Previous");
		btnPrev.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				btnPrevActionPerformed(evt);
			}
		});
		getContentPane().add(btnPrev);
		
		// NEXT
		btnNext.setText("Next");
		btnNext.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				btnNextActionPerformed(evt);
			}
		});
		getContentPane().add(btnNext);
		
		// SEARCH
		btnSearch.setText("Search");
		btnSearch.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				btnAddActionPerformed(evt);
			}
		});
		getContentPane().add(btnSearch);
		
		// FIRST
		btnFirst.setText("First");
		btnFirst.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				btnFirstActionPerformed(evt);
			}
		});
		getContentPane().add(btnFirst);
		
		// LAST
		btnLast.setText("Last");
		btnLast.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				btnLastActionPerformed(evt);
			}
		});
		getContentPane().add(btnLast);
				
		// MODIFY
		btnModify.setText("Modify");
		btnModify.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				btnModifyActionPerformed(evt);
			}
		});
		getContentPane().add(btnModify);
					
		// SAVE
		btnSave.setText("Save");
		btnSave.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				btnAddActionPerformed(evt);
			}
		});
		getContentPane().add(btnSave);
		
		// DELETE
		btnDel.setText("Delete");
		btnDel.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent evt)
			{
				btnDeleteActionPerformed(evt);
			}
		});
		getContentPane().add(btnDel);
		
		
		// new Jlist model
		listModel = new DefaultListModel();
		Inventorylist.setModel(listModel);
		
		jScrollPanel.setViewportView(Inventorylist);
		
		getContentPane().add(jScrollPanel);
		
		pack();
	}// close
	
			
		private void btnAddActionPerformed(ActionEvent evt)
		{
			// Create cd to add
			CdwArtist newCD = new CdwArtist();
			newCD.setArtist(artistField.getText());
			newCD.setName(cdNameField.getText());	
			newCD.setItemno(Integer.parseInt(itemField.getText()));
			newCD.setNstock(Integer.parseInt(nstockField.getText()));
			newCD.setPrice(Float.parseFloat(priceField.getText()));
			
			// Add cd to list
			listModel.addElement(newCD);
			currCD = listModel.size()-1;  // sets currCD to added index
			
			
			// Clear the text fields after add
			artistField.setText(null);
			cdNameField.setText(null);	
			itemField.setText(null);
			nstockField.setText(null);
         priceField.setText(null);
	
			}// end ADD
		
		private void btnPrevActionPerformed(ActionEvent evt)
		{
			// Grab Previous cd 
			if (--currCD<0) currCD = listModel.size()-1;
			CdwArtist newCD = (CdwArtist) listModel.get( currCD );
			

			artistField.setText(newCD.getArtist());
			cdNameField.setText(newCD.getName());	
			itemField.setText(String.valueOf(newCD.getItemno()));
			nstockField.setText(String.valueOf(newCD.getNstock()));
			priceField.setText(formatter.format(newCD.getPrice()));
					
			
			}// end PREV
			
				private void btnNextActionPerformed(ActionEvent evt)
			{
			// Grab Next cd 
			if (++currCD >= listModel.size()) currCD= 0;
			CdwArtist newCD = (CdwArtist) listModel.get( currCD );
			

			artistField.setText(newCD.getArtist());
			cdNameField.setText(newCD.getName());	
			itemField.setText(String.valueOf(newCD.getItemno()));
			nstockField.setText(String.valueOf(newCD.getNstock()));
			priceField.setText(formatter.format(newCD.getPrice()));
					
			
			}// end NEXT
			
			
				private void btnFirstActionPerformed(ActionEvent evt)
			{
			// Grab First cd 
			CdwArtist newCD = (CdwArtist) listModel.get(0);
			currCD = 0;
				
			artistField.setText(newCD.getArtist());
			cdNameField.setText(newCD.getName());	
			itemField.setText(String.valueOf(newCD.getItemno()));
			nstockField.setText(String.valueOf(newCD.getNstock()));
			priceField.setText(formatter.format(newCD.getPrice()));
					
			
			}// end FIRST
			
			
				private void btnLastActionPerformed(ActionEvent evt)
			{
			// Grab Last cd 
			CdwArtist newCD = (CdwArtist) listModel.lastElement();
			currCD = listModel.size()-1;
			

			artistField.setText(newCD.getArtist());
			cdNameField.setText(newCD.getName());	
			itemField.setText(String.valueOf(newCD.getItemno()));
			nstockField.setText(String.valueOf(newCD.getNstock()));
			priceField.setText(formatter.format(newCD.getPrice()));
					
			
			}// end LAST
			
				private void btnDeleteActionPerformed(ActionEvent evt)
			{
			// Delete cd 
			listModel.remove(currCD);
				
			
			// Clear the text fields after delete
			artistField.setText(null);
			cdNameField.setText(null);	
			itemField.setText(null);
			nstockField.setText(null);
         priceField.setText(null);
					
			
			}// end DELETE
			
				private void btnModifyActionPerformed(ActionEvent evt)
			{
			// Modify cd
			listModel.remove(currCD);
			
			// Create cd to add
			CdwArtist newCD = new CdwArtist();
			newCD.setArtist(artistField.getText());
			newCD.setName(cdNameField.getText());	
			newCD.setItemno(Integer.parseInt(itemField.getText()));
			newCD.setNstock(Integer.parseInt(nstockField.getText()));
			newCD.setPrice(Float.parseFloat(priceField.getText()));
			
			// Add cd to list
			listModel.addElement(newCD);
			currCD = listModel.size()-1;  // sets currCD to added index
			
			
			// Clear the text fields after add
			artistField.setText(null);
			cdNameField.setText(null);	
			itemField.setText(null);
			nstockField.setText(null);
         priceField.setText(null);
					
			
			}// end Modify
			
			// Search the Name Field
			cdNameField.addCaretListener(new CaretListener()
			{
			public void caretUpdate(CaretEvent e)
				{
				JTextField f = (JtextField)e.getSource();
				final String s = f.getText();
			 
			
		// run it
		public static void main(String args[])
		{
		JFrame frame = new JFrame( "CD Inventory Logo" );
      frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

     	java.awt.EventQueue.invokeLater(new Runnable()
			{
			public void run()
				{
				new Inventory2().setVisible(true);
			   }
			});
		}
			
} // close class

Recommended Answers

All 34 Replies

Regular expression is answer to your problem. Ofcourse you can do it with substrings, but it is dirty work. Read up Sun tutorial on regular expressions here

1st - This listener seems to be a CaretListener .... how will that work with my ActionListener and my SEARCH button?

It won't as written. It will respond to any text change in your cd name field and perform a search on the list for an incremental match. If you want this to only occur when search is pressed you will need a state variable like boolean searching; for the caret listener to check before performing the search. Alternately you could provide a separate search field for the user to type in or use an input dialog (JOptionPane.showInputDialog(..) ) for this. It depends on how you want searching to be performed.

2nd - I already have a runnable for my panel. Does the code from this runnable next inside my current one, or can I have more than one in the same app?

You can have multiple runnables just fine. All those are doing is putting a piece of code into a queue to be run in a separate thread.

I can't even run that code and see. The code you pasted has all kinds of weird errors.

Exception in thread "main" java.lang.UnsatisfiedLinkError: java.awt.Toolkit.init
IDs()V
        at java.awt.Toolkit.initIDs(Native Method)
        at java.awt.Toolkit.<clinit>(Toolkit.java:1619)
        at java.awt.Component.<clinit>(Component.java:562)
Press any key to continue...

All kinds of weird erros ... welcome to my day! :o)
I know one thing, I recognize and understand almost every error I see now ... I may not be able to fix it, but it is all familiar territory.

I had not even thought about an additional Search field Ezzaral. That sounds a lot easier than what I have been reading.
I can make another field and panel with no problem ... how would I then tie what is entered into that field with my cdname and the Search button?

If Search is clicked and there is text in the search field, you just need to compare that to the cd names in the list model and if you have a match (or partial match if you wish), select that cd object.

I only want full match, or a message stating No Match ...
I cannot find any docs on how to do this.
Only thing I have found close is
FindMatchingItem, but there are not a lot of examples to go off of with that.
Is any of the code I had before useable? That is about the only thing close to what I am looking for that I have found.

You merely need to break down my previous post into steps and think about what each of those requires. You have text in a search field that you want to compare to the name (or title or whatever) property of each cd object in the list. The only way to do that is to loop through those and check for a match on each one. If one matches, you can make that the current cd. If there is no match, you could use the JOptionPane.showMessageDialog() method to inform the user that no match was found (alternately a label under the search field could be used for that as well).

I cant believe this actually works ... kind of ... it puts the wrong cd in there, but that is a currCD issue I need to work on.

This seems too easy ... is it right?

private void btnSearchActionPerformed(ActionEvent evt)
			{
			if (searchField == cdNameField); 	
			CdwArtist newCD = (CdwArtist) listModel.get( currCD );
			
			artistField.setText(newCD.getArtist());
			cdNameField.setText(newCD.getName());	
			itemField.setText(String.valueOf(newCD.getItemno()));
			nstockField.setText(String.valueOf(newCD.getNstock()));
			priceField.setText(formatter.format(newCD.getPrice()));
			}

Well, that doesn't really do anything at all beyond put the current cd info into your text fields. You will of course want to do that - after you have found the appropriate cd in the list model.

This statement does nothing whatsoever: if (searchField == cdNameField);

I knew that was too easy.
Where can I find something on how to do that compare?

You have all the knowledge to do it already, you just need to think about it.
a) You need to loop through the listModel.
b) You need to get the cd object and compare it's name property to the string you are looking for.
c) if it's a match, you need to make that the current cd
d) you need to set the text field values to the new current cd values.

I really can't spell it out any more clearly than that short of writing the code myself.

I am trying to put it together, but I have holes in my knowledge.
Step 1, Go to first element ... I know how to do this.
Step 2. Is to compare the cdNameField to my new searchField. I do not know how to do this.
Step 3. If Step 2 is a match .. fill fields. I know how to fill fields, but not how to structure this IF statement with what follows.
Step 4. If Step 2 was not a match, currCD++ and do it again, until we hit listModel()-1; I think I know this step.
Step 5. No matches, showMessageDialogue. Again, I do not know how to do this step.

private void btnSearchActionPerformed(ActionEvent evt)
			{
			CdwArtist newCD = (CdwArtist) listModel.get(0);
			currCD = 0;
			//compare searchField == cdNameField); 	
				// if match
				CdwArtist newCD = (CdwArtist) listModel.get( currCD );
			
				artistField.setText(newCD.getArtist());
				cdNameField.setText(newCD.getName());	
				itemField.setText(String.valueOf(newCD.getItemno()));
				nstockField.setText(String.valueOf(newCD.getNstock()));
				priceField.setText(formatter.format(newCD.getPrice()));
			
				else if(currCD<=listmodel.Size()-1;) currCD++;
			 			
			//JOptionPane.showMessageDialog(null,"No CD Match Found",JOptionPane.INFORMATION_MESSAGE);
			}// Search

It sounds easy, and I know what steps to do, maybe not even in the best order, but there are several things here I have never seen before.

You already had a pretty good start on the searching in that first post. The only issue there is that instead of

String item = (String)listModel.elementAt(i);

you would instead want to get

CdwArtist cdEntry = (CdwArtist)listModel.elementAt(i);

Using a boolean such as "matchFound" which is flagged on a match, you can present the message dialog if there was no match.

I knew this would be hard, that is why I saved it for the end, but man! I never expected it to be this bad.
I think I actually understand LESS than I did this morning! :o)

I am going to the gym, going home and play with my little one, and then try somemore before I go to bed.

Right now, this is what I have, and it is erroring all over the place. I do not even know where to begin.

// Search the Name Field
			private void btnSearchActionPerformed(ActionEvent evt)
			{
			//start at first cd
			currCD = 0;
			// compare
			JTextField f = (JTextField)e.getSource(); 
			final String s = f.getText(); 
			
			SwingUtilities.invokeLater( new Runnable() 
				{ 
				public void run() 
				{ 
				try 
					{ 
					for(int i = 0; i < listModel.getSize(); i++) 
					{ 
					CdwArtist cdEntry = (CdwArtist)listModel.elementAt(i);
         		String sub = item.substring(0, s.length()); 
			
					if(sub.equalsIgnoreCase(s)) 
						{ 
						Inventorylist.setSelectedIndex(i); 
						Inventorylist.scrollRectToVisible( Inventoryist.getCellBounds(i,i) ); 
						break; 
						} 
					} 
				} 
				catch(StringIndexOutOfBoundsException sie) 
				{} 
				} 
				}); 
			 
			 
 	
				// if match
				CdwArtist newCD = (CdwArtist) listModel.get( currCD );
			
				artistField.setText(newCD.getArtist());
				cdNameField.setText(newCD.getName());	
				itemField.setText(String.valueOf(newCD.getItemno()));
				nstockField.setText(String.valueOf(newCD.getNstock()));
				priceField.setText(formatter.format(newCD.getPrice()));
			
						 			
			JOptionPane.showMessageDialog(null,"No CD Match Found",JOptionPane.INFORMATION_MESSAGE);
			}// Search

It cannot find symbol e form e.getSource, or item from item.substring (and honestly I do not even know what these two things are) and to top that off my dialog box does not work either.

hopefully I can recharge and come at this fresh later, because right now it is winning the battle.

It cannot find symbol e form e.getSource, or item from item.substring (and honestly I do not even know what these two things are) and to top that off my dialog box does not work either.

Well, look at your code and you will see that you don't have variables "e" or "item". You don't need e.getSource() any longer anyway because you can just get the text to search for from your text field (e.getSource() was getting a reference to the component that you had the caret listener attached to). You changed "String item" to "CdwArtist cdEntry", so you have to work with the cdEntry now (and it has method to get it's properties...).

The only problem with your message box is a missing parameter. The form you are trying to use takes four, not three, which I am sure the compiler yelled at you about.

Well, look at your code and you will see that you don't have variables "e" or "item". You don't need e.getSource() any longer anyway because you can just get the text to search for from your text field (e.getSource() was getting a reference to the component that you had the caret listener attached to). You changed "String item" to "CdwArtist cdEntry", so you have to work with the cdEntry now (and it has method to get it's properties...).

The only problem with your message box is a missing parameter. The form you are trying to use takes four, not three, which I am sure the compiler yelled at you about.

I am going to work with this as much as I can tonight. I will try to find more to read, because I do not really understand it all just yet.
I made the mistake of telling my wife that I could actually turn the app in now and pass the class just fine, I have already worked on more than the required number of methods.
I just do not want to, I did the easier stuff first and amassed my points so that I would not get stuck like this early and not make the score. Now I have time to work on the parts I do not understand, and I want to learn as much as I can and do as much as I can before I turn it in. If I am going to use this for anything in the future I need to learn this sooner or later, for class or not, the way I see it.
It is just frustrating for me to have her on me to spend more time inside, when I know I could, but my principals wont let me.
Thanks for sticking with me Ezzeral. I will get this.

Between late last night and early this morning I have put in about 3 hours on this, and my progress is somewhat disapointing to me. The searches have always given me problem. The code never looks like my brain thinks it should.

The showMessage was easy enough, quick reading and typing had me leaving out a variable there.

JOptionPane.showMessageDialog(null,"No CD Match Found","TryAgain",JOptionPane.INFORMATION_MESSAGE);

Hopefully that will remedy that situation. I am still not sure it is logically in the right place, to run only if a match is not found, but I cannot start testing that until I get the match working.

There is the issue.
I really only partially understand the code for that. I have read and read, and the terms are just not sinking it, the text is all speaking Java, and I still speak dummy.
Two areas still have me scraching my head, if you could explain these variables to me in English, maybe something will click and I can take my next baby step along this path.
First Question, this entire statment. Are these variables, f, e, and s really just generic terms for me to replace with my information, or are they meant to be taken literally?

JTextField f = (JTextField)e.getSource(); 
			final String s = f.getText();

f, is this really just my searchField? I cannot figure out why there is an f there or what it means. I know e.getSource() should be replaced with what I am looking for, ie my cdNameField text, and string s, I cannot figure out what s is supposed to be.
I keep wanting to change it to

JTextField searchField = (jTextField).cdNameField
final String ??? = searchField.getText();

but of course that does not mean anything.

second question is cdEntry.

CdwArtist cdEntry = (CdwArtist)listModel.elementAt(i);

Where did that come from, and why do I need it here?

You can replace "f, e & s" with names you want to use that was just quick example from Ezzaral. He should also remember that even if he is giving small code examples he should use meaningfull names to avoid confusion like now :).
This statement CdwArtist cdEntry = (CdwArtist)listModel.elementAt(i); will retrive info about your CD from the list, starting from first position of list till the end or till it reach searched item. (Side note: Do you realy want to interupt that loop? What if you have more CD titles with searched keyword? Don't they count?)

First Question, this entire statment. Are these variables, f, e, and s really just generic terms for me to replace with my information, or are they meant to be taken literally?

JTextField f = (JTextField)e.getSource(); 
            final String s = f.getText();

f, is this really just my searchField? I cannot figure out why there is an f there or what it means.

Those are variables - from the code that you copied and pasted in from a method that had a parameter "e". The others are defined right there in the method. Rename them whatever you want - they are variables.

I know e.getSource() should be replaced with what I am looking for, ie my cdNameField text, and string s, I cannot figure out what s is supposed to be.
I keep wanting to change it to

JTextField searchField = (jTextField).cdNameField
final String ??? = searchField.getText();

but of course that does not mean anything.

You are correct - that doesn't mean anything. The original code was doing nothing more than defining a String variable (which they called "s"; name it whatever you like) with the contents of a text field, which is the String that you want to search for.

second question is cdEntry.

CdwArtist cdEntry = (CdwArtist)listModel.elementAt(i);

Where did that come from, and why do I need it here?

Well, you do want to check a field on an item in the list, right? To do that you have to have a reference to it, hence the reference.

If stringFromCurrentObject.equalsIgnoreCase(stringYouAreLookingFor) then bMatchFound=true and after the loop you can use that boolean to determine what to do. (Yes, those are just generic fragments of code with names I made up. You have to figure out what really goes there.)

You can replace "f, e & s" with names you want to use that was just quick example from Ezzaral. He should also remember that even if he is giving small code examples he should use meaningfull names to avoid confusion like now :).

Actually those variables came from the code sample he got elsewhere for a CaretListener (shown in first post). I wouldn't use those if I were writing an example myself :)

My appology then :)

My appology then :)

hehe... no worries, there are a lot of code fragments floating around here.

Peter - it will be everything I can do to get through one search here without eating a bullet, at this point I do not want to compound my lack of understanding by making it more difficult.
I think the break should stay for now. ;)

I have never used a Boolean before (this just gets better and better).
Is it absolutley necessary here, easier, or what?

I am trying to make an IF/THEN statement so that the dialogue box only shows up if a match is not found, but it is erroring out as I have it written and the message does not make sense to me.

JTextField f = searchField; 
			final String s = f.getText(); 
			
			SwingUtilities.invokeLater( new Runnable() 
				{ 
				public void run() 
				{ 
				try 
					{ 
					for(int i = 0; i < listModel.getSize(); i++) 
					{ 
					CdwArtist cdEntry = (CdwArtist)listModel.elementAt(i);
         					
					if(cdNameField.getText().equalsIgnoreCase(s)) 
						{ 
						Inventorylist.setSelectedIndex(i); 
						Inventorylist.scrollRectToVisible( Inventorylist.getCellBounds(i,i) );
						// do the stuff below  boolean here
						break;
					else
					JOptionPane.showMessageDialog(null,"No CD Match Found","TryAgain",JOptionPane.INFORMATION_MESSAGE); 
						} 
					} 
				} 
				catch(StringIndexOutOfBoundsException sie) 
				{} 
				} 
				});

error states 'else' without 'if' .... but I see the IF right there??!!

I am reading up on boolean right now trying to learn how to implement it. I know where it goes, I think, and I know it's purpose, just not how to properly code it.

hehe... no worries, there are a lot of code fragments floating around here.

sorry. :$

It is the only way I have found that I can make sense of most of this.
Until I see it down in code, and can see how information flows through what is written, see how the input and output works, then it is just words on the screen.

It is one of the reasons I have such problems with the API I think. I have not seen enough Java to even know how to structure things properly yet, the code frags help with my logic.

I know my stuff is not clean, or probably not even acceptable to most standards with now, but this is the most effective way I have found to learn.

I have never used a Boolean before (this just gets better and better).
Is it absolutley necessary here, easier, or what?

I am trying to make an IF/THEN statement so that the dialogue box only shows up if a match is not found, but it is erroring out as I have it written and the message does not make sense to me.

JTextField f = searchField; 
			final String s = f.getText(); 
			
			SwingUtilities.invokeLater( new Runnable() 
				{ 
				public void run() 
				{ 
				try 
					{ 
					for(int i = 0; i < listModel.getSize(); i++) 
					{ 
					CdwArtist cdEntry = (CdwArtist)listModel.elementAt(i);
         					
					if(cdNameField.getText().equalsIgnoreCase(s)) 
						{ 
						Inventorylist.setSelectedIndex(i); 
						Inventorylist.scrollRectToVisible( Inventorylist.getCellBounds(i,i) );
						// do the stuff below  boolean here
						break;
					else
					JOptionPane.showMessageDialog(null,"No CD Match Found","TryAgain",JOptionPane.INFORMATION_MESSAGE); 
						} 
					} 
				} 
				catch(StringIndexOutOfBoundsException sie) 
				{} 
				} 
				});

error states 'else' without 'if' .... but I see the IF right there??!!

I am reading up on boolean right now trying to learn how to implement it. I know where it goes, I think, and I know it's purpose, just not how to properly code it.

You have your nesting wrong. Your brackets look like this:

(pseudocode)

if
{
else
}

but need to look like:

if
{
}
else
commented: Thanks for trying to help. +1

To be more specific, change:

if(cdNameField.getText().equalsIgnoreCase(s)) 
						{ 
						Inventorylist.setSelectedIndex(i); 
						Inventorylist.scrollRectToVisible( Inventorylist.getCellBounds(i,i) );
						// do the stuff below  boolean here
						break;
					else
					JOptionPane.showMessageDialog(null,"No CD Match Found","TryAgain",JOptionPane.INFORMATION_MESSAGE); 
						}

to:

if(cdNameField.getText().equalsIgnoreCase(s)) 
						{ 
						Inventorylist.setSelectedIndex(i); 
						Inventorylist.scrollRectToVisible( Inventorylist.getCellBounds(i,i) );
						// do the stuff below  boolean here
						break;
					
						}
else
					JOptionPane.showMessageDialog(null,"No CD Match Found","TryAgain",JOptionPane.INFORMATION_MESSAGE);

I don't see why you need a break; statement in there either :-\

sorry. :$

It is the only way I have found that I can make sense of most of this.
Until I see it down in code, and can see how information flows through what is written, see how the input and output works, then it is just words on the screen.

It is one of the reasons I have such problems with the API I think. I have not seen enough Java to even know how to structure things properly yet, the code frags help with my logic.

I know my stuff is not clean, or probably not even acceptable to most standards with now, but this is the most effective way I have found to learn.

That was only in reply to peter's apology :) With all the pieces of code flying around it's easy to see where he might have thought that was my code fragment.

This is kind of neat. (This is the part I like to do, this is where I really learn).
But anyways, I read and read on Boolean, and could not get it coded in correctly, so after almost 2 hours of errors I decided to just do what you see below, which is move the IF TRUE section up into the loop.

I think it works there just as if it would with a Boolean statement. Tell me if I am wrong.

The problem that I am having, is that the search does not return anything 1st off, I have checked and rechecked my variables and from what I understand they look right, but I enter a name into my search field, hit the search button, and it finds no match.

2nd thing, it returns the messagedialog box everytime it checks a record. Which tells me this search executes the entire loop one time for each list element ... how do I make it check the entire list before going to the "else" statement?
or do I have to move my dialog somehow?

here is the latest version of the loop:

JTextField f = searchField; 
			final String s = f.getText(); 
			
			SwingUtilities.invokeLater( new Runnable() 
				{ 
				public void run() 
				{ 
				try 
					{ 
					for(int i = 0; i < listModel.getSize(); i++) 
					{ 
					CdwArtist cdEntry = (CdwArtist)listModel.elementAt(i);
         					
					if(cdNameField.getText().equalsIgnoreCase(s)) 
						{ 
						Inventorylist.setSelectedIndex(i); 
						Inventorylist.scrollRectToVisible( Inventorylist.getCellBounds(i,i) );
						// do the stuff below  boolean here
						CdwArtist newCD = (CdwArtist) listModel.get( currCD );
			
				artistField.setText(newCD.getArtist());
				cdNameField.setText(newCD.getName());	
				itemField.setText(String.valueOf(newCD.getItemno()));
				nstockField.setText(String.valueOf(newCD.getNstock()));
				priceField.setText(formatter.format(newCD.getPrice()));
						}
					else
					   {
					JOptionPane.showMessageDialog(null,"No CD Match Found","TryAgain",JOptionPane.INFORMATION_MESSAGE); 
						} 
					} 
				} 
				catch(StringIndexOutOfBoundsException sie) 
				{} 
				} 
				})

this is a currCD problem ..
nobody answer yet ... let me do some more trouble shooting.
I have discovered if I put a name in the cdname field then I can match it, so that tells me there is nothing there otherwise .... I think

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.