GUI array information cycler help please

I currently have a program that has 3 classes. Basically one class is the main and has some information hard coded that it submits to one of the other classes. The second class takes that information, formats it and sends it to the third class. The third class creates an array, takes the information from the second class and has a display method that the main can call to display the information.

The program basically spews out all the information in the array in a specific format. The array elements contain strings, ints and doubles. The third class also calculates some things that are displayed with the display method in main.

What I need to do is create a third class. This class needs to make a GUI to display the information. I currently have the programs display method display the information in a GUI but I need it to display each element one at a time with a NEXT and PREVIOUS button. The next button needs to go to the next array element and the previous button obviously needs to go back to the array element.

Here is the code.

// Inventory Program

// Created June 20, 2007

import java.util.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

publicclass Inventory4{

publicstaticvoid main(String[] args){

CD cd;

Inventory inventory =new Inventory();

cd =new CDWithGenre(16,"Disney Hits", 11, 13.01f,"Soundtrack");

inventory.add(cd);

cd =new CDWithGenre(12,"The Clash", 10, 19.99f,"Classic Rock");

inventory.add(cd);

cd =new CDWithGenre(45,"Dixie Chiks", 18, 10.87f,"Country");

inventory.add(cd);

cd =new CDWithGenre(32,"The Cure", 62, 25.76f,"Alternative");

inventory.add(cd);

cd =new CDWithGenre(18,"MS Office", 27, 99.27f,"None");

inventory.add(cd);

inventory.display();

}//End main method

}//End Inventory4 class

/* Defines data from main as CD data and formats it. Calculates value of a title multiplied by its stock.

Creates compareTo method to be used by Arrays.sort when sorting in alphabetical order. */

class CDimplements Comparable{

//Declares the variables as protected so only this class and subclasses can act on them

protectedint cdSku;

protected String cdName;

protectedint cdCopies;

protecteddouble cdPrice;

protected String genre;

//Constructor

CD(int cdSku, String cdName,int cdCopies,double cdPrice, String genre){

this.cdSku= cdSku;

this.cdName= cdName;

this.cdCopies = cdCopies;

this.cdPrice = cdPrice;

this.genre = genre;

}

// This method tells the sort method what is to be sorted

publicint compareTo(Object o)

{

return cdName.compareTo(((CD) o).getName());

}

// Calculates the total value of the copies of a CD

publicdouble totalValue(){

return cdCopies * cdPrice;

}

// Tells the caller the title

public String getName(){

return cdName;

}

//Displays the information stored by the constructor

public String toString(){

return String.format("SKU=%2dName=%-20sStock=%3dPrice=$%6.2fValue=$%,8.2f",

cdSku, cdName, cdCopies, cdPrice, totalValue());

}

}// end CD class

//Class used to add items to the inventory, display output for the inventory and sort the inventory

class Inventory{

private CD[] cds;

privateint nCount;

// Creates array cds[] with 10 element spaces

Inventory(){

cds =new CD[10];

nCount = 0;

}

// Used by main to input a CD object into the array cds[]

publicvoid add(CD cd){

cds[nCount] = cd;

++nCount;

sort();

}

//Displays the arrays contents element by element into a GUI pane

publicvoid display(){

JTextArea textArea =new JTextArea();

textArea.append("\nThere are " + nCount +" CD titles in the collection\n\n");

for (int i = 0; i < nCount; i++)

textArea.append(cds[i]+"\n");

textArea.append("\nTotal value of the inventory is "+new java.text.DecimalFormat("$0.00").format(totalValue())+"\n\n");

JFrame invFrame =new JFrame();

invFrame.getContentPane().add(new JScrollPane(textArea));

invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

invFrame.pack();

invFrame.setLocationRelativeTo(null);

invFrame.setVisible(true);

}

// Steps through the array adding the totalValue for each CD to "total"

publicdouble totalValue(){

double total = 0;

double restock = 0;

for (int i = 0; i < nCount; i++)

total += cds[i].totalValue();

return total;

}

//Method used to sort the array by the the name of the CD

privatevoid sort(){

Arrays.sort(cds, 0, nCount);

}

}// end Inventory class

// Subclass of CD. Creates new output string to be used, adds a restocking fee calculation and genre catagory to be displayed.

class CDWithGenreextends CD{

String genre;

CDWithGenre(int cdSku, String cdName,int cdCopies,double cdPrice, String genre){

super(cdSku, cdName, cdCopies, cdPrice, genre);

this.cdName= cdName;

this.cdCopies = cdCopies;

this.cdPrice = cdPrice;

this.genre = genre;

}

// Calculates restocking fee based on previous data.

publicdouble restockFee(){

double total = 0;

double restock = 0;

total = cdCopies * cdPrice;

restock = total * .05;

return restock;

}

// New output method overrides superclass's output method with new data and format.

public String toString(){

return String.format("SKU: %2dGenre: %-12sName: %-20s\nPrice: $%6.2fValue: $%,8.2fStock: %3d Restocking Fee: $%6.2f\n",

cdSku, genre , cdName, cdPrice, totalValue(), cdCopies, restockFee());

}

}// Ends CDWithGenre class

[10652 byte] By [Codigoa] at [2007-11-27 8:35:34]
# 1
> I currently have a program....and you wrote that all by yourself? http://forum.java.sun.com/thread.jspa?threadID=5185444
Michael_Dunna at 2007-7-12 20:32:13 > top of Java-index,Desktop,Core GUI APIs...
# 2
Hey Micheal, that is a friend of mine. We are working on the same project sorta. Do you have any ideas on this cos I need help with it too.
Jmichelsen4a at 2007-7-12 20:32:13 > top of Java-index,Desktop,Core GUI APIs...
# 3

change main() (in Inventory4)

//inventory.display();

new InventoryGUI(inventory).buildGUI();

add this class

class InventoryGUI

{

Inventory inventory;

int displayElement = 0;

public InventoryGUI(Inventory inv)

{

inventory = inv;

}

public void buildGUI()

{

final JTextArea textArea = new JTextArea(inventory.display(displayElement));

final JButton prevBtn = new JButton("Previous");

prevBtn.setEnabled(false);

final JButton nextBtn = new JButton("Next");

JPanel p = new JPanel(new GridLayout(1,2));

p.add(prevBtn); p.add(nextBtn);

JFrame invFrame = new JFrame();

invFrame.getContentPane().add(new JScrollPane(textArea),BorderLayout.CENTER);

invFrame.getContentPane().add(p,BorderLayout.SOUTH);

invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

invFrame.pack();

invFrame.setLocationRelativeTo(null);

invFrame.setVisible(true);

prevBtn.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

nextBtn.setEnabled(true);

displayElement--;

textArea.setText(inventory.display(displayElement));

if(displayElement <= 0) prevBtn.setEnabled(false);

}

});

nextBtn.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

prevBtn.setEnabled(true);

displayElement++;

textArea.setText(inventory.display(displayElement));

if(displayElement >= inventory.nCount-1) nextBtn.setEnabled(false);

}

});

}

}

change Inventory.display

//public void display() {

public String display(int element) {

return cds[element].toString();//change toString to match output required

//perhaps a few more \n

}

nCount is private, modify access or use a getter

(if a getter, gui code also needs to be modified)

put it all together and it should work OK

you would be better off using an ArrayList instead of a CD[] and nCount

Michael_Dunna at 2007-7-12 20:32:13 > top of Java-index,Desktop,Core GUI APIs...
# 4
Sweet I will try that. Thanks a bunch Michael. Sorry about my friend there. I really appreciate your posts
Jmichelsen4a at 2007-7-12 20:32:13 > top of Java-index,Desktop,Core GUI APIs...
# 5

Hey Michael,

I edited the code to add some more features but I am having some errors. Can you help again?

Here is the code

The additional buttons are for features I need to add. The commented part that says save need to save to a certain location.

But the problem I am having is with the previous and next buttons. I need them to loop so when Next reaches the end of the array it needs to go to the first element again and keep on rolling thru. The previous needs to roll back from element 0 to the end again.

This works when the program is not stopped on the last or first element. If I press the last button then press next, it errors. If I press the first button and press previous, it errors.

I also need to add an icon

Let me know what you think. Thanks a bunch

class InventoryGUI

{

Inventory inventory;

int displayElement = 0;

public InventoryGUI(Inventory inv)

{

inventory = inv;

}

public void buildGUI()

{

final JTextArea textArea = new JTextArea(inventory.display(displayElement));

final JButton prevBtn = new JButton("Previous");

final JButton nextBtn = new JButton("Next");

final JButton lastBtn = new JButton("Last");

final JButton firstBtn = new JButton("First");

final JButton addBtn = new JButton("Add");

final JButton modifyBtn = new JButton("Modify");

final JButton searchBtn = new JButton("Search");

final JButton deleteBtn = new JButton("Delete");

final JButton saveBtn = new JButton("Save");

ImageIcon icon = new ImageIcon("images/icon.jpg");

JLabel label1 = new JLabel(icon);

JPanel panel = new JPanel(new GridLayout(2,4));

panel.add(firstBtn); panel.add(nextBtn); panel.add(prevBtn); panel.add(lastBtn);

panel.add(addBtn); panel.add(modifyBtn); panel.add(searchBtn); panel.add(deleteBtn);

//panel.add(saveBtn);

JFrame invFrame = new JFrame();

invFrame.getContentPane().add(new JScrollPane(textArea),BorderLayout.CENTER);

invFrame.getContentPane().add(panel,BorderLayout.SOUTH);

invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

invFrame.pack();

invFrame.setSize(500,200);

invFrame.setTitle("Inventory Manager");

invFrame.setLocationRelativeTo(null);

invFrame.setVisible(true);

prevBtn.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

nextBtn.setEnabled(true);

displayElement--;

textArea.setText(inventory.display(displayElement));

if(displayElement <= 0) displayElement = 5;

}

});

nextBtn.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

prevBtn.setEnabled(true);

displayElement++;

textArea.setText(inventory.display(displayElement));

if(displayElement >= inventory.nCount-1) displayElement = -1;

}

});

firstBtn.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

firstBtn.setEnabled(true);

displayElement = 0;

textArea.setText(inventory.display(displayElement));

}

});

lastBtn.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

lastBtn.setEnabled(true);

displayElement = inventory.nCount-1;

textArea.setText(inventory.display(displayElement));

}

});

}

}

Jmichelsen4a at 2007-7-12 20:32:13 > top of Java-index,Desktop,Core GUI APIs...
# 6

try these couple of changes

class InventoryGUI

{

Inventory inventory;

int displayElement = 0;

public InventoryGUI(Inventory inv)

{

inventory = inv;

}

public void buildGUI()

{

final JTextArea textArea = new JTextArea(inventory.display(displayElement));

final JButton prevBtn = new JButton("Previous");

final JButton nextBtn = new JButton("Next");

final JButton lastBtn = new JButton("Last");

final JButton firstBtn = new JButton("First");

final JButton addBtn = new JButton("Add");

final JButton modifyBtn = new JButton("Modify");

final JButton searchBtn = new JButton("Search");

final JButton deleteBtn = new JButton("Delete");

final JButton saveBtn = new JButton("Save");

ImageIcon icon = new ImageIcon("images/icon.jpg");

JLabel label1 = new JLabel(icon);

JPanel panel = new JPanel(new GridLayout(2,4));

panel.add(firstBtn); panel.add(nextBtn); panel.add(prevBtn); panel.add(lastBtn);

panel.add(addBtn); panel.add(modifyBtn); panel.add(searchBtn); panel.add(deleteBtn);

//panel.add(saveBtn);

JFrame invFrame = new JFrame();

invFrame.getContentPane().add(new JScrollPane(textArea),BorderLayout.CENTER);

invFrame.getContentPane().add(panel,BorderLayout.SOUTH);

invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

invFrame.pack();

invFrame.setSize(500,200);

invFrame.setTitle("Inventory Manager");

invFrame.setLocationRelativeTo(null);

invFrame.setVisible(true);

prevBtn.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

//nextBtn.setEnabled(true);//no longer needed

//displayElement--;

displayElement = (inventory.nCount+displayElement-1) % inventory.nCount;

textArea.setText(inventory.display(displayElement));

//if(displayElement <= 0) displayElement = 5;//bad to use 'magic' numbers

}

});

nextBtn.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

//prevBtn.setEnabled(true);//no longer needed

//displayElement++;

displayElement = (displayElement+1) % inventory.nCount;

textArea.setText(inventory.display(displayElement));

//if(displayElement >= inventory.nCount-1) displayElement = -1;

}

});

firstBtn.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

//firstBtn.setEnabled(true);//not required

displayElement = 0;

textArea.setText(inventory.display(displayElement));

}

});

lastBtn.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

//lastBtn.setEnabled(true);//not required

displayElement = inventory.nCount-1;

textArea.setText(inventory.display(displayElement));

}

});

}

}

> I also need to add an icon

where? to what?

Michael_Dunna at 2007-7-12 20:32:13 > top of Java-index,Desktop,Core GUI APIs...
# 7

Thanks, awesome. That worked but can you tell me why?

What is a "magic number"?

What does this part actually do? ' % inventory.nCount; '

The icon is just of a logo and I think I would like it in the top right hand corner of the application. Reading the tutorial from Javas website I tried to add the image but nothing shows up at all.

I changed the code while awaiting your response. I am trying to get the delete button to actually remove an element from the array. I copied the add() method and just revised it to delete an item but its having issues.

I have also started making the GUI that will take the users input and add an element but not quite finished with it.

Here is the code that I modified in the 2 classes. The delete button should delete the current element.

Thanks for your help!

} // end CD class

//Class used to add items to the inventory, display output for the inventory and sort the inventory

class Inventory {

private CD[] cds;

int nCount;

// Creates array cds[] with 10 element spaces

Inventory() {

cds = new CD[10];

nCount = 0;

}

// Used by main to input a CD object into the array cds[]

public void add(CD cd) {

cds[nCount] = cd;

++nCount;

sort();

}

// Deletes an element from the array

public void delete(CD cd) {

cds[nCount] = null;

}

deleteBtn.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

inventory.delete(cd);

textArea.setText("The item has been deleted");

}

});

addBtn.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

textArea.setText("Please add your item");

JPanel panel2 = new JPanel(new GridLayout(1,1));

panel2.add(saveBtn);

JFrame invFrame = new JFrame();

invFrame.getContentPane().add(new JScrollPane(textArea),BorderLayout.CENTER);

invFrame.getContentPane().add(panel2,BorderLayout.SOUTH);

invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

invFrame.pack();

invFrame.setSize(500,200);

invFrame.setTitle("Add Item");

invFrame.setLocationRelativeTo(null);

invFrame.setVisible(true);

}

});

Jmichelsen4a at 2007-7-12 20:32:13 > top of Java-index,Desktop,Core GUI APIs...
# 8

> That worked but can you tell me why?

the code was changed so that 'displayElement' was always within the bounds

of the array, using the % (mod) operator.

your code, when program opens displayElement is 0, then if 'prev' is clicked:

displayElement--;//now = -1

textArea.setText(inventory.display(displayElement));//-1 is out of bounds

if(displayElement <= 0) displayElement = 5;

same code, other way around (with a tweak) would have worked

displayElement--;

//if(displayElement <= 0) displayElement = 5;

if(displayElement < 0) displayElement = 4;

textArea.setText(inventory.display(displayElement));

> What is a "magic number"?

a number that is a constant, and appears out of left field. Anyone just reading

your code will be scratching their head: why 5? what is 5?

what happens when you add a CD, or, as you're trying to do now, delete one,

and you try to display the 5th element, when there is only 4 remaining

> What does this part actually do? ' % inventory.nCount; '

mod operator working with the number of non-null elements in the array.

displayElement = (displayElement+1) % inventory.nCount;

so, displayElement starts at 0, then if you click 'next' about 6 times

displayElement = (0+1)% inventory.nCount(5) 1%5 = 1

displayElement = (1+1)% inventory.nCount(5) 2%5 = 2

displayElement = (2+1)% inventory.nCount(5) 3%5 = 3

displayElement = (3+1)% inventory.nCount(5) 4%5 = 4

displayElement = (4+1)% inventory.nCount(5) 5%5 = 0 //wraps around to the start here

displayElement = (0+1)% inventory.nCount(5) 1%5 = 1 //and so on

similarly for the 'prev' button, except adding nCount, so displayElement can not be < 0

> The icon is just of a logo and I think I would like it in the top right hand corner of the application.

add it to a JLabel, and use the correct LayoutManager to position the label

where you want. This could be done by adding the scrollpane and 'panel' to

another panel(borderLayout), adding this new panel to the frame(center), then

adding the iconLabel (justification set to right) to the frame(north)

> I am trying to get the delete button to actually remove an element from the array

you are going to run into huge problems here - I'd suggest you use an

ArrayList, and instead of nCount, arrayList.size().

Michael_Dunna at 2007-7-12 20:32:13 > top of Java-index,Desktop,Core GUI APIs...
# 9

Ah that all makes sense. I was confused by magic number because something like I think of referring to a wildcard but I see what you mean about that being obscure.

Also, thanks for the information on % stuff, that helps a bunch.

OK I am now trying to use JLabel to create a lable with an image. I have it working sort of. It creates the label and puts it where I want it but I cant get the icon actually defined. So all that is displaying is the path.

I tried this, but it didnt like ImageIcon that way.

ImageIcon icon = new ImageIcon(c:/logo.jpg);

JLabel logo = new JLabel("c:/logo.jpg",icon, JLabel.RIGHT);

JPanel panel = new JPanel(new GridLayout(1,2));

panel.add(firstBtn); panel.add(prevBtn); panel.add(nextBtn); panel.add(lastBtn);

//panel.add(addBtn); panel.add(modifyBtn); panel.add(searchBtn); panel.add(deleteBtn);

//panel.add(saveBtn);

JPanel panel2 = new JPanel(new GridLayout(1,2));

panel2.add(logo);

JFrame invFrame = new JFrame();

invFrame.getContentPane().add(new JScrollPane(textArea),BorderLayout.CENTER);

invFrame.getContentPane().add(panel,BorderLayout.SOUTH);

invFrame.getContentPane().add(panel2,BorderLayout.NORTH);

invFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

> you are going to run into huge problems here - I'd

> suggest you use an

> ArrayList, and instead of nCount, arrayList.size().

I am so new to this all I dont know anything about ArrayList. I am going to read up on it but could you give me an example of how it would be used?

One last thing I overlooked,

I have a method named totalValue() and it is in two different classes. I need to call them separately to display separately. How would I go about doing that?

I thought I could just reference the class like this " inventory.totalValue(); " but that doesnt fly.

Thanks so much

public String toString() {

return String.format("SKU: %2dGenre: %-12sName: %-20s\nPrice: $%6.2fValue: $%,8.2fStock: %3dRestocking Fee: $%6.2f\n \nTotal value of the inventory is $%,.2f\n\n",

cdSku, genre , cdName, cdPrice, totalValue(), cdCopies, restockFee(), inventory.totalValue());

}

Jmichelsen4a at 2007-7-12 20:32:13 > top of Java-index,Desktop,Core GUI APIs...
# 10

a working example of your logo/icon in the top right corner

import javax.swing.*;

import java.awt.*;

class Testing

{

public void buildGUI()

{

JPanel oldContentPanePanel = new JPanel(new BorderLayout());//what *was* added to the JFrame, add to this instead

oldContentPanePanel.setPreferredSize(new Dimension(600,400));//not adding anything in this, so needs a size

JFrame f = new JFrame();

f.getContentPane().add(new JLabel("",new ImageIcon("test.gif"),JLabel.RIGHT),BorderLayout.NORTH);

f.getContentPane().add(oldContentPanePanel,BorderLayout.CENTER);

f.pack();

f.setLocationRelativeTo(null);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

}

public static void main(String[] args)

{

SwingUtilities.invokeLater(new Runnable(){

public void run(){

new Testing().buildGUI();

}

});

}

}

a working example of an ArrayList - much easier to add/remove that using an Array

class ArrayListExample

{

java.util.List<String> list = new java.util.ArrayList<String>();

public ArrayListExample()

{

String[] country = {"Britain","France","Germany","Russia","USA"};

for(int x = 0; x < country.length; x++) list.add(country[x]);

printList();

list.remove("France");

list.remove(country[3]);

list.remove(1);

printList();

list.add("Italy");

printList();

list.add(0,"Greece");

printList();

System.exit (0);

}

public void printList()

{

System.out.println("There are "+list.size()+" countries in the list:");

for(int x = 0, y = list.size(); x < y; x++)

{

System.out.println(list.get(x));

}

System.out.println("=====");

}

public static void main(String args[]){new ArrayListExample();}

}

> I have a method named totalValue() and it is in two different classes. I

> need to call them separately to display separately. How would I go about

> doing that?

> I thought I could just reference the class like this " inventory.totalValue(); "

> but that doesnt fly.

if you're trying to use inventory.totalValue() in

public String toString() {....

and the toString() method is part of CDWithGenre, then it won't work.

CDWithGenre knows nothing about Inventory. it may work like this

setText(toString()+inventory.totalValue());

Michael_Dunna at 2007-7-12 20:32:13 > top of Java-index,Desktop,Core GUI APIs...
# 11

That does look much better.

I could have the GUI Add button use a method to add to the ArrayList and the delete button to remove an element right?. I would modify my current Inventory class methods to add to the ArrayList instead of the current array. I dont see you having defined the array length or did I miss that?

Currently the MAIN of my program does all the adding of stuff. I would have to remove all that (aside from declarations) and just have the MAIN call the GUI and it would do all the work right?

By the way, the image came out great. Thanks for all the help.

Jmichelsen4a at 2007-7-12 20:32:13 > top of Java-index,Desktop,Core GUI APIs...
# 12

> I dont see you having defined the array length or did I miss that?

ArrayList is expandable/reducable - there is no set length/size.

this should be all you need to do in the Inventory class

class Inventory {

java.util.List<CD> cds; //removed 'private', or add/use a getter

Inventory() {

cds = new java.util.ArrayList<CD>();

}

public void add(CD cd) {

cds.add(cd);

sort();

}

public String display(int element) {

return cds.get(element).toString();

}

public double totalValue() {

double total = 0;

double restock = 0;

for (int i = 0; i < cds.size(); i++)

total += cds.get(i).totalValue();

return total;

}

private void sort() {

java.util.Collections.sort(cds);

}

}

and in InventoryGUI, replace all

inventory.nCount

with

inventory.cds.size()

Michael_Dunna at 2007-7-12 20:32:13 > top of Java-index,Desktop,Core GUI APIs...
# 13

So when using a GUI to input to the array list, the GUI would have a JTextPane to grab the users text and then it would use method cds.add(cd); to put it in the array?

Will the GUI class be able to access the inventory methods? For example when I tried using the delete method in my GUI class before, it had issues but if I put it in main, it didnt error (although I really couldnt tell if it worked)

If that is the way it would work, how would I have the input formatted? My constructor now does the formatting but I wouldnt be using that same constructor for the GUI input would I?

Or would I use the same constructor but add a GUI to main that would do the adding and removing?

Sorry so many questions.

//Constructor

CD(int cdSku, String cdName, int cdCopies, double cdPrice, String genre) {

this.cdSku= cdSku;

this.cdName= cdName;

this.cdCopies = cdCopies;

this.cdPrice = cdPrice;

this.genre = genre;

}

Jmichelsen4a at 2007-7-12 20:32:13 > top of Java-index,Desktop,Core GUI APIs...
# 14

> the GUI would have a JTextPane to grab the users text

this is likely to cause you grief - too many things can go wrong.

here's something to play around with, which might simplify things.

enter a title/star, then click 'add''

click a dvd title in the list, to select it, then click 'delete'

import javax.swing.*;

import javax.swing.event.*;

import java.awt.*;

import java.awt.event.*;

class Testing

{

public void buildGUI()

{

final DefaultListModel dlm = new DefaultListModel();

final JList list = new JList(dlm);

dlm.addElement(new DVD("Star Wars","Mark Hamill"));

dlm.addElement(new DVD("Citizen Kane","Orson Welles"));

JLabel titleLabel = new JLabel("Title: ");

final JTextField titleTextfield = new JTextField(10);

JLabel starLabel = new JLabel("Star: ");

final JTextField starTextfield = new JTextField(10);

JButton addButton = new JButton("Add");

JButton deleteButton = new JButton("Delete");

JPanel dataPanel = new JPanel(new GridLayout(0,1));

dataPanel.add(titleLabel);

dataPanel.add(titleTextfield);

dataPanel.add(starLabel);

dataPanel.add(starTextfield);

dataPanel.add(addButton);

dataPanel.add(deleteButton);

final JFrame f = new JFrame();

f.getContentPane().add(new JScrollPane(list),BorderLayout.WEST);

f.getContentPane().add(dataPanel,BorderLayout.CENTER);

f.pack();

f.setLocationRelativeTo(null);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

list.addListSelectionListener(new ListSelectionListener(){

public void valueChanged(ListSelectionEvent lse){

if(lse.getValueIsAdjusting() == false)

{

if(list.getSelectedIndex() > -1)

{

DVD dvd = (DVD)list.getSelectedValue();

titleTextfield.setText(dvd.title);

starTextfield.setText(dvd.star);

}

}

}

});

addButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

//needs error handling for empty textfields

dlm.addElement(new DVD(titleTextfield.getText(),starTextfield.getText()));

titleTextfield.setText("");

starTextfield.setText("");

}

});

deleteButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

int index = list.getSelectedIndex();

if(index < 0)

{

JOptionPane.showMessageDialog(f.getContentPane(),"No selection!");

return;

}

list.clearSelection();

dlm.remove(index);

titleTextfield.setText("");

starTextfield.setText("");

}

});

}

public static void main(String[] args)

{

SwingUtilities.invokeLater(new Runnable(){

public void run(){

new Testing().buildGUI();

}

});

}

}

class DVD

{

String title;

String star;

public DVD(String t,String s)

{

title = t; star = s;

}

public String toString(){return title;}

}

Michael_Dunna at 2007-7-12 20:32:13 > top of Java-index,Desktop,Core GUI APIs...
# 15

I am trying to use that type of thing in my program and its proving to be a bit difficult.

I was thinking I would use your example and create a DefaultListModel to take the users input. The add button would let them input the information aboutt he inventory thing into the list then i would have a Submit or Confirm button to actually take that list entry and feed it into the array.

Am I going about this entirely the wrong way?

If you see the action listener for addButton, the commented out area is what I need so the program will take all the input but it errors if I change any of the doubles or ints to Textfield.getText(), I assume its because Textfield wants text only?

This is just what I want the add GUI to look like.

addBtn.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

final DefaultListModel dlm = new DefaultListModel();

final JList list = new JList(dlm);

dlm.addElement(new CDWithGenre(00, "Example", 00, 00.00f, "Example")); //example of input

JLabel genreLabel = new JLabel("Genre: ");

final JTextField genreTextfield = new JTextField(10);

JLabel nameLabel = new JLabel("Name: ");

final JTextField nameTextfield = new JTextField(10);

JLabel priceLabel = new JLabel("Price: ");

final JTextField priceTextfield = new JTextField(10);

JLabel stockLabel = new JLabel("Stock: ");

final JTextField stockTextfield = new JTextField(10);

JLabel skuLabel = new JLabel("SKU: ");

final JTextField skuTextfield = new JTextField(10);

JButton addButton = new JButton("Add");

JButton deleteButton = new JButton("Delete");

JPanel dataPanel = new JPanel(new GridLayout(0,1));

dataPanel.add(genreLabel);

dataPanel.add(genreTextfield);

dataPanel.add(nameLabel);

dataPanel.add(nameTextfield);

dataPanel.add(priceLabel);

dataPanel.add(priceTextfield);

dataPanel.add(stockLabel);

dataPanel.add(stockTextfield);

dataPanel.add(skuLabel);

dataPanel.add(skuTextfield);

dataPanel.add(addButton);

dataPanel.add(deleteButton);

final JFrame f = new JFrame();

f.getContentPane().add(new JScrollPane(list),BorderLayout.WEST);

f.getContentPane().add(dataPanel,BorderLayout.CENTER);

f.pack();

f.setLocationRelativeTo(null);

f.setVisible(true);

addButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

//needs error handling for empty textfields

//dlm.addElement(new CDWithGenre(skuTextfield.getText(),nameTextfield.getText(),stockTextfield.getText(),priceTextfield.getText(),genreTextfield.getText()));

dlm.addElement(new CDWithGenre(0,nameTextfield.getText(), 00, 00.00f, genreTextfield.getText()));

genreTextfield.setText("");

nameTextfield.setText("");

priceTextfield.setText("");

stockTextfield.setText("");

skuTextfield.setText("");

}

});

}

});

exitBtn.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

System.exit(0);

}

});

}

}

Jmichelsen4a at 2007-7-21 22:43:23 > top of Java-index,Desktop,Core GUI APIs...
# 16

> Am I going about this entirely the wrong way?

Totally.

every time you click 'addbtn', you will be creating a new JList and JTextFields etc.

the JList etc code goes into InventoryGUI, unless you're trying to create a popup

to get the data, but then the JList wouldn't be in the popup.

all the textfield.getText() will return strings.

To match your CD constructor, you will need to convert the strings to ints or doubles

dlm.addElement(new CDWithGenre(0,nameTextfield.getText(), 00, 00.00f, genreTextfield.getText()));

(changing this so the arguments are on separate lines

dlm.addElement(new CDWithGenre(

0,

nameTextfield.getText(),

00,

00.00f,

genreTextfield.getText()));

will end up something like this

dlm.addElement(new CDWithGenre(

Integer.parseInt(skuTextfield.getText()),

nameTextfield.getText(),

Integer.parseInt(stockTextfield.getText()),

Double.parseDouble(priceTextfield.getText()),

genreTextfield.getText()));

Michael_Dunna at 2007-7-21 22:43:23 > top of Java-index,Desktop,Core GUI APIs...
# 17

Ah that worked just fine. I read something a while back telling about parsing and I thought that I may have to do that but didnt know how exactly.

So does the DefaultListModel have index numbers at all? Can I reference those individual index items in any way to suck them into the array?

That would not work at all because the GUI class knows nothing about the Inventory class where the add method is, right?

Jmichelsen4a at 2007-7-21 22:43:23 > top of Java-index,Desktop,Core GUI APIs...
# 18

> That would not work at all because the GUI class knows nothing about the

> Inventory class where the add method is, right?

the way it is now, yes.

So why not make 'Inventory' the model?

Only thing missing from DefaultListModel is totalValue(), and it can be added in.

above might make a bit more sense if you read this

http://java.sun.com/docs/books/tutorial/uiswing/components/list.html

here's a bit more to play around with (I'm still using DVD, you'll need to convert, to suit)

import javax.swing.*;

import javax.swing.event.*;

import java.awt.*;

import java.awt.event.*;

class Testing

{

public void buildGUI()

{

final Inventory dlm = new Inventory();//<--

final JList list = new JList(dlm);

list.setPrototypeCellValue("12345678987654321");

dlm.addElement(new DVD("123","Star Wars","Mark Hamill",9.99,5));

dlm.addElement(new DVD("789","Citizen Kane","Orson Welles",6.5,10));

JLabel skuLabel = new JLabel("SKU: ");

final JTextField skuTextfield = new JTextField(10);

JLabel titleLabel = new JLabel("Title: ");

final JTextField titleTextfield = new JTextField(10);

JLabel starLabel = new JLabel("Star: ");

final JTextField starTextfield = new JTextField(10);

JLabel priceLabel = new JLabel("Price: ");

final JTextField priceTextfield = new JTextField(10);

JLabel quantityLabel = new JLabel("Quantity: ");

final JTextField quantityTextfield = new JTextField(10);

JLabel quantityValueLabel = new JLabel("Quantity Value:");

final JLabel quantityDollars = new JLabel("$");

JLabel inventoryValueLabel = new JLabel("Total Inventory Value:");

final JLabel inventoryDollars = new JLabel("$");

JPanel dataPanel = new JPanel(new GridLayout(7,2));

dataPanel.add(skuLabel);

dataPanel.add(skuTextfield);

dataPanel.add(titleLabel);

dataPanel.add(titleTextfield);

dataPanel.add(starLabel);

dataPanel.add(starTextfield);

dataPanel.add(priceLabel);

dataPanel.add(priceTextfield);

dataPanel.add(quantityLabel);

dataPanel.add(quantityTextfield);

dataPanel.add(quantityValueLabel);

dataPanel.add(quantityDollars);

dataPanel.add(inventoryValueLabel);

dataPanel.add(inventoryDollars);

JButton addButton = new JButton("Add");

JButton deleteButton = new JButton("Delete");

final JButton clearButton = new JButton("Clear");

JPanel buttonPanel = new JPanel(new GridLayout(1,3));

buttonPanel.add(clearButton);

buttonPanel.add(deleteButton);

buttonPanel.add(addButton);

JPanel holdingPanel = new JPanel(new BorderLayout());

holdingPanel.add(dataPanel,BorderLayout.CENTER);

holdingPanel.add(buttonPanel,BorderLayout.SOUTH);

final JFrame f = new JFrame();

f.getContentPane().add(new JScrollPane(list),BorderLayout.CENTER);

f.getContentPane().add(holdingPanel,BorderLayout.EAST);

f.pack();

f.setLocationRelativeTo(null);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setVisible(true);

list.addListSelectionListener(new ListSelectionListener(){

public void valueChanged(ListSelectionEvent lse){

if(lse.getValueIsAdjusting() == false)

{

if(list.getSelectedIndex() > -1)

{

DVD dvd = (DVD)list.getSelectedValue();

skuTextfield.setText(dvd.SKU);

titleTextfield.setText(dvd.title);

starTextfield.setText(dvd.star);

priceTextfield.setText(String.valueOf(dvd.price));

quantityTextfield.setText(String.valueOf(dvd.quantity));

java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");

quantityDollars.setText("$"+df.format(dvd.totalValue()));

inventoryDollars.setText("$"+df.format(dlm.totalValue()));

}

}

}

});

addButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

//needs error handling for empty textfields

dlm.addElement(new DVD(skuTextfield.getText(),titleTextfield.getText(),starTextfield.getText(),

Double.parseDouble(priceTextfield.getText()),Integer.parseInt(quantityTextfield.getText())));

clearButton.doClick();

}

});

deleteButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

int index = list.getSelectedIndex();

if(index < 0)

{

JOptionPane.showMessageDialog(f.getContentPane(),"No selection!");

return;

}

dlm.remove(index);

clearButton.doClick();

}

});

clearButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

list.clearSelection();

skuTextfield.setText("");

titleTextfield.setText("");

starTextfield.setText("");

priceTextfield.setText("");

quantityTextfield.setText("");

quantityDollars.setText("$");

inventoryDollars.setText("$");

}

});

}

public static void main(String[] args)

{

SwingUtilities.invokeLater(new Runnable(){

public void run(){

new Testing().buildGUI();

}

});

}

}

class DVD

{

String SKU;

String title;

String star;

double price;

int quantity;

public DVD(String sku,String t,String s,double p,int q)

{

SKU = sku;title = t; star = s;price = p; quantity = q;

}

public double totalValue()

{

return price*quantity;

}

public String toString(){return title;}

}

class Inventory extends DefaultListModel //<--

{

public double totalValue()

{

double total = 0;

double restock = 0;

for (int x = 0, y = size(); x < y; x++)

{

total += ((DVD)get(x)).totalValue();

}

return total;

}

}

run it, add a DVD, delete one (or more) of the DVD's etc.

you may note there's not an array or arraylist in sight.

also note there's minimal error handling in the above, and it is definitely required

Michael_Dunna at 2007-7-21 22:43:23 > top of Java-index,Desktop,Core GUI APIs...
# 19

Ok that looks great. But you say there is no array, as there is not. This whole GUI is just a button of the main GUI that manipulates an array. So with this program adding to the dlm, if it cant put the data from the dlm into the array from the main GUI, is there another way to do it? I have to use the array because I need the data sorted in alpha.

You know what I mean?

Im sorry I am so needy. I know exactly what I want this program to do but I have very limited knowledge of how to do it.

Jmichelsen4a at 2007-7-21 22:43:23 > top of Java-index,Desktop,Core GUI APIs...
# 20

for sorting, couple of tweaks to DVD and Inventory classes

(now there is an arraylist - just for the sorting)

class DVD implements Comparable

{

String SKU;

String title;

String star;

double price;

int quantity;

public DVD(String sku,String t,String s,double p,int q)

{

SKU = sku;title = t; star = s;price = p; quantity = q;

}

public double totalValue()

{

return price*quantity;

}

public int compareTo(Object o)

{

return title.compareTo(((DVD) o).title);

}

public String toString(){return title;}

}

class Inventory extends DefaultListModel

{

java.util.List<DVD> temp = new java.util.ArrayList<DVD>();

public void addElement(Object obj)

{

temp.add((DVD)obj);

java.util.Collections.sort(temp);

add(temp.indexOf(obj),obj);

}

public double totalValue()

{

double total = 0;

double restock = 0;

for (int x = 0, y = size(); x < y; x++)

{

total += ((DVD)get(x)).totalValue();

}

return total;

}

}

Michael_Dunna at 2007-7-21 22:43:23 > top of Java-index,Desktop,Core GUI APIs...
# 21

So you just put an array in here for sorting?

If the data is stored as a dlm instead of an array, can it be manipulated in the sense of searching and modifying?

Say I wanted to do a search just for the title of the movie, could I do that?

I was under the impression that arrays were the only way to manipulate data this way.

Jmichelsen4a at 2007-7-21 22:43:23 > top of Java-index,Desktop,Core GUI APIs...
# 22

> So you just put an array in here for sorting?

Yes, add the new item to the arraylist, sort the arraylist, get the index of the

sorted object, then add the object to the listModel at that index.

> If the data is stored as a dlm instead of an array, can it be manipulated in the

> sense of searching and modifying?

the listModel (dlm) has the data, you can do whatever you like with it,

search/modify/add/delete/etc. you can also have first/last/next/previous, but this

would be a bit of overkill as the data is all displayed in the view (the JList)

> I was under the impression that arrays were the only way to manipulate data this way.

arrays are just one type of collection, and probably the most inflexible.

They are good when the size is unlikely to change e.g. an array to hold

the months of the year is unlikely to be any size other than 12

Michael_Dunna at 2007-7-21 22:43:23 > top of Java-index,Desktop,Core GUI APIs...
# 23

I was thinking I needed to do what you did with the sort,

>add the new item to the arraylist, sort the arraylist, get the index of the

>sorted object, then add the object to the listModel at that index.

(not exactly but similar to above, but just adding all items to the array)

I wouldnt even need to use an array for sorting like I thought I would. I would just search the list itself correct?

int indexOf(Object elem)

I dont think this will do strings though, will it?

Also, what I am going to do with modifying (if possible) is set the input boxes to be unchangable when an index item is selected so it can just be viewed. Then when modify is clicked, the text boxes will become changeable and when confirmed or add is selected, the info will overwrite the previous info for that index item.

>arrays are just one type of collection, and probably the most inflexible.

>They are good when the size is unlikely to change e.g. an array to hold

>the months of the year is unlikely to be any size other than 12

I thought this about arrays and wondered if there was a better way, I guess all the ways serve their purpose tho.

Jmichelsen4a at 2007-7-21 22:43:23 > top of Java-index,Desktop,Core GUI APIs...
# 24

> I would just search the list itself correct?

or the model.

say you had a collection of 5000 CDs/DVDs, you wouldn't want to scroll through it,

so you might add a routine where you type the first couple of letters of the title you want

and the list goes to the first title starting with those letters.

at each keystroke (probably in a separate textfield is easiest)

iterate the JList (or model)

get the object at the index of the iteration, casting to CD/DVD

if(dvd.title.startsWith(textField.getText()))//convert both to lower/uppercase

{

list.setSelectedIndex(x);//where x is the for loop counter

return;

}

as the list is sorted, keep the value of x, then next keystroke the for loop starts

where x finished the previous keystroke.

> int indexOf(Object elem)

> I dont think this will do strings though, will it?

any time you have a question like that, it is a very simple exercise to write a

10 line program to check.

> Also, what I am going to do with modifying (if possible) ...

making the textfields uneditable could be a bit of overkill. changing what's in

the textfield doesn't change what's in the model, unless specifically setting it

to do so.

a possible way to handle modification is to have a button "Edit" or "Modify" which

removes the current selection from the model, then adds the current data as

a new record. As you do not want duplicate code, the code that is in the add

button's actionPerformed move to a separate method so that is can also be

called from Edit/Modify

Michael_Dunna at 2007-7-21 22:43:23 > top of Java-index,Desktop,Core GUI APIs...
# 25

Hey can you check this out and tell me what you think of it now and if there are any problems that you see right away, please advise.

The modify button seems to have issues only after you press it a few times. Not sure why.

I havent implemented all of the button actions yet but I am getting there. Thanks for all your help.

Also I wonder about the save button. I need it to save to a specific location and not even open a menu or anything so I thought it would be pretty simple.

like

I tried something like this, with problems.

saveButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae ){

java.util.List<CDWithGenre> temp = new java.util.ArrayList<CDWithGenre>();

Object obj = new Object();

temp.add((CDWithGenre)obj);

java.util.Collections.sort(temp);

PrintStream MyOutput = null;

try {

MyOutput = new PrintStream(new FileOutputStream("InventoryIO.txt"));

}

catch (IOException e)

{

System.out.println("OOps");

}

}

});

what do you think?

I tried using the same algorithm used to create a temp array, add the stuff, sort it but in this case, just let it sit there, then let the printer print the array. I dont think that adding the array back to the index makes any difference because it wasnt modified.

import java.util.*;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.*;

public class Inventory6 {

public static void main(String[] args) {

CD cd;

Inventory inventory = new Inventory();

//Calls the GUI to display

new InventoryGUI(inventory).buildGUI();

} //End main method

} //End Inventory6 class

/* Defines data from main as CD data and formats it. Calculates value of a title multiplied by its stock.

Creates compareTo method to be used by Arrays.sort when sorting in alphabetical order. */

class CD implements Comparable{

//Declares the variables as protected so only this class and subclasses can act on them

protected int cdSku;

protected String cdName;

protected int cdCopies;

protected double cdPrice;

protected String genre;

//Constructor

CD(int cdSku, String cdName, String genre, double cdPrice, int cdCopies) {

this.cdSku= cdSku;

this.cdName= cdName;

this.cdCopies = cdCopies;

this.cdPrice = cdPrice;

this.genre = genre;

}

// This method tells the sort method what is to be sorted

public int compareTo(Object o)

{

return cdName.compareTo(((CD) o).getName());

}

// Calculates the total value of the copies of a CD

public double totalValue() {

return cdCopies * cdPrice;

}

// Tells the caller the title

public String getName() {

return cdName;

}

//Displays the information stored by the constructor

public String toString() {

return String.format("SKU=%2dName=%-20sStock=%3dPrice=$%6.2fValue=$%,8.2f",

cdSku, cdName, cdCopies, cdPrice, totalValue());

}

} // end CD class

// Subclass of CD. Creates new output string to be used, adds a restocking fee calculation and genre catagory to be displayed.

class CDWithGenre extends CD {

String genre;

CDWithGenre(int cdSku, String cdName, String genre, double cdPrice, int cdCopies) {

super(cdSku, cdName, genre, cdPrice, cdCopies);

this.cdName= cdName;

this.cdCopies = cdCopies;

this.cdPrice = cdPrice;

this.genre = genre;

}

// Calculates restocking fee based on previous data.

public double restockFee() {

double total = 0;

double restock = 0;

total = cdCopies * cdPrice;

restock = total * .05;

return restock;

}

// New output method overrides superclass's output method with new data and format.

public String toString() {

/*return String.format("SKU: %2dGenre: %-12sName: %-20s\nPrice: $%6.2fValue: $%,8.2fStock: %3dRestocking Fee: $%6.2f\n \nTotal value of the inventory is $%,.2f\n\n",

cdSku, genre , cdName, cdPrice, totalValue(), cdCopies, restockFee(), totalValue());*/

return cdName;

}

}// Ends CDWithGenre class

//GUI creation class

class InventoryGUI {

Inventory inventory;

public int displayElement = 0;

InventoryGUI(Inventory inv) {

inventory = inv;

}

public void buildGUI() {

final Inventory dlm = new Inventory();//<--

final JList list = new JList(dlm);

list.setPrototypeCellValue("12345678987654321");

//dlm.addElement(new DVD("123","Star Wars","Mark Hamill",9.99,5));

//dlm.addElement(new DVD("789","Citizen Kane","Orson Welles",6.5,10));

dlm.addElement(new CDWithGenre(00, "Example", "Example", 00.00f,00 )); //example of input

JLabel skuLabel = new JLabel("SKU: ");

final JTextField skuTextfield = new JTextField(10);

JLabel nameLabel = new JLabel("Name: ");

final JTextField nameTextfield = new JTextField(10);

JLabel genreLabel = new JLabel("Genre: ");

final JTextField genreTextfield = new JTextField(10);

JLabel priceLabel = new JLabel("Price: ");

final JTextField priceTextfield = new JTextField(10);

JLabel quantityLabel = new JLabel("Quantity: ");

final JTextField quantityTextfield = new JTextField(10);

JLabel quantityValueLabel = new JLabel("Quantity Value:");

final JLabel quantityDollars = new JLabel("$");

JLabel inventoryValueLabel = new JLabel("Total Inventory Value:");

final JLabel inventoryDollars = new JLabel("$");

JLabel srchLabel = new JLabel("Search: ");

final JTextField srchTextfield = new JTextField(10);

JPanel dataPanel = new JPanel(new GridLayout(9,2));

dataPanel.add(skuLabel);

dataPanel.add(skuTextfield);

dataPanel.add(nameLabel);

dataPanel.add(nameTextfield);

dataPanel.add(genreLabel);

dataPanel.add(genreTextfield);

dataPanel.add(priceLabel);

dataPanel.add(priceTextfield);

dataPanel.add(quantityLabel);

dataPanel.add(quantityTextfield);

dataPanel.add(quantityValueLabel);

dataPanel.add(quantityDollars);

dataPanel.add(inventoryValueLabel);

dataPanel.add(inventoryDollars);

dataPanel.add(srchLabel);

dataPanel.add(srchTextfield);

JButton addButton = new JButton("Add");

JButton deleteButton = new JButton("Delete");

JButton frstButton = new JButton("First");

JButton prevButton = new JButton("Previous");

JButton nextButton = new JButton("Next");

JButton lastButton = new JButton("Last");

JButton saveButton = new JButton("Save");

JButton mdfyButton = new JButton("Modify");

JButton srchButton = new JButton("Search");

//JButton deleteButton = new JButton("Exit");

final JButton clearButton = new JButton("Clear");

JPanel buttonPanel = new JPanel(new GridLayout(2,10));

buttonPanel.add(clearButton);

buttonPanel.add(deleteButton);

buttonPanel.add(addButton);

/*

buttonPanel.add(frstButton);

buttonPanel.add(prevButton);

buttonPanel.add(nextButton);

buttonPanel.add(lastButton);

*/

buttonPanel.add(saveButton);

buttonPanel.add(mdfyButton);

buttonPanel.add(srchButton);

//buttonPanel.add(exitButton);

JPanel holdingPanel = new JPanel(new BorderLayout());

holdingPanel.add(dataPanel,BorderLayout.CENTER);

holdingPanel.add(buttonPanel,BorderLayout.SOUTH);

final JFrame f = new JFrame();

f.getContentPane().add(new JScrollPane(list),BorderLayout.CENTER);

f.getContentPane().add(holdingPanel,BorderLayout.EAST);

f.pack();

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

f.setTitle("Add Item");

f.setLocationRelativeTo(null);

f.setVisible(true);

list.addListSelectionListener(new ListSelectionListener(){

public void valueChanged(ListSelectionEvent lse){

if(lse.getValueIsAdjusting() == false)

{

if(list.getSelectedIndex() > -1)

{

CDWithGenre cd = (CDWithGenre)list.getSelectedValue();

skuTextfield.setText(String.valueOf(cd.cdSku));

nameTextfield.setText(cd.cdName);

genreTextfield.setText(cd.genre);

priceTextfield.setText(String.valueOf(cd.cdPrice));

quantityTextfield.setText(String.valueOf(cd.cdCopies));

java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");

quantityDollars.setText("$"+df.format(cd.totalValue()));

inventoryDollars.setText("$"+df.format(dlm.totalValue()));

}

}

}

});

addButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

//needs error handling for empty textfields

dlm.addElement(new CDWithGenre(Integer.parseInt(skuTextfield.getText()),nameTextfield.getText(),genreTextfield.getText(),

Double.parseDouble(priceTextfield.getText()),Integer.parseInt(quantityTextfield.getText())));

clearButton.doClick();

}

});

deleteButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

int index = list.getSelectedIndex();

if(index < 0)

{

JOptionPane.showMessageDialog(f.getContentPane(),"No selection!");

return;

}

dlm.remove(index);

clearButton.doClick();

}

});

clearButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

list.clearSelection();

skuTextfield.setText("");

nameTextfield.setText("");

genreTextfield.setText("");

priceTextfield.setText("");

quantityTextfield.setText("");

quantityDollars.setText("$");

inventoryDollars.setText("$");

}

});

mdfyButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

//needs error handling for empty textfields

int index = list.getSelectedIndex();

dlm.addElement(new CDWithGenre(Integer.parseInt(skuTextfield.getText()),nameTextfield.getText(),genreTextfield.getText(),

Double.parseDouble(priceTextfield.getText()),Integer.parseInt(quantityTextfield.getText())));

dlm.remove(index);

clearButton.doClick();

}

});

/* class CDWithGenre implements Comparable

{

String SKU;

String name;

String genre;

double price;

int quantity;

public CDWithGenre(String sku,String t,String s,double p,int q)

{

SKU = sku;name = t; genre = s;price = p; quantity = q;

}

public double totalValue()

{

return price*quantity;

}

public int compareTo(Object o)

{

return name.compareTo(((CDWithGenre) o).name);

}

public String toString(){return name;}

}

*/

/*

exitBtn.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

System.exit(0);

}

});

*/

}

}

/*

srchBtn.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent ae){

for (int x = 0; x < list.size(); x++);

if(cd.title.genretsWith(textField.getText()))//convert both to lower/uppercase

{

list.setSelectedIndex(x);//where x is the for loop counter

return;

}

}

});

*/

class Inventory extends DefaultListModel

{

java.util.List<CDWithGenre> temp = new java.util.ArrayList<CDWithGenre>();

public void addElement(Object obj)

{

temp.add((CDWithGenre)obj);

java.util.Collections.sort(temp);

add(temp.indexOf(obj),obj);

}

public double totalValue()

{

double total = 0;

double restock = 0;

for (int x = 0, y = size(); x < y; x++)

{

total += ((CDWithGenre)get(x)).totalValue();

}

return total;

}

}

Jmichelsen4a at 2007-7-21 22:43:23 > top of Java-index,Desktop,Core GUI APIs...
# 26

> The modify button seems to have issues only after you press it a few times.

you would need to remove the object first, before adding the modified one back,

reason is: adding first may change the index of the object to be removed.

this has lead to another problem, the Inventory class needs to also override remove(),

as the Arraylist (used for sorting) also needs to have the dvd removed

add this method to Inventory()

public Object remove(int index)

{

Object dvd = temp.get(index);

super.remove(index);

temp.remove(index);

return dvd;

}

the save (and load) routine should also be in the Inventory class:

add a method to save the contents of dlm to InventoryIO.txt.

do not try to add/delete to/from the file, just save the entire contents, overwriting

previous file.

the save method is then called at the end of both the addElement() and

remove() methods (automatically - no separate 'save' button required)

Michael_Dunna at 2007-7-21 22:43:23 > top of Java-index,Desktop,Core GUI APIs...
# 27

For error handling, how does that work. I did this...

and it doesnt like the == I did this same thing but with NOT equal to and it worked, but I want info there and I want it to error if its not, not the other way around haha.

if(skuTextfield ==null )

{

JOptionPane.showMessageDialog(f.getContentPane(),"Information is missing. Please check info and re-add.");

return;

}

Jmichelsen4a at 2007-7-21 22:43:23 > top of Java-index,Desktop,Core GUI APIs...
# 28

> if(skuTextfield ==null )

it won't be null:

final JTextField skuTextfield = new JTextField(10);

unless you plan on setting it to null, later on

for "Information is missing" you should be checking if getText() returns an empty string

skuTextfield.getText().equals("")

or

skuTextfield.getText().length() == 0

Michael_Dunna at 2007-7-21 22:43:23 > top of Java-index,Desktop,Core GUI APIs...