Programming assistance
Hi all,
I need some help hopefully before Sun evening... I have to modify my Inventory program to have an Add, Delete and a search button simple enough.. Well Im new to Java programming and have been limping my way along from day one I have a C+ and need a C- so a little leeway.
Could any one assist me on the easiest way to accomplish the task above even if it is just the search button that I get help with its better then nothing... So My DVDGUI looks like this;
//DVDGUI.java
import java.util.Arrays;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.ImageIcon;
public class DVDGUI extends JFrame
{
//Private Variables
private GridBagLayout layout = new GridBagLayout();
private GridBagConstraints constraints = new GridBagConstraints();
//Private data from prior assignments
private DVD [] dvd;
private int index;
// Labels
private JLabel logoLabel;
private JLabel nameLabel;
private JLabel idLabel;
private JLabel titleLabel;
private JLabel unitsLabel;
private JLabel priceLabel;
private JLabel valueLabel;
private JLabel feeLabel;
private JLabel totalLabel;
// Text Fields for displaying or editing
private JTextField nameText;
private JTextField idText;
private JTextField titleText;
private JTextField unitsText;
private JTextField priceText;
private JTextField valueText;
private JTextField feeText;
private JTextField totalText;
private JTextField searchText;
//Buttons
private JButton firstButton;//To move to first element in the array
private JButton nextButton;//To move to next element in the array
private JButton previousButton; //To again move to next element in the array
private JButton lastButton;//To move again to first element in the array
private JButton addButton;//To add a DVD to array
private JButton deleteButton;//To delete a DVD from array
private JButton modifyButton;//To modify an element
private JButton saveButton;//To save the array
private JButton searchButton;//To search the array
//Constatnts
private final static int LOGO_WIDTH= 4;
private final static int LOGO_HEIGHT= 4;
private final static int LABEL_HEIGHT= 1;
private final static int LABEL_WIDTH= 1;
private final static int TEXT_HEIGHT= 1;
private final static int TEXT_WIDTH= LOGO_WIDTH - LABEL_WIDTH;
private final static int BUTTON_HEIGHT= 1;
private final static int BUTTON_WIDTH= 1;
private final static int LABEL_START_ROW = LOGO_HEIGHT + LABEL_WIDTH + 1;
private final static int LABEL_COLUMN= 0;
private final static int TEXT_START_ROW= LABEL_START_ROW;
private final static int TEXT_COLUMN= LABEL_WIDTH + 1;
private final static int BUTTON_START_ROW = LABEL_START_ROW + 9*LABEL_HEIGHT;
private final static int BUTTON_COLUMN= LABEL_COLUMN;
private final static int SEARCH_START_ROW = BUTTON_START_ROW + 3;
final static String EMPTY_ARRAY_MESSAGE = "Hit ADD to add a new DVD";
//Constants
private final static int FRAME_WIDTH= 325;//460
private final static int FRAME_LENGTH= 350;//343
private final static int FRAME_XLOC= 250;
private final static int FRAME_YLOC= 100;
//Constructors
//Initialization constructor
public DVDGUI( DVD dvdIn[] )
{
//Pass the frame title to JFrame, set the IconImage
super( "DVD Inventory" );
setLayout( layout );
//Copy the input array (dvdIn)
setDVDArray( dvdIn );
//Start the display with the first element of the array
index = 0;
//Build the GUI
buildGUI();
//Values
updateAllTextFields();
}//End constructor DVDGUI
//Methods
//Copy an input DVD array to the GUI's private DVD array variable
private void setDVDArray( DVD dvdIn[] )
{
dvd = new DVD[dvdIn.length];
for(int i = 0;i < dvd.length;i++)
{
//Create a DVD array element from the input array
dvd = new DVD( dvdIn );
/*dvd = new DVD( dvdIn.title(), dvdIn.productNumber(),
dvdIn.productUnitsInStock(), dvdIn.productPrice()
);*/
//System.out.println( dvdIn.toString() );
}//End for
}//End copyArray
//A method for updating each of the GUI fields
private void updateAllTextFields()
{
if ( dvd.length > 0 ) //Then update the JTextField display
{
//Update the product name text field
nameText.setText( dvd[index].productName() );
//Update the product id text field
idText.setText( String.format( "%d", dvd[index].productNumber() ) );
//Update the title text field
titleText.setText( dvd[index].title() );
//Update the units in stock text field
unitsText.setText( String.format( "%d", dvd[index].productUnitsInStock() ) );
//Update the price text field
priceText.setText( String.format( "$%.2f" , dvd[index].productPrice() ));
//Update the stock value text field
valueText.setText( String.format( "$%.2f" , dvd[index].productValue() ));
//Update the restocking fee text field
feeText.setText( String.format( "$%.2f" , dvd[index].restockingFee() ));
//Update the total value text field
totalText.setText( String.format( "$%.2f" , DVD.productValue( dvd ) ));
}//End if
else //Put a special message in the fields
{
//Update the product name text field
nameText.setText( EMPTY_ARRAY_MESSAGE );
//Update the product id text field
idText.setText( EMPTY_ARRAY_MESSAGE );
//Update the title text field
titleText.setText( EMPTY_ARRAY_MESSAGE );
//Update the units in stock text field
unitsText.setText( EMPTY_ARRAY_MESSAGE );
//Update the price text field
priceText.setText( EMPTY_ARRAY_MESSAGE );
//Update the stock value text field
valueText.setText( EMPTY_ARRAY_MESSAGE );
//Update the restocking fee text field
feeText.setText( EMPTY_ARRAY_MESSAGE );
//Update the total value text field
totalText.setText( EMPTY_ARRAY_MESSAGE );
}//End else
}//End updateAllTextFields
//Set the appropriate fields editable or uneditable
private void setModifiableTextFieldsEnabled( Boolean state )
{
//The DVD ID, title, units in stock, and price can all be set editable or uneditable
idText.setEditable( state );
titleText.setEditable( state );
unitsText.setEditable( state );
priceText.setEditable( state );
}//End setModifiableTextFieldsEnabled
//Button Handler Class - Handling Methods
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if( event.getSource() == firstButton ) //First is pressed
{
handleFirstButton();
}//End if
else if( event.getSource() == previousButton ) //Previous is pressed
{
handlePreviousButton();
}//End else if
else if( event.getSource() == nextButton ) //Next button is pressed
{
handleNextButton();
}//End else if
else if( event.getSource() == lastButton ) //Last button is pressed
{
handleLastButton();
}//End else if
else if (event.getSource() == firstButton)
{
handleFirstButton();
}//end else if
}//End method actionPerformed
}//End class ButtonHandler
//Display the first element of the DVD array
private void handleFirstButton()
{
//Set the index to the first element in the array
index = 0;
//Update and disable modification
updateAllTextFields();
setModifiableTextFieldsEnabled( false );
}//End method handleFirstButton
//Display the next element of the DVD array or wrap to the first
private void handleNextButton()
{
//Increment the index
index++;
//If index exceeds the last valid array element, wrap around to the first element of the array
if ( index > dvd.length - 1 )
{
index = 0;
}//End if
//Update and disable modification
updateAllTextFields();
setModifiableTextFieldsEnabled( false );
}//End method handleNextButton
private void handlePreviousButton()
{
index--;
if ( index < 0)
{
index = dvd.length - 1;
}// End if
//Update and disable modification
updateAllTextFields();
setModifiableTextFieldsEnabled( false );
}//End method handlePreviousButton
private void handleLastButton()
{
index--;
if ( index < dvd.length - 1 )
{
index = 2;
}//End if
//Update and disable modification
updateAllTextFields();
setModifiableTextFieldsEnabled( false );
}//End method handleLastButton
//TextField Handler Class - Handling Methods
//The class for handling the events for the buttons
//NOTE: You don't need this for Week Eight, but I'm including it for motivation on Week
//Nine's assignment
//Hope you dont mind me leaving thin in there
private class TextFieldHandler implements ActionListener
{
public void actionPerformed( ActionEvent event )
{
//User pressed Enter in JTextField titleText
if ( event.getSource() == idText )
{
//handleIdTextField();
}//End if
//User pressed Enter in JTextField titleText
else if ( event.getSource() == titleText )
{
//handleTitleTextField();
}//End else if
//User pressed Enter in JTextField unitsText
else if ( event.getSource() == unitsText )
{
//handleUnitsTextField();
}//End else if
//User pressed Enter in JTextField priceText
else if ( event.getSource() == priceText )
{
//handlePriceTextField();
}//End else if
//User pressed Enter in JTextField searchText
else if ( event.getSource() == searchText )
{
//handleSearchButtonOrTextField();
}//End else if
}//End method actionPerformed
}//End inner class TextFieldHandler
//GUI Methods
//Build GUI
private void buildGUI()
{
//Add the logo
buildLogo();
//Add the text fields and their labels
buildLabels();
buildTextFields();
//Add the navigation and other buttons
buildMainButtons();
//Give some values to the fields
updateAllTextFields();
//Set some of the frame properties
setSize( FRAME_LENGTH , FRAME_WIDTH );
setLocation( FRAME_XLOC , FRAME_YLOC );
setResizable( false );
//pack();
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setVisible( true );
}//End buildGUI()
//Add the logo to the JFrame
private void buildLogo()
{
constraints.weightx = 2;
constraints.weighty = 1;
logoLabel = new JLabel( new ImageIcon( "shamrock.jpg" ) );
logoLabel.setText( "Lucky DVDs" );
constraints.fill = GridBagConstraints.BOTH;
addToGridBag( logoLabel, 2, 2, LOGO_WIDTH, LOGO_HEIGHT );
//Create a vertical space
addToGridBag( new JLabel( "" ), LOGO_HEIGHT + 1, 0, LOGO_WIDTH, LABEL_WIDTH );
}//End method buildLogo
//Build just the panel containing the text
private void buildLabels()
{
//Variables (for readability)
int row= 0;
int column= 0;
int width= 0;
int height= 0;
column = LABEL_COLUMN;
width = LABEL_WIDTH;
height = LABEL_HEIGHT;
constraints.weightx = 1;
constraints.weighty = 0;
constraints.fill = GridBagConstraints.BOTH;
//Create the name label and name text field
nameLabel = new JLabel( "Product: " );
nameLabel.setLabelFor( nameText );
row= LABEL_START_ROW;
addToGridBag( nameLabel, row, column, width, height);
//Create the id label and id text field
idLabel = new JLabel( "Product Id: " );
idLabel.setLabelFor( idText );
row+= LABEL_HEIGHT;
addToGridBag( idLabel, row, column, width, height);
//Create the DVD title label and DVD title text field
titleLabel = new JLabel( "Title: " );
titleLabel.setLabelFor( titleText );
row+= LABEL_HEIGHT;
addToGridBag( titleLabel, row, column, width, height);
//Create the units in stock label and units in stock text field
unitsLabel = new JLabel( "Units in Stock: " );
unitsLabel.setLabelFor( unitsText );
row+= LABEL_HEIGHT;
addToGridBag( unitsLabel, row, column, width, height);
//Create the price label and price text field
priceLabel = new JLabel( "Unit Price:" );
priceLabel.setLabelFor( priceText );
row+= LABEL_HEIGHT;
addToGridBag( priceLabel, row, column, width, height);
//Create the value label and value text field
valueLabel = new JLabel( "Product Value:" );
valueLabel.setLabelFor( valueText );
row+= LABEL_HEIGHT;
addToGridBag( valueLabel, row, column, width, height);
//Create the fee label and fee text field
feeLabel = new JLabel( "Restocking fee:" );
feeLabel.setLabelFor( feeText );
row+= LABEL_HEIGHT;
addToGridBag( feeLabel, row, column, width, height);
//Create a vertical space
row+= LABEL_HEIGHT;
addToGridBag( new JLabel( "" ), row, column, width, height );
//Create the total value label and total value text field
totalLabel = new JLabel( "Inventory Value:" );
totalLabel.setLabelFor( totalText );
row+= LABEL_HEIGHT;
addToGridBag( totalLabel, row, column, width, height);
}//End method buildLabels()
//Build containing textFields
private void buildTextFields()
{
//Variables
int row= 0;
int column= 0;
int width= 0;
int height= 0;
column = TEXT_COLUMN;
width = TEXT_WIDTH;
height = TEXT_HEIGHT;
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1;
TextFieldHandler handler = new TextFieldHandler();
nameText = new JTextField( "DVD" );
nameText.setEditable( false );
row = TEXT_START_ROW;
addToGridBag( nameText, row , column, width, height );
idText = new JTextField( "" );
idText.setEditable( false );
row += TEXT_HEIGHT;
addToGridBag( idText, row , column, width, height );
titleText = new JTextField( " " );
titleText.addActionListener( handler );
titleText.setEditable( false );
row += TEXT_HEIGHT;
addToGridBag( titleText, row , column, width, height );
unitsText = new JTextField( " " );
unitsText.addActionListener( handler );
unitsText.setEditable( false );
row += TEXT_HEIGHT;
addToGridBag( unitsText, row , column, width, height );
priceText = new JTextField( " " );
priceText.addActionListener( handler );
priceText.setEditable( false );
row += TEXT_HEIGHT;
addToGridBag( priceText, row , column, width, height );
valueText = new JTextField( " " );
valueText.setEditable( false );
row += TEXT_HEIGHT;
addToGridBag( valueText, row , column, width, height );
feeText = new JTextField( " " );
feeText.setEditable( false );
row += TEXT_HEIGHT;
addToGridBag( feeText, row , column, width, height );
//Create a vertical space
row+= TEXT_HEIGHT;
addToGridBag( new JLabel( " " ), row, column, width, height );
totalText = new JTextField( "" );
totalText.setEditable( false );
row += TEXT_HEIGHT;
addToGridBag( totalText, row , column, width, height );
}//End method buildTextFields
//Add the main buttons to the frame
private void buildMainButtons()
{
//Variables
int row= 0;
int column= 0;
int width= 0;
int height= 0;
row = BUTTON_START_ROW;
column = BUTTON_COLUMN;
width = BUTTON_WIDTH;
height = BUTTON_HEIGHT;
constraints.weightx = 1;
constraints.weighty = 0;
//constraints.fill = GridBagConstraints.HORIZONTAL;
ButtonHandler handler = new ButtonHandler();
//Create a vertical space
addToGridBag( new JLabel( "" ), row, 0, LOGO_WIDTH, LABEL_HEIGHT );
firstButton= new JButton( "First" );
firstButton.addActionListener( handler );
row += LABEL_HEIGHT;
addToGridBag( firstButton, row, column, width, height );
previousButton= new JButton( "Previous" );
previousButton.addActionListener( handler );
column += BUTTON_WIDTH;
addToGridBag( previousButton, row, column, width, height );
nextButton= new JButton( "Next" );
nextButton.addActionListener( handler );
column += BUTTON_WIDTH;
addToGridBag( nextButton, row, column, width, height );
lastButton= new JButton( "Last" );
lastButton.addActionListener( handler );
column += BUTTON_WIDTH;
addToGridBag( lastButton, row, column, width, height );
}//End method buildMainButtons
//Add a component to the grid bag
// See Chapter 22, pp 1037 - 1046, Deital & Deital
private void addToGridBag( Component component, int row, int column, int width, int height )
{
//Set the upper-left corner of the component (gridx, gridy)
constraints.gridx = column;
constraints.gridy = row;
//Set the number of rows and columns the componenet occupies
constraints.gridwidth = width;
constraints.gridheight = height;
//Set the constraints
layout.setConstraints( component, constraints );
//Add the component to the JFrame
add( component );
}//End method addToGridBag
} //End class DVDGUI
Another thing is I have no idea where in this big list of code I need to write more code in order for the buttons to work. I was able to add buttons but they did nothing so I took them out. If anyone can help out that would be fantastic, if not its cool I will just do the best I can and get a second job to repay to take the class again :) No pressure right! Also please know Im not trying to have you all do my work, I just need guidence on where in this mess of text where I need to add more text.
Thanks!
Message was edited by: Me
Greenbeer4me
A suggestion: No one is going to want to read your unformated code, especially code that is that long. If you want to increase the chance that someone might read it and critique it, make the code readable with code tags. You can find info on this [url=http://forum.java.sun.com/help.jspa?sec=formatting]here[/url]. It's probably a good idea to repost the code once you figure this out.
Another suggestion: The more specific your question, the more specific (and helpful) the answer.
A 3rd suggestion: the more work you do on your own, the more effort you put into your program, the better folks in here will be inclined to help you. They've already been through programming 101, they've already had to do their own homework, and they are probably not going to want to do yours or anyone else's be they have a c- or an a+. It's your work, we can suggest changes , but you must do the work.
Good luck!
Also, are you missing a class called "DVD"?
Message was edited by:
petes1234
I agree with petes. even if the code is formatted i will not take a chance to read it.
1) Whenever you need to add, delete or search you need to use some kind of datastructure like arraylist, Map, HashMap,etc..
2) if you are just using arrays then i have two words for you. Good Luck
3) I will post an example in just a little while so that you can have a little idea. remember i am not good in swing.
i will post back.
Petes1234? whats going on?
> Petes1234? whats going on?I was trying to read through this code in my Eclipse.... not easy.Thanks for your good comments. Hopefully the OP will take them to heart./Pete
> Another thing is I have no idea where in this big
> list of code I need to write more code in order for
> the buttons to work.
That's a red flag right there that things are getting too big, too out of hand to maintain. I have a feeling that you have to refactor this huge beast into smaller more manageble chunks. If you don't know how to manage this thing, and you are the one who created it, imagine how we feel.
> That's a red flag right there that things are getting
> too big, too out of hand to maintain. I have a
> feeling that you have to refactor this huge beast
> into smaller more manageble chunks. If you don't
> know how to manage this thing, and you are the one
> who created it, imagine how we feel.
Yea, listen to him, about 6 months ago I wrote a 2d game in java, about 2 k lines of code. Absolutely no comments, used only 3 classes, and right now I can't make heads or toes out of it.
Bogada at 2007-7-12 18:28:58 >

the OP dont care. I think he would be better of he have a seperate class Dvdrental and should have all the getter, setter methods.
After that a class which holds arraylist or map in which he can have add, delete, search method. i can do that all in no time but swing is my problem o well i just wanted to do this exercise for my sake.
Brb
Agree.... as I was looking over the code, I wrote:
.....
Other suggestions:
1) in your DVD class, getters should start with getXXXX. For example you should have a method "getProductName()", not "productName()".
2) If I were doing this project, I wouldn't keep my collection of DVD's together with the DVD class. I'd have a separate class for the collection that had add, delete, and search functionality.
..........
but you already said it. So they must be good ideas!
By the way, the OP doesn't need Swing help -- I think he can throw buttons where he wants to -- rather he needs program design and functionality help, both of which have little to do with Swing.
As far as the code goes, this is the first I have asked for help out side of class and its the last week so Ive managed. Also I do have the DVD, Inventory, and Product programs.
When it comes to questions I dont know really what to ask since Im new to all this.
I need to use a copy array for my Add and Delete I just dont know exactly how or where I need to put it or if I just need to alter the copy array I have already. Make sence? If not dont worry about replying I think Ive wasted enough of your time.
Thanks
DvdRental class
public class DvdRental {
private String title;
private int units;
private double price;
private String advisory;
public DvdRental(String title, int units, double price
, String advisory) {
this.title = title;
this.units = units;
this.price = price;
this.advisory = advisory;
}
public void setTitle(String dvdTitle) {
title = dvdTitle;
}
public void setUnits(int dvdUnits) {
units = dvdUnits;
}
public void setPrice(double dvdPrice) {
price = dvdPrice;
}
public void setAdvisory(String dvdAdvisory) {
advisory = dvdAdvisory;
}
public String getTitle() {
return title;
}
public int getUnits() {
return units;
}
public double getPrice() {
return price;
}
public String getAdvisory() {
return advisory;
}
}
DvdList class
import java.util.*;
import javax.swing.*;
public class DvdList extends AbstractListModel{
private SortedSet model;
public DvdList() {
model = new TreeSet();
}
public void add(DvdRental b) {
model.add(b);
fireContentsChanged(this,0,getSize());
}
public void remove(DvdRental b) {
model.remove(b);
fireContentsChanged(this,0,getSize());
}
public int getSize() {
return model.size();
}
public Object getElementAt(int index) {
return model.toArray()[index];
}
public void clear() {
model.clear();
}
public boolean contains(Object element) {
return model.contains(element);
}
public DvdRental find(String title) {
for(DvdRental a : model) {
if(a.getTitle().equals(title))
return a;
}
return null;
}
}
Now the swing part is left
> DvdRental class
> > public class DvdRental {
> private String title;
>................ }
> }
>
>
> Now the swing part is left
fastmike, please don't just give out code. Nudge him with suggestions on what to do, but don't spoon feed. Otherwise he will be encouraged to be lazy and post requirements rather than do his own work, and you run the risk of looking like a Duke Stars wh髍e.
Just my 2 Shekels.
I have noticed in the last 9 weeks how many diffrent ways the same type of Java coding can be written, why? My text has one way, then my instructor suggest how he would or could write, this makes learning Java so much more confusing. I love computers but I have to say programming is not my thing. I admire those of you who can sit down and write out code and create something usefull!
Dont worry this is my last week, well sunday is my last day of class I cant get lazy that fast. I do actually want to learn and understand why it is what it is but reading the text we have is hard to understand.
> As far as the code goes, this is the first I have
> asked for help out side of class and its the last
> week so Ive managed. Also I do have the DVD,
> Inventory, and Product programs.
>
> When it comes to questions I dont know really what to
> ask since Im new to all this.
>
> I need to use a copy array for my Add and Delete I
> just dont know exactly how or where I need to put it
> or if I just need to alter the copy array I have
> already. Make sence? If not dont worry about replying
> I think Ive wasted enough of your time.
>
> Thanks
You need some type of DvdCollection class, perhaps like fastmike's but better to have in your own voice. In it you will probably have a private List<DVD> of your dvd's and public getters and setters including your Add and Delete. Study the List and ArrayList Java classes and you will see how to do this.
> I have noticed in the last 9 weeks how many diffrent
> ways the same type of Java coding can be written,
> why?
Why? That's the beauty of programming. So many choices to choose from, some elegant, some not so. If there were only one way to do this, we'd have it all automated by now. The more different ways you learn with their relative strengths and weaknesses, the better coder you become.
By the way you don't need to provide the actual code just an explanation where in the program it needs to go and why. I want to understand the reasoning on why it is needed or the purpose it serves. For example in order to get the DVD information from DVDGUI, it needs to be linked with the Inventory program.. Something like that I want to understand why something is done...
Do you want me to post the DVD code I have? Ill post everything if you want to see in my own words.
I have to use JEdit and its line numbers otherwise I get a headache!
Let me ask you this, can you have multiple DVD classes that then get called upon by one main program and is that the reasoning behind the copy array? To index multiple items?
> Let me ask you this, can you have multiple DVD
> classes that then get called upon by one main program
> and is that the reasoning behind the copy array? To
> index multiple items?
I'm not sure what y ou are getting at here. You probably will only have one Dvd class but you will have multiple dvd instances. They will probably be placed into a single dvdCollection of some sort (ArrayList is what I recommend, treeSet is what the other poster recommended). Do not use an array of Dvd's (DVD[ ]) as it would be much more difficult to implement when compared to a flexible java collection. Read up on collections at the sun java tutorials.
> By the way you don't need to provide the actual code
> just an explanation where in the program it needs to
> go and why. I want to understand the reasoning on why
> it is needed or the purpose it serves. For example in
> order to get the DVD information from DVDGUI, it
> needs to be linked with the Inventory program..
> Something like that I want to understand why
> something is done...
Inventory program? what does this do?
Sure go ahead and post all your classes, but if you do, please use code tags (see my first response for a helpful link).
some people learn by reading other people code and some people dont. there are no duke dollars offered in this thread. i am just doing it for fun. actually dukes stars are piece of ****. First i did care but later on its worthless.
> some people learn by reading other people code and
> some people dont. there are no duke dollars offered
> in this thread. i am just doing it for fun. actually
> dukes stars are piece of ****. First i did care but
> later on its worthless.
We're all very impressed with how well you write code, but no, people are not going to learn by just reading it. Go ahead and post sample code that shows the concept such as contained in the Sun Java tutorials, but don't code exactly to the spec. Again, all that does is spoon-feed and does not teach. The OP's have to go through the creative process themselves.
Allrite pete. i stop :--). The OP disappeared without a trace. anyways let me ask you a question pete how long have you been coding in java?
> Allrite pete. i stop :--). The OP disappeared without> a trace. anyways let me ask you a question pete how> long have you been coding in java?not long. Only about 6 months. I'm not that good yet, but I'm working on it. Why?
i saw your previous post in swing and some dealing with collections framework. You catch things pretty quick and you can code very good. 6 months wow it took me way more than that and still learning.what books or refrences do you use?
> i saw your previous post in swing and some dealing
> with collections framework. You catch things pretty
> quick and you can code very good. 6 months wow it
> took me way more than that and still learning.
>
> what books or refrences do you use?
You are kind, but I have a way to go before I reach your level. I have just standard reference texts and online references. I was working as a hobbiest in c# a bit but then switched over to Java when my son had to take a Java course at college. and you?
> You are kind, but I have a way to go before I reach
> your level. I have just standard reference texts and
> online references. I was working as a hobbiest in c#
> a bit but then switched over to Java when my son had
> to take a Java course at college. and you?
Well you really can code good. in 6 months you have catched alot. half of the time you are in the forums. these forums will teach you alot specially camickr post in swing. he is the master of swing.
i hate C++. i hate pointers. i was never a good programmer while i was taking classes for C++. my college where i graduated from focus on C++ more than Java, but when i took my first java class i was so impressed that i dont even have words. i bought tons of book. actually i got 9 books just on core java. every book has its own taste and will teach you their own style of coding. I asked my instructor that if its possible for me to code in java for all of my C++ class? he said yes.
Now learning j2ee, jsp, servlets is my new task. lets see what happens. i have learned swing just by myself that is why i am not good. I have recently graduated and looking for a job. Lets hope for the best what happens. you working?
> i hate C++. i hate pointers. i was never a good
> programmer while i was taking classes for C++. my
> college where i graduated from focus on C++ more than
> Java, but when i took my first java class i was so
> impressed that i dont even have words. i bought tons
> of book. actually i got 9 books just on core java.
> every book has its own taste and will teach you their
> own style of coding. I asked my instructor that if
> its possible for me to code in java for all of my C++
> class? he said yes.
>
> Now learning j2ee, jsp, servlets is my new task. lets
> see what happens. i have learned swing just by myself
> that is why i am not good. I have recently graduated
> and looking for a job. Lets hope for the best what
> happens. you working?
Yes, I'm working. As implied previously, I'm a hobbiest programmer, and as such will never be guru like camikr and the other gods here. I am a practicing physician, a gastroenterologist to be exact, who uses coding for creative outlet and to make utilities for my work.
Son you are doing a good job ;--). Now let me complete this swing program. looks like the OP is never coming back hehe
ok OP if you ever come back try to learn from this code. try to make some changes and if you have any problem post back. i am sure if you give the same assignment to your teacher. you will get 0. its better to analyze the code understand and make it work to your prespective.
DvdRental class
public class DvdRental {
private String title;
private int units;
private double price;
private String advisory;
public DvdRental(String title, int units, double price
, String advisory) {
this.title = title;
this.units = units;
this.price = price;
this.advisory = advisory;
}
public DvdRental() {
}
public void setTitle(String dvdTitle) {
title = dvdTitle;
}
public void setUnits(int dvdUnits) {
units = dvdUnits;
}
public void setPrice(double dvdPrice) {
price = dvdPrice;
}
public void setAdvisory(String dvdAdvisory) {
advisory = dvdAdvisory;
}
public String getTitle() {
return title;
}
public int getUnits() {
return units;
}
public double getPrice() {
return price;
}
public String getAdvisory() {
return advisory;
}
public String toString() {
return "\t" + getTitle() + "\t" + getUnits() + " \t" + getPrice() + " \t" + getAdvisory() ;
}
}
DvdList class
import java.util.*;
import javax.swing.*;
public class DvdList extends AbstractListModel
implements MutableComboBoxModel{
/**
*
*/
//private static final long serialVersionUID = 1L;
private List<DvdRental>model;
private Object selectedItem;
public DvdList() {
model = new ArrayList<DvdRental>();
}
public void insertElementAt(Object element, int index) {
model.add(index, (DvdRental) element);
fireIntervalAdded(this, index, index);
}
public void removeElement(Object element) {
// Find out position
int index = model.indexOf(element);
if (index != -1) {
model.remove(element);
fireIntervalRemoved(this, index, index);
}
}
public void addElement(Object element) {
model.add((DvdRental) element);
int length = getSize();
fireIntervalAdded(this,length-1,length-1);
}
public void removeElementAt(int index) {
if(getSize() > index) {
model.remove(index);
fireIntervalRemoved(this, index, index);
}
}
public Iterator iterator() {
return model.iterator();
}
public Object getSelectedItem() {
return selectedItem;
}
public void setSelectedItem(Object newValue) {
selectedItem = newValue;
}
public int getSize() {
return model.size();
}
public Object getElementAt(int index) {
return model.toArray()[index];
}
public void clear() {
model.clear();
}
public boolean contains(Object element) {
return model.contains(element);
}
public DvdRental find(String title) {
for(DvdRental a : model) {
if(a.getTitle().equals(title))
return a;
}
return null;
}
}
DvdExample class
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
public class DvdExample extends JFrame{
private static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 350;
private JButton addButton;
private JButton clearButton;
private JButton printButton;
private JButton removeButton;
private JPanel buttonPanel;
private JLabel title;
private JLabel unit;
private JLabel price;
private JLabel advisory;
private JList list;
private JScrollPane scrollPane;
private JPanel textPanel;
public static void main(String[] args) {
DvdExample frame = new DvdExample();
frame.setVisible(true);
}
public DvdExample() {
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setTitle("WellCome to The Freakin Store");
Container contentPane = getContentPane();
final DvdList dvd = new DvdList();
final DvdRental d = new DvdRental();
list = new JList(dvd);
textPanel = new JPanel(new GridLayout(4,2));
scrollPane = new JScrollPane(list);
scrollPane.setBorder(BorderFactory.createLineBorder(Color.RED));
contentPane.add(scrollPane, BorderLayout.CENTER);
buttonPanel = new JPanel(new GridLayout(2,2));
addButton = new JButton("Add");
clearButton = new JButton("clear");
printButton = new JButton("Print");
removeButton = new JButton("RmvFirst");
title = new JLabel("Title");
unit = new JLabel("unit");
price = new JLabel("price");
advisory = new JLabel("advisory");
final JTextField f1 = new JTextField(5);
final JTextField f2 = new JTextField(5);
final JTextField f3 = new JTextField(5);
final JTextField f4 = new JTextField(5);
textPanel.add(title);
textPanel.add(f1);
textPanel.add(unit);
textPanel.add(f2);
textPanel.add(price);
textPanel.add(f3);
textPanel.add(advisory);
textPanel.add(f4);
addButton.setBackground(Color.magenta);
clearButton.setBackground(Color.magenta);
printButton.setBackground(Color.magenta);
removeButton.setBackground(Color.magenta);
buttonPanel.setBackground(new Color(201,178,96));
buttonPanel.add(addButton);
buttonPanel.add(clearButton);
buttonPanel.add(printButton);
buttonPanel.add(removeButton);
contentPane.add(buttonPanel,BorderLayout.SOUTH);
contentPane.add(textPanel,BorderLayout.NORTH);
ActionListener clearAction = new ActionListener() {
public void actionPerformed(ActionEvent event) {
dvd.clear();
};
};
clearButton.addActionListener(clearAction);
ActionListener addAction = new ActionListener() {
public void actionPerformed(ActionEvent event) {
String title1 = f1.getText().trim();
int unit1 = Integer.parseInt(f2.getText().trim());
double price1 = Double.parseDouble(f3.getText().trim());
String advisory1 = f4.getText().trim();
dvd.addElement(new DvdRental(title1, unit1, price1, advisory1));
};
};
addButton.addActionListener(addAction);
ActionListener printListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Iterator iterator = dvd.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
};
};
printButton.addActionListener(printListener);
ActionListener removeFirstListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String s = JOptionPane.showInputDialog("Enter the title to delete");
Object first = dvd.find(s);
dvd.removeElement(first);
};
};
removeButton.addActionListener(removeFirstListener);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Hope this helps.
Here is my DVDGUI;
//DVDGUI.java
import java.util.Arrays;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.ImageIcon;
public class DVDGUI extends JFrame
{
//Private Variables
private GridBagLayout layout = new GridBagLayout();
private GridBagConstraints constraints = new GridBagConstraints();
//Private data from prior assignments
private DVD [] dvd;
private int index;
// Labels
private JLabel logoLabel;
private JLabel nameLabel;
private JLabel idLabel;
private JLabel titleLabel;
private JLabel unitsLabel;
private JLabel priceLabel;
private JLabel valueLabel;
private JLabel feeLabel;
private JLabel totalLabel;
// Text Fields for displaying or editing
private JTextField nameText;
private JTextField idText;
private JTextField titleText;
private JTextField unitsText;
private JTextField priceText;
private JTextField valueText;
private JTextField feeText;
private JTextField totalText;
private JTextField searchText;
//Buttons
private JButton firstButton;//To move to first element in the array
private JButton nextButton;//To move to next element in the array
private JButton previousButton; //To again move to next element in the array
private JButton lastButton;//To move again to first element in the array
private JButton addButton;//To add a DVD to array
private JButton deleteButton;//To delete a DVD from array
private JButton modifyButton;//To modify an element
private JButton saveButton;//To save the array
private JButton searchButton;//To search the array
//Constatnts
private final static int LOGO_WIDTH= 4;
private final static int LOGO_HEIGHT= 4;
private final static int LABEL_HEIGHT= 1;
private final static int LABEL_WIDTH= 1;
private final static int TEXT_HEIGHT= 1;
private final static int TEXT_WIDTH= LOGO_WIDTH - LABEL_WIDTH;
private final static int BUTTON_HEIGHT= 1;
private final static int BUTTON_WIDTH= 1;
private final static int LABEL_START_ROW = LOGO_HEIGHT + LABEL_WIDTH + 1;
private final static int LABEL_COLUMN= 0;
private final static int TEXT_START_ROW= LABEL_START_ROW;
private final static int TEXT_COLUMN= LABEL_WIDTH + 1;
private final static int BUTTON_START_ROW = LABEL_START_ROW + 9*LABEL_HEIGHT;
private final static int BUTTON_COLUMN= LABEL_COLUMN;
private final static int SEARCH_START_ROW = BUTTON_START_ROW + 3;
final static String EMPTY_ARRAY_MESSAGE = "Hit ADD to add a new DVD";
//Constants
private final static int FRAME_WIDTH= 325;//460
private final static int FRAME_LENGTH= 350;//343
private final static int FRAME_XLOC= 250;
private final static int FRAME_YLOC= 100;
//Constructors
//Initialization constructor
public DVDGUI( DVD dvdIn[] )
{
//Pass the frame title to JFrame, set the IconImage
super( "DVD Inventory" );
setLayout( layout );
//Copy the input array (dvdIn)
setDVDArray( dvdIn );
//Start the display with the first element of the array
index = 0;
//Build the GUI
buildGUI();
//Values
updateAllTextFields();
}//End constructor DVDGUI
//Methods
//Copy an input DVD array to the GUI's private DVD array variable
private void setDVDArray( DVD dvdIn[] )
{
dvd = new DVD[dvdIn.length];
for(int i = 0;i < dvd.length;i++)
{
//Create a DVD array element from the input array
dvd[i] = new DVD( dvdIn[i] );
/*dvd[i] = new DVD( dvdIn[i].title(), dvdIn[i].productNumber(),
dvdIn[i].productUnitsInStock(), dvdIn[i].productPrice()
);*/
//System.out.println( dvdIn[i].toString() );
}//End for
}//End copyArray
//A method for updating each of the GUI fields
private void updateAllTextFields()
{
if ( dvd.length > 0 ) //Then update the JTextField display
{
//Update the product name text field
nameText.setText( dvd[index].productName() );
//Update the product id text field
idText.setText( String.format( "%d", dvd[index].productNumber() ) );
//Update the title text field
titleText.setText( dvd[index].title() );
//Update the units in stock text field
unitsText.setText( String.format( "%d", dvd[index].productUnitsInStock() ) );
//Update the price text field
priceText.setText( String.format( "$%.2f" , dvd[index].productPrice() ));
//Update the stock value text field
valueText.setText( String.format( "$%.2f" , dvd[index].productValue() ));
//Update the restocking fee text field
feeText.setText( String.format( "$%.2f" , dvd[index].restockingFee() ));
//Update the total value text field
totalText.setText( String.format( "$%.2f" , DVD.productValue( dvd ) ));
}//End if
else //Put a special message in the fields
{
//Update the product name text field
nameText.setText( EMPTY_ARRAY_MESSAGE );
//Update the product id text field
idText.setText( EMPTY_ARRAY_MESSAGE );
//Update the title text field
titleText.setText( EMPTY_ARRAY_MESSAGE );
//Update the units in stock text field
unitsText.setText( EMPTY_ARRAY_MESSAGE );
//Update the price text field
priceText.setText( EMPTY_ARRAY_MESSAGE );
//Update the stock value text field
valueText.setText( EMPTY_ARRAY_MESSAGE );
//Update the restocking fee text field
feeText.setText( EMPTY_ARRAY_MESSAGE );
//Update the total value text field
totalText.setText( EMPTY_ARRAY_MESSAGE );
}//End else
}//End updateAllTextFields
//Set the appropriate fields editable or uneditable
private void setModifiableTextFieldsEnabled( Boolean state )
{
//The DVD ID, title, units in stock, and price can all be set editable or uneditable
idText.setEditable( state );
titleText.setEditable( state );
unitsText.setEditable( state );
priceText.setEditable( state );
}//End setModifiableTextFieldsEnabled
//Button Handler Class - Handling Methods
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if( event.getSource() == firstButton ) //First is pressed
{
handleFirstButton();
}//End if
else if( event.getSource() == previousButton ) //Previous is pressed
{
handlePreviousButton();
}//End else if
else if( event.getSource() == nextButton ) //Next button is pressed
{
handleNextButton();
}//End else if
else if( event.getSource() == lastButton ) //Last button is pressed
{
handleLastButton();
}//End else if
else if (event.getSource() == firstButton)
{
handleFirstButton();
}//end else if
}//End method actionPerformed
}//End class ButtonHandler
//Display the first element of the DVD array
private void handleFirstButton()
{
//Set the index to the first element in the array
index = 0;
//Update and disable modification
updateAllTextFields();
setModifiableTextFieldsEnabled( false );
}//End method handleFirstButton
//Display the next element of the DVD array or wrap to the first
private void handleNextButton()
{
//Increment the index
index++;
//If index exceeds the last valid array element, wrap around to the first element of the array
if ( index > dvd.length - 1 )
{
index = 0;
}//End if
//Update and disable modification
updateAllTextFields();
setModifiableTextFieldsEnabled( false );
}//End method handleNextButton
private void handlePreviousButton()
{
index--;
if ( index < 0)
{
index = dvd.length - 1;
}// End if
//Update and disable modification
updateAllTextFields();
setModifiableTextFieldsEnabled( false );
}//End method handlePreviousButton
private void handleLastButton()
{
index--;
if ( index < dvd.length - 1 )
{
index = 2;
}//End if
//Update and disable modification
updateAllTextFields();
setModifiableTextFieldsEnabled( false );
}//End method handleLastButton
//TextField Handler Class - Handling Methods
//The class for handling the events for the buttons
//NOTE: You don't need this for Week Eight, but I'm including it for motivation on Week
//Nine's assignment
//Hope you dont mind me leaving thin in there
private class TextFieldHandler implements ActionListener
{
public void actionPerformed( ActionEvent event )
{
//User pressed Enter in JTextField titleText
if ( event.getSource() == idText )
{
//handleIdTextField();
}//End if
//User pressed Enter in JTextField titleText
else if ( event.getSource() == titleText )
{
//handleTitleTextField();
}//End else if
//User pressed Enter in JTextField unitsText
else if ( event.getSource() == unitsText )
{
//handleUnitsTextField();
}//End else if
//User pressed Enter in JTextField priceText
else if ( event.getSource() == priceText )
{
//handlePriceTextField();
}//End else if
//User pressed Enter in JTextField searchText
else if ( event.getSource() == searchText )
{
//handleSearchButtonOrTextField();
}//End else if
}//End method actionPerformed
}//End inner class TextFieldHandler
//GUI Methods
//Build GUI
private void buildGUI()
{
//Add the logo
buildLogo();
//Add the text fields and their labels
buildLabels();
buildTextFields();
//Add the navigation and other buttons
buildMainButtons();
//Give some values to the fields
updateAllTextFields();
//Set some of the frame properties
setSize( FRAME_LENGTH , FRAME_WIDTH );
setLocation( FRAME_XLOC , FRAME_YLOC );
setResizable( false );
//pack();
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
setVisible( true );
}//End buildGUI()
//Add the logo to the JFrame
private void buildLogo()
{
constraints.weightx = 2;
constraints.weighty = 1;
logoLabel = new JLabel( new ImageIcon( "shamrock.jpg" ) );
logoLabel.setText( "Lucky DVDs" );
constraints.fill = GridBagConstraints.BOTH;
addToGridBag( logoLabel, 2, 2, LOGO_WIDTH, LOGO_HEIGHT );
//Create a vertical space
addToGridBag( new JLabel( "" ), LOGO_HEIGHT + 1, 0, LOGO_WIDTH, LABEL_WIDTH );
}//End method buildLogo
//Build just the panel containing the text
private void buildLabels()
{
//Variables (for readability)
int row= 0;
int column= 0;
int width= 0;
int height= 0;
column = LABEL_COLUMN;
width = LABEL_WIDTH;
height = LABEL_HEIGHT;
constraints.weightx = 1;
constraints.weighty = 0;
constraints.fill = GridBagConstraints.BOTH;
//Create the name label and name text field
nameLabel = new JLabel( "Product: " );
nameLabel.setLabelFor( nameText );
row= LABEL_START_ROW;
addToGridBag( nameLabel, row, column, width, height);
//Create the id label and id text field
idLabel = new JLabel( "Product Id: " );
idLabel.setLabelFor( idText );
row+= LABEL_HEIGHT;
addToGridBag( idLabel, row, column, width, height);
//Create the DVD title label and DVD title text field
titleLabel = new JLabel( "Title: " );
titleLabel.setLabelFor( titleText );
row+= LABEL_HEIGHT;
addToGridBag( titleLabel, row, column, width, height);
//Create the units in stock label and units in stock text field
unitsLabel = new JLabel( "Units in Stock: " );
unitsLabel.setLabelFor( unitsText );
row+= LABEL_HEIGHT;
addToGridBag( unitsLabel, row, column, width, height);
//Create the price label and price text field
priceLabel = new JLabel( "Unit Price:" );
priceLabel.setLabelFor( priceText );
row+= LABEL_HEIGHT;
addToGridBag( priceLabel, row, column, width, height);
//Create the value label and value text field
valueLabel = new JLabel( "Product Value:" );
valueLabel.setLabelFor( valueText );
row+= LABEL_HEIGHT;
addToGridBag( valueLabel, row, column, width, height);
//Create the fee label and fee text field
feeLabel = new JLabel( "Restocking fee:" );
feeLabel.setLabelFor( feeText );
row+= LABEL_HEIGHT;
addToGridBag( feeLabel, row, column, width, height);
//Create a vertical space
row+= LABEL_HEIGHT;
addToGridBag( new JLabel( "" ), row, column, width, height );
//Create the total value label and total value text field
totalLabel = new JLabel( "Inventory Value:" );
totalLabel.setLabelFor( totalText );
row+= LABEL_HEIGHT;
addToGridBag( totalLabel, row, column, width, height);
}//End method buildLabels()
//Build containing textFields
private void buildTextFields()
{
//Variables
int row= 0;
int column= 0;
int width= 0;
int height= 0;
column = TEXT_COLUMN;
width = TEXT_WIDTH;
height = TEXT_HEIGHT;
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1;
TextFieldHandler handler = new TextFieldHandler();
nameText = new JTextField( "DVD" );
nameText.setEditable( false );
row = TEXT_START_ROW;
addToGridBag( nameText, row , column, width, height );
idText = new JTextField( "" );
idText.setEditable( false );
row += TEXT_HEIGHT;
addToGridBag( idText, row , column, width, height );
titleText = new JTextField( " " );
titleText.addActionListener( handler );
titleText.setEditable( false );
row += TEXT_HEIGHT;
addToGridBag( titleText, row , column, width, height );
unitsText = new JTextField( " " );
unitsText.addActionListener( handler );
unitsText.setEditable( false );
row += TEXT_HEIGHT;
addToGridBag( unitsText, row , column, width, height );
priceText = new JTextField( " " );
priceText.addActionListener( handler );
priceText.setEditable( false );
row += TEXT_HEIGHT;
addToGridBag( priceText, row , column, width, height );
valueText = new JTextField( " " );
valueText.setEditable( false );
row += TEXT_HEIGHT;
addToGridBag( valueText, row , column, width, height );
feeText = new JTextField( " " );
feeText.setEditable( false );
row += TEXT_HEIGHT;
addToGridBag( feeText, row , column, width, height );
//Create a vertical space
row+= TEXT_HEIGHT;
addToGridBag( new JLabel( " " ), row, column, width, height );
totalText = new JTextField( "" );
totalText.setEditable( false );
row += TEXT_HEIGHT;
addToGridBag( totalText, row , column, width, height );
}//End method buildTextFields
//Add the main buttons to the frame
private void buildMainButtons()
{
//Variables
int row= 0;
int column= 0;
int width= 0;
int height= 0;
row = BUTTON_START_ROW;
column = BUTTON_COLUMN;
width = BUTTON_WIDTH;
height = BUTTON_HEIGHT;
constraints.weightx = 1;
constraints.weighty = 0;
//constraints.fill = GridBagConstraints.HORIZONTAL;
ButtonHandler handler = new ButtonHandler();
//Create a vertical space
addToGridBag( new JLabel( "" ), row, 0, LOGO_WIDTH, LABEL_HEIGHT );
firstButton= new JButton( "First" );
firstButton.addActionListener( handler );
row += LABEL_HEIGHT;
addToGridBag( firstButton, row, column, width, height );
previousButton= new JButton( "Previous" );
previousButton.addActionListener( handler );
column += BUTTON_WIDTH;
addToGridBag( previousButton, row, column, width, height );
nextButton= new JButton( "Next" );
nextButton.addActionListener( handler );
column += BUTTON_WIDTH;
addToGridBag( nextButton, row, column, width, height );
lastButton= new JButton( "Last" );
lastButton.addActionListener( handler );
column += BUTTON_WIDTH;
addToGridBag( lastButton, row, column, width, height );
}//End method buildMainButtons
//Add a component to the grid bag
// See Chapter 22, pp 1037 - 1046, Deital & Deital
private void addToGridBag( Component component, int row, int column, int width, int height )
{
//Set the upper-left corner of the component (gridx, gridy)
constraints.gridx = column;
constraints.gridy = row;
//Set the number of rows and columns the componenet occupies
constraints.gridwidth = width;
constraints.gridheight = height;
//Set the constraints
layout.setConstraints( component, constraints );
//Add the component to the JFrame
add( component );
}//End method addToGridBag
} //End class DVDGUI
Now for my Inventory;
//Inventory4.java
import java.util.Arrays;
public class Inventory4
{
public static void main( String args[] )
{
DVD [] inventory; //An array variable
inventory = new DVD[3];
inventory[0] = new DVD("I-Robot",2,15,15.99);
inventory[1] = new DVD("Sideways",1,4,18.00);
inventory[2] = new DVD("Love Actually",5,3,16.95);
//Create and pass control to the GUI
DVDGUI gui = new DVDGUI( inventory );
}//End method main
}//End class Inventory4
Now for the Product class code;
//Product.java
import java.util.Scanner; // program uses class Scanner
public class Product implements Comparable
{
// product private variables
private String productName; // name of product
private int productNumber; // product number
private int productUnitsInStock; // how many in stock
private double productPrice; // cost per product
private double productValue; // total value of product
// product constructors
public Product(String productNameIn, int productNumberIn, int
productUnitsInStockIn, double productPriceIn)
{
productName( productNameIn );
productNumber( productNumberIn );
productUnitsInStock( productUnitsInStockIn );
productPrice( productPriceIn );
}//End Product constructor
public void productName(String productNameIn)
{
productName = productNameIn;
}
public String productName()
{
return (productName);
}
public void productNumber(int productNumberIn)
{
productNumber = productNumberIn;
}
public int productNumber()
{
return (productNumber);
}
public void productUnitsInStock(int productUnitsInStockIn)
{
productUnitsInStock = productUnitsInStockIn;
}
public int productUnitsInStock()
{
return (productUnitsInStock);
}
public void productPrice(double productPriceIn)
{
productPrice = productPriceIn;
}
public double productPrice()
{
return (productPrice);
}
public double productValue()
{
return (productUnitsInStock * productPrice);
}
public static double productValue( Product inventory[] )
{
double value = 0.0;
for(Product p: inventory)
{
value += p.productValue();
}// End for
return ( value );
}// End method productValue
public int compareTo(Object o)
{
String s2 =((Product)o).productName.toUpperCase();
String s1 = productName.toUpperCase();
return(s1.compareTo(s2));
}
public String toString()
{
String formatString = "Product number:%d\n";
formatString += "Product Name:%s\n";
formatString += "Product Units in stock:%d\n";
formatString += "Product Price:$%.2f\n";
formatString += "Product Value:$%.2f\n\n";
return(
String.format(
formatString, productNumber, productName, productUnitsInStock, productPrice, productValue()
)
);
}//End toString()
}// End Product
Now for the DVD class;
//DVD.java
public class DVD extends Product
{
// My private variables
private String title; // Name of the DVD
// Constructors
public DVD(String titleIn, int identificationNumberIn,
int unitsInStockIn, double unitPriceIn)
{
//Call the super class (Product) constructor
super("DVD", identificationNumberIn, unitsInStockIn, unitPriceIn);
setTitle( titleIn );
}//End DVD constructor
public void setTitle( String titleIn )
{
title = titleIn;
}
public String title()
{
return (title);
}
public double productValue()
{
//Add 5% restocing fee
return ( super.productValue() * 1.05);
}
public double restockingFee()
{
return (0.05 * super.productPrice());
}// End methods
public String toString()
{
String formatString = "DVD Title : %s\n";
formatString += "Restocking Fee: $%.2f\n";
//Create a formatted string
formatString = String.format( formatString, title, restockingFee() );
//Return the string for use in display
return( formatString + super.toString());
}//End toString()
}//End class DVD
As you can see there is a lot for a new bee Java user to sift through...
Now that you have seen the cluster I have I need to use a copy-array for my Add and Delete buttons, however I already have a copy array and I would like to know if anyone has an idea if I need to use another copy array or if I need to alter my current copy array to accept the addition of another DVD and the deletion of a DVD? I just need to know the best way to accomplish this, there is no need to pust a bunch of code I just need someone to look over mine to check if I can alter or if I have to replace my copy array.
Thanks!
Thanks
I like to see and use bits of code rather then steal the whole thing!
> I like to see and use bits of code rather then steal> the whole thing!smart boy. What he was doing is not ethical.I think OP stands for "original poster" as in you.Message was edited by: petes1234
In order to get this to run on my machine, I had to add another constructor in the DVD class:
public DVD(DVD myDVD)
{
super("DVD", myDVD.productNumber(), myDVD.productUnitsInStock(), myDVD.productPrice());
setTitle(myDVD.title());
}
It's a lot of code to sift through, so I'm not sure I can help, but will try.
More suggestions as I read through your code:
1) Get the main method out of the Inventory4 class, and use the Inventory4 as what it was meant to be used: as a truly functional storage class for your DVD class. I would put my main method in someother totally unrelated class such as "TestDvd".
2) Inventory4 should be standard class with constructors and methods. Most importantly, it has to have a flexible way of storing DVDs. A standard array (i.e., DVD[]) is not bad, but it is very difficult to add to this and remove from it since it has a fixed size. Instead, I would use an ArrayList which is much better adapted to your situation. For instance:
public class Inventory4
{
private List<DVD> dvdList;
public Inventory4()
{
dvdList = new ArrayList<DVD>();
}
3) add add() and remove() functions to this class by adding and removing from the ArrayList. Study the ArrayList Java docs and examples at Sun's tutorials. They will make your life / job easier.
Here's an example of a storage class that I have been working on:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
class JunkLst implements Iterable<Junk>
{
List<Junk> junkList;
public JunkLst()
{
junkList = new ArrayList<Junk>();
}
public boolean add(Junk j)
{
return junkList.add(j);
}
public boolean remove(Junk j)
{
return junkList.remove(j);
}
public Junk get(int index)
{
if (index >= junkList.size() || index < 0)
{
throw new IndexOutOfBoundsException("Index: " + index +
", Size: " + junkList.size());
}
return junkList.get(index);
}
public Iterator<Junk> iterator()
{
return junkList.iterator();
}
public int size()
{
return junkList.size();
}
}
Warning though: I am still kind of new to all of this, so don't accept anything here as gospel. Hopefully if I have made mistakes, others will correct me.
addendum: the more I look at this mess of mine, the less I like it, as I can't see that there is any added functionality in here as compared to just having a simple ArrayList variable (like I said, I'm learning).
You may do just as well to have an ArrayList<DVD> variable in the class that has the main function (like you were doing all along).:(
Message was edited by:
petes1234
I had an aha moment. You could use something like my junkList but augment it with methods for first(), last(), next(), and prev(). You would need to maintain your own int variable that would be a circular iterator. This would allow next() to circle back to the first item when you are currently at the last item, and likewise for prev() when at the first item.
The advantage to having all this here is that it would allow you to make your humongous DVDGUI class smaller and also would allow more separation of the interface (the GUI) and the program logic.
Any of this make sense?
I am not good in explaining things but i am good in writing codes. one more suggestion. try to compare your code and my code. look how easy it is to debug in my code since i have 3 classes and how hard it would be for anyone to debug your code because its way too long and all in one file.
I would prefer you to go with JTable. may be it will ease a little bit. try to search online for JTable. So theoratically all you need is construct a JTable have 4 buttons. clear, add, search, exit. If add button is clicked then open another frame a little JFrame which will have 4 textField with labels Title, Units, Price, Advisory and 2 buttons (ok, cancel). if click ok add in JTable. this will be more efficient if you want to do it with swing.
Any more questions feel free to ask. I can do this for you again but i already posted one solution try to look at it.
Later
> Any more questions feel free to ask. I can do this> for you again but i already posted one solution try> to look at it. I believe that he already requested (correctly) that complete solutions are not desired.
right. i did not asked him to submit the same code. All i am trying to tell him is seperate his data into other java files. Just a suggestion. Whats up pete?
I was able to figure out enough manage to get it working, thanks for the help and suggestions!