wow. that took about 5 minutes.
I was having such a hard time the other day that I figured there was NO way it could be that easy, so I just dropped it.
That was the same day I came up with
searchField.getText()==cdNameField.getText();
:o)
Thanks again Ez.
no1zson 24 Posting Whiz in Training
no1zson 24 Posting Whiz in Training
My bad. I left that out, but I do have key initialized in cdwartist. key = 1; because I didnt want the first one to be 0.
I did change the names also, does make more sense.
So are you hinting that I could possibly use currCD to set this value, with little change since it is already coded and working?
I thought about trying something like that, when I started looking at putting key++ in my add button code, but was worried about using the same counter for two different things. Thought that might create some kind of problems somewhere.
no1zson 24 Posting Whiz in Training
Thanks Ez.
That is the kind of stuff it would take me a year to learn otherwise.
It also gave me some ideas of things I want to do when I get back off vacation and start cleaning up this whole app.
As always, you are a great help.
no1zson 24 Posting Whiz in Training
This is the last thing I am doing to my app, and I saved the hardest for last. I have been out here all week beating you guys to death with questions, so if I do not get any replies at all I will understand. I do not need this for a grade, I just want to do it, so if I get no help, so be it. I learned alot and appreciate everything.
Now, the task at hand, what I have tried, and where I am stuck. I actually started this two days ago when I almost stopped working on the search part.
I currently have an itemnoField where the user supplies the product number of the cd. I have used it almost as a counter for my tests with NEXT, FIRST, LAST ect by putting in a 1, 2, 3, 4 etc as I created cds.
Well I want to do that now in the app and take it out of the users hand.
Every cd addition I want to make the itemno one larger that the previous last itemno.
Sounded easy until I started. I wanted to do this one correctly, not just shove it in my primary class as I have all the other methods. Here is what I came up with.
I created a new class to house my generator:
public class SimplePrimaryKeyGenerator implements PrimaryKeyGenerator
{
private int key;
public synchronized int give()
{
return key++;
}
public void take() …
no1zson 24 Posting Whiz in Training
Ez-
That is not entirely true. I do not replace any code without thinking it through. The problem for me is that, besides here, I have absolutley NO instruction on how to do any of this. A month ago I did not even know what a method was.
I am taking an online course with lord only knows how many other students, and IF I get a reply back from the instructor on a question, it is two days later.
The extent of this class was to buy a book, read it, and turn in assignments from the syllabus. The instructor graded them, and gave back the "recommended way" of doing it.
So it is not that I am not thinking about what I am doing, I just do not have the tools to put together the correct thought processes yet. I still do not understand how alot of it works together. I understand bits and pieces.
I am trying alot of stuff, and being a troubleshooter, I then simply try to work out the errors to gain a working product.
I know it is not the best way, and out here it is more error than trial, but I really have no other method to learn from right now.
My class is over and done, I have a week to code this app with X number of working methods out of the book to work, I have already surpassed that number ... …
no1zson 24 Posting Whiz in Training
OK, with the fileoutput stream I was able to write the file, but not create the directory.
With the new File statement I am able to create the directory but not write the file.
When I put both in, neither works.
Anyone?
no1zson 24 Posting Whiz in Training
Actually, as I continued to play with it I DID get it to create my data directory by altering this line.
File toWork = new File("C:" + File.separator + "data");
Only problem is that my string now prints to the screen in stead of a file.
no1zson 24 Posting Whiz in Training
I am most confused then, because I am supposed to use exception handling to create the file and directory if they do not exist.
Maybe I will just put up a message if it is not there telling the user to create it manually and then try again.
no1zson 24 Posting Whiz in Training
Something new. It did not error durning compile. good sign. It did not error during test run, another good sign.
It did not create file or directory either though! :D
I have done a lot of wrong stuff out here, but I cannot wait to see how I managed this.
// SAVE
private void btnSaveActionPerformed(ActionEvent evt)
{
File toWork = new File("C:" + File.separator + "data" + File.separator + "inventory.dat");
try
{
if(toWork.exists() == false)// if file and directory do not exist
{
toWork.mkdir();// make directory
toWork.createNewFile(); // create file
System.out.println(listModel); // print list to file
}
if(toWork.canRead()== false)
System.out.println("Read Error.");
if(toWork.canWrite() == false)
System.out.println("Write error.");
}
catch (Exception e){}
}// end SAVE
p.s. I tried the file name both ways, just incase I misunderstood what you told me earlier.
no1zson 24 Posting Whiz in Training
Thanks for the tip on relative and absolute references.
I added to your line with this:
out = new FileOutputStream("C:" + File.separator + "data" + File.separator + "inventory.dat");
In order to get it down one more level into my DATA folder. It works, as long as the data folder is present upon execution.
Can I not make Java create that folder if it is not already present?
no1zson 24 Posting Whiz in Training
After my poor showing yesterday I was ready to quit, but I decided this morning I would rather feel dumb than feel like a quitter, so here I am.
I coded this last night thinking if it worked great, if not then I would just drop it. Well it worked ... kind of.
I want to write my JList to a file on the harddrive, so I created a button that does this, and the file is created just fine, in the same directory as all my classes and java files. Not where I want it. I tried changing the path to a c:\data\ directory, but my method will not put the file there, even if I manually create the directory it will not do it.
private void btnSaveActionPerformed(ActionEvent evt)
{
FileOutputStream out; // declare a file output object
PrintStream p; // declare a print stream object
try
{
// create a new file output stream
// connected to "myfile.txt"
out = new FileOutputStream("inventory.dat");
// connect print stream to the output stream
p = new PrintStream(out);
p.println (listModel);
p.close();
}
catch (Exception e)
{
System.err.println ("Error writing to file");
}
}// end SAVE
Why can I not change location of my output? And if I can, can I make JAVA create the directory for me if it is not already there?
no1zson 24 Posting Whiz in Training
wow. I thought I was so close and I couldn't have been farther off.
My boolean attempts were WAY screwed up!
Changing to cdEntry was something I had played with in one way or another several times, never with any success, but I could have stayed for 100 years the way I was going and would have never even come close on most of it.
You don't know how much I appreciate this. I am feeling a bit dence right now and will probably stay out of here the rest of the night just to go over things and try to improve my future performance. This is all so new, and I think I am just trying too much for not having any more experience than I do ... at the same time, I will never learn if I do not try this stuff.
If it is any consolation, I only have two more methods I am even going to attempt and then I am done until I get back from Mexico in mid August ... so you will done with me for at least that long! :o)
peter_budo commented: Keep up good work. I'm happy to finaly see somebody who wants to learn. +5
no1zson 24 Posting Whiz in Training
I am just flat out busted. I have done everything I can think of, and this is the closest I can get toworking correctly.
If I put the cd name in the search field AND the cdnamefield the search will find it and populate everything like it should.
I do not understand it. The only thing I can think of is that my search is looking in the text field itself, and when a match is made then pulling in that element.
here is the code
//start at first cd
[B]currCD = 0;[/B]
// compare
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);
[B]if(cdNameField.getText().equalsIgnoreCase(s))[/B]
{
Inventorylist.setSelectedIndex(i);
Inventorylist.scrollRectToVisible( Inventorylist.getCellBounds(i,i) );
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)
{}
}
});
I have "tweaked" on the currCD and if lines above to my wits end ... i think therein the problem lies.
Please someone pull me from the depths of despair.
no1zson 24 Posting Whiz in Training
OK, I have figured out what is going on ... I think ... it is not currCD or else it would not check each element and give the dialog box, that tells me it is moving through the list.
If I put the cdname in the cdnamefield also, it finds that cd and populates the fields as it should.
Why would I have to put it in both places? It seems to be searching the field, not the list ... which is what I think it is set to do, but not exactly what I want to do ....
does that rambling make any sense?
no1zson 24 Posting Whiz in Training
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
no1zson 24 Posting Whiz in Training
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 ); …
no1zson 24 Posting Whiz in Training
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.
no1zson 24 Posting Whiz in Training
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.
no1zson 24 Posting Whiz in Training
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 …
no1zson 24 Posting Whiz in Training
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 …
no1zson 24 Posting Whiz in Training
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.
no1zson 24 Posting Whiz in Training
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.
no1zson 24 Posting Whiz in Training
I knew that was too easy.
Where can I find something on how to do that compare?
no1zson 24 Posting Whiz in Training
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()));
}
no1zson 24 Posting Whiz in Training
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.
no1zson 24 Posting Whiz in Training
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?
no1zson 24 Posting Whiz in Training
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 …
no1zson 24 Posting Whiz in Training
That was mynext question! You have helped me so much you know what I am going to ask before I even ask it now!
I have some more buttons to work on, the modify is kicking my butt, but I have a few more things to try before I bring it out here.
Thanks also Peter - I only have a few more things to do to this app, and then I am going to go back through everything and see if I have learned enough to make it better. Things like you have mentioned with my fields and panels, and probably even breaking some of these methods up and stuff like that.
I appreciate the help guys.
no1zson 24 Posting Whiz in Training
wow. that worked. so, setpreferredsize instead of logo.getsize was the answer?
Would you explain why that would make a difference?
no1zson 24 Posting Whiz in Training
I am sorry, I have too many windows open at once, this is the logo.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.BasicStroke;
import java.awt.GradientPaint;
import java.awt.TexturePaint;
import java.awt.Rectangle;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.geom.Arc2D;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class ShapesJPanel extends JPanel
{
// draw cd logo
public void paintComponent( Graphics g )
{
super.paintComponent( g ); // call superclass's paintComponent
Graphics2D g2d = ( Graphics2D ) g; // cast g to Graphics2D
// draw 2D ellipse filled with a blue-yellow gradient
g2d.setPaint( new GradientPaint( 5, 30, Color.BLUE, 35, 100,
Color.WHITE, true ) );
g2d.fill( new Ellipse2D.Double( 5, 30, 65, 100 ) );
// draw 2D rectangle in blue
g2d.setPaint( Color.BLUE );
g2d.setStroke( new BasicStroke( 10.0f ) );
g2d.draw( new Rectangle2D.Double( 1, 25, 75, 110 ) );
} // end method paintComponent
} // end class ShapesJPanel
no1zson 24 Posting Whiz in Training
My bad. Here it is. Pretty simple, but most of my work is.
import javax.swing.JFrame;
public class Shapes
{
// execute application
public static void main( String args[] )
{
// create frame for ShapesJPanel
JFrame frame = new JFrame( "Logo" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
// create ShapesJPanel
ShapesJPanel shapesJPanel = new ShapesJPanel();
frame.add( shapesJPanel ); // add shapesJPanel to frame
frame.setSize( 425, 200 ); // set frame size
frame.setVisible( true ); // display frame
} // end main
} // end class Shapes
no1zson 24 Posting Whiz in Training
Peter ... you are right, and I am trying.
I will give that a shot, hope I do not mess up everything else implimenting it!
Ezzarral, that did not work either. Does not error, does not do anything, and no logo appears when the app opens.
no1zson 24 Posting Whiz in Training
This is what jwenting told me few months back while I had problem with my layout
Meaning, organize your component in groups of fever components, if necessary put them even on their own. Given them requered arrangement, in their own space and then after that put this separate layouts together. It is like building with LEGO.
Fastest solution for you will be to put all your existing components on to JPanel, create separate JPanel for graphic and then add these two JPanels to frame. That is the fastest you can do. Longer, but more satisfying would be doing some arrangements in existing code so it will not requere whole re-do. You have to admit no1zson that current layout is not best solution, specialy without fixed frame size....
I certianly understand it is not the greatest design .. :$ , it was kind of put together on the fly one week at a time, it is my first dont forget.
This logo is the last thing I am adding to it though, so I did not want to redo the entire layout for it. I like your idea about adding my two panels into one new frame, but have no idea how to even start that, and do not want to get in over my head again as I did last week.
Ezzarral - I am displaying it the only way I know how, I just put the code up for you to look at ... but I …
no1zson 24 Posting Whiz in Training
yes. If I implement it in is own panel it shows up fine, although in another panel behind my cd window ... as so ...
// run it
public static void main(String args[])
{
JFrame frame = new JFrame( "CD Inventory Logo" );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
// create ShapesJPanel
ShapesJPanel shapesJPanel = new ShapesJPanel();
frame.add( shapesJPanel ); // add shapesJPanel to frame
frame.setSize( 125, 200 ); // set frame size
frame.setVisible( true ); // display frame
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new Inventory2().setVisible(true);
}
});
}
That is why, like Peter indicates, that maybe it could not be done in an unorganized pane like I have.
no1zson 24 Posting Whiz in Training
That is what I had hoped, and what I tried to impliment yesterday.
Almost exactly. Here is where I slide yours in, witht he same resutls.
Nothing errors, it just does not show up.
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);
[B]// add shapesJPanel to frame
getContentPane().add( new ShapesJPanel() );[/B]
// place textFields and labels
I put it a few different places, before the fields, after the buttons, just seeing if placement would matter, but no matter what I put it nothing happens.
no1zson 24 Posting Whiz in Training
OK, I think I understand. Because I am using Flowlayout, and my items are unorganized I cannot put my graphic in.
I will need to reorganize as you have shown here.
I have a few questions about the code you show.
1st
Does it replace my
getContentPane().setLayout(new FlowLayout())
or run in addition to this, down in my runable replacing
new Inventory2().setVisible(true);
or is it in addition to both and should be placed elsewhere.
2nd
Is this all just generic default code, or is it ready to be used?
I do not know what progress bar, process panel, or rename do for me here.
no1zson 24 Posting Whiz in Training
I do not even know if I can do this, so this may be quick and painless.
I have my existing code, all the fields, buttons, scroll panel and everything else where I need them. Simple FlowLayout is fine for what I am doing.
Yesterday I created this goofy little graphic and went to put it in right next to my buttons. Figured I would just insert it above the buttons and let FlowLayout handle the rest and just stick it where it wanted.
It wouldn't work. The graphic is there, no compile errors, no errors at all in fact, it just does not show up unless I open a separate panel (as I have below in bold).
Can I not stick this little graphic, meant to be like a logo, into my current GUI without having this extra panel open up?
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; …
no1zson 24 Posting Whiz in Training
Maybe you should use a bigger hammer next time! Thanks to both of you for helping me out yet AGAIN!
Promise I will get better eventaully.
I actually read up on the listModel API today without anyone having to yell at me.
no1zson 24 Posting Whiz in Training
Or I could just do this.
if (++currCD >= listModel.size()) currCD= 0;
and not worry about it at all. Is this ugly programming by pro standards?
no1zson 24 Posting Whiz in Training
Which is why I keep pointing out listModel.size(). That is the current number of items in your list. That number -1 is the index of the last item. If your pointer equals the number of items, you have incremented too far and need to wrap back to the index of the first item.
I understand. The mystery to me is the index of the first item.
-1 is last item, but I do not know what to bring it around to once that is reached. T have searched up and down on listmodel but cannot find anything listing those. As a guess I used +1, it did not error on compile, but blows up when running.
if (++currCD > listModel.size()-1) currCD = listModel.size()1;
If I understand what I think I understand, this should work once I get the index of the first element.
no1zson 24 Posting Whiz in Training
What exception? Exception to what? I do not know what that means.
I am still trying to wrap my brain around my NEXT button will go to that lastElement, and then loop back to the first again.
if (++currCD<0) currCD = listModel.size()+1;
does not work. I am not sure how to tell currCD which element number is lastElement. Greater than what is my question?
I am also not sure listModel.size()+1; is correct either.
if (++currCD > listModel.lastElement()) currCD = listModel.size()+1;
Keeps coming from my fingers, but I know currCD and lastElement cannot be compared like that.
no1zson 24 Posting Whiz in Training
oooooooooo. I see.
Then, when I start going the other way, ie the NEXT button, ... hmmm,
I would think it would have to stay -1, as that still means end of the list, but how do I incement up? To what end? I would not know, would I?
if (++currCD>???) currCD = listModel.size()-1;
CdwArtist newCD = (CdwArtist) listModel.get( currCD );
Ok, now you have got me perplexed. This affects also my First and Last records buttons as well.
I will not have to do an IF statement for those two, as I am just going to the first or last record, and the first record I know, so that statement should be easy
currCD = listModel.get()0;
I think,
but for LAST, I do not know what last will be ... any help with this?
no1zson 24 Posting Whiz in Training
My bad, you'll need to use String.valueOf( newCD.getItemno() ) in the setText method for the numeric entries or a DecimalFormat formatter.
Or one of each as the case calls for here. That is great. Thanks for the help.
Can you explain the way the list model size works for me?
if (--currCD<0) currCD = listModel.size()-1;
CdwArtist newCD = (CdwArtist) listModel.get( currCD-- );
I understand if the currCD counter is less than zero, then currCD impliments listModel.size()-1;
What does the -1 refer to? What does that mean?
Right now, it works, "kind of". If I put in 3 cds, and then hit PREV it goes from the 3rd to the 2nd, from the 2nd to the first, and then from the 1st back to the 3rd .... then it just bounces back and forth from the 3rd to the 1st ... it never goes to the second again.
I need to understand what it is doing, because I have a NEXT button to impliment which does exactly the opposite of the PREV, and then a FIRST and LAST button which go to the first and last records respectively and know I will need to use this command again.
no1zson 24 Posting Whiz in Training
You simply call setText() on the textfield with the value from the cd object.
itemField.setText( newCD.getItemno());
makes perfect sense.
when I do it though
artistField.setText(newCD.getArtist());
cdNameField.setText(newCD.getName());
itemField.setText(newCD.getItemno());
nstockField.setText(newCD.getNstock());
priceField.setText(newCD.getPrice())
the old familiar
Inventory2.java:282: setText(java.lang.String) in javax.swing.text.JTextComponent cannot be applied to (int)
Shows up for all three. Possibly something to do with it being a FormattedTextField????
no1zson 24 Posting Whiz in Training
Your parsing problem is clear from the exception message:
[B]Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
[/B]It's trying to parse an int from an empty string. If you look at the code in your previous handler, you have it backward. You want to set the text to the value from the object - not the other way around.
If I understand you, in the ADD I am setting the object to the value of the text field (so that I can do calculations and what not), but now that I am taking that information back from the list, I need to set the text back to the value of the object?
newCD.setItemno(Integer.parseInt(itemField.getText()));
is obviously the way to do number 1.
Will you show me an example of how to put it back?
newCD.setText(Integer.parseInt(getItemno()));
Is what my limited experience tells me, but of course that is wrong.
no1zson 24 Posting Whiz in Training
Well, think about your index in relation to the list. If the decrement puts it past 0 you know what you want the next value to be and listModel has a size() function to help you out.
As I do not know how many elements can be in my JList at any given moment, would something likeFor CurrCD < 0 listModel.Last();
bet a better option?
Either way, I am not sure of the syntax for the actual command.
What is the "return" or "get" command, I guess.
// Grab Previous cd
CdwArtist newCD = (CdwArtist) listModel.get( currCD-- );
For currCD < 0 listModel.size(99);
newCD.setArtist(artistField.getText());
newCD.setName(cdNameField.getText());
just does not look right to me.
Of course it is all mute if I cannot find the problem with the PREV button anyways, cuz it does not work now to begin with! ;)
no1zson 24 Posting Whiz in Training
Peter, here is my first class
import java.util.*;
import java.text.*;
import java.lang.Comparable;
public class Compactdisk implements Comparable
{// begin class
//InventoryCD class has 5 fields
public String name; // Name of cd
public float price; // price of cd
public int itemno; // item number of cd
public int nstock; // how many units in stock
private int i; // cd counter for array
public float value; // value for single cd inventory
//Compact disk class constructor
public Compactdisk()
// 4 fields need to be set up
{
name = "";
price = .00f;
itemno = 0;
nstock = 0;
i = 0;
value = .00f;
}
// set values
public void setName(String diskName)
{
name = diskName;
}
public void setPrice(float cdPrice)
{
price = cdPrice;
}
public void setItemno(int cdItemno)
{
itemno = cdItemno;
}
public void setNstock(int cdStock)
{
nstock = cdStock;
}
public void setValue(float cdValue)
{
value = cdValue;
}
public void seti(int Count)
{
i = Count;
}
// return values
public String getName()
{
return (name);
}
public float getPrice()
{
return (price);
}
public int getItemno()
{
return (itemno);
}
public int getNstock()
{
return (nstock);
}
public int compareTo(Object in)
{
return ((Comparable)name.toLowerCase()).compareTo((Comparable)((Compactdisk)in).getName().toLowerCase());
}
// returns indivudual inventory value for a disk
public float getValue()
{
return (price * nstock);
}
}// end class
And the class that extends it
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.text.*;
import java.lang.*;
public class CdwArtist extends Compactdisk …
no1zson 24 Posting Whiz in Training
Looks like I only made it a day and a half without a new question. I am not sure if that is good or bad.
I have everything just about the way I want it. I am now putting new buttons in to my GUI to manipulate everything put in my JList.
I added all the buttons to the GUI, put the architecture in so that I can just go in, one by one and edit them for functionality.
ADD works fine.
PREV is giving me an issue, and I am not even sure what it is.
I just want it to pull the last cd up so that I can look at it. Populate the given fields for possible modification should I decide to change or update anything.
What I have coded compiles, but after entering several cds, if I hit PREV I get:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:468)
at java.lang.Integer.parseInt(Integer.java:497)
at Inventory2.btnPrevActionPerformed(Inventory2.java:280)
at Inventory2.access$100(Inventory2.java:10)
at Inventory2$2.actionPerformed(Inventory2.java:155)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1849)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2169)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:420)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:258)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:5517)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3135)
at java.awt.Component.processEvent(Component.java:5282)
at java.awt.Container.processEvent(Container.java:1966)
at java.awt.Component.dispatchEventImpl(Component.java:3984)
at java.awt.Container.dispatchEventImpl(Container.java:2024)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4212)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3892)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3822)
at java.awt.Container.dispatchEventImpl(Container.java:2010)
at java.awt.Window.dispatchEventImpl(Window.java:1791)
at java.awt.Component.dispatchEvent(Component.java:3819)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
no1zson 24 Posting Whiz in Training
Even after I turned it in I kept working on it. I did discover one interesting piece of information, you can use html tags to format toString output. <br> being a newline command in html.
public String toString()
{
return "<html>Artist: " + artist +
" CD Name: " + name +
"<br> Item Number: " + itemno +
" Price: " + formatter.format(getPrice()) +
"<br> In Stock: " + nstock +
" Stock Value: " + formatter.format(getValue()) +
"<br> Restocking Fee: $" + restock +
"<br> Total Inventory Value: " + formatter.format(getTotal())+ "</html>";
}
no1zson 24 Posting Whiz in Training
Thanks Peter, but I think that is going to be too little too late. I need to get my project submitted, do not really have the time to try and learn and impliment that.
I do not want to sit here and just beg for code so I am going to close this thread.
Hopefully next week will be a better week.
I appreciate everyones help.