I need to
Modify the Inventory Program by adding a button to the GUI that allows the user to move to the first item, the previous item, the next item, and the last item in the inventory. If the first item is displayed and the user clicks on the Previous button, the last item should display. If the last item is displayed and the user clicks on the Next button, the first item
should display.
Add a company logo to the GUI using Java graphics classes.
This is what I have so far.
import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat; // used to format currency
import javax.swing.*;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class InventoryMain implements ActionListener
{
CD[] product;
JTextField[] fields;
NumberFormat nf;
public void actionPerformed(ActionEvent e)
{
int index = ((JComboBox)e.getSource()).getSelectedIndex();
populateFields(index);
}
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception e)
{
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
InventoryMain test = new InventoryMain();
test.initCD();
test.showGUI();
test.populateFields(0);
}
/**
*
*/
public void initCD() {
//Create an array
product = new CD[10];
//fill in the classes
product[0] = new CD( 1, "Crowbar" , 20.00, 10, "00722");
product[1] = new CD( 2, "Pantera" , 20.00, 10, "00263");
product[2] = new CD( 3, "Ozzy" , 15.00, 10, "00142");
product[3] = new CD( 4, "Soulfly" , 18.00, 10, "00553");
product[4] = new CD( 5, "Down", 24.00, 10, "00789");
product[5] = new CD( 6, "God Forbid" , 10.00, 10, "00712");
product[6] = new CD( 7, "Black Label Society" , 16.00, 10, "00458" );
product[7] = new CD( 8, "Saint Vitus" , 15.00, 10, "00889");
product[8] = new CD( 9, "Clearlight" , 15.00, 10, "00897");
product[9] = new CD( 10, "Testament" , 15.00, 10, "00656");
//Sort elements in array in alphabetical order by product name
// product[0].sortItems(product);
final JButton firstBtn = new JButton("First"); // first button
final JButton prevBtn = new JButton("Previous"); // previous button
final JButton nextBtn = new JButton("Next"); // next button
final JButton lastBtn = new JButton("Last"); // last button
final JLabel label; // logo
final JTextArea textArea; // text area for product list
final JPanel buttonJPanel; // panel to hold buttons
//JLabel constructor for logo
Icon logo = new ImageIcon("C:/logo.jpg"); // load logo
label = new JLabel(logo); // create logo label
label.setToolTipText("Company Logo"); // create tooltip
}
private void showGUI() {
JLabel l;
JButton b;
fields = new JTextField[9];
JComboBox combo = new JComboBox();
for(int j = 0; j < product.length; j++)
combo.addItem(product[j].getName());
combo.addActionListener(this);
JFrame f = new JFrame("InventoryGUI");
Container cp = f.getContentPane();
cp.setLayout(new GridBagLayout());
cp.setBackground(UIManager.getColor("control"));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
c.gridwidth = 1;
c.gridheight = 1;
c.insets = new Insets(2, 2, 2, 2);
c.anchor = GridBagConstraints.EAST;
cp.add(l = new JLabel("Item Number:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('a');
cp.add(l = new JLabel("Item Name:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('b');
cp.add(l = new JLabel("Number of Units in Stock:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('c');
cp.add(l = new JLabel("Price per Unit: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('d');
cp.add(l = new JLabel("Total cost of This Item: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('e');
cp.add(l = new JLabel("Total Value of All Merchandise in Inventory: $",
SwingConstants.CENTER), c); l.setDisplayedMnemonic('f');
cp.add(l = new JLabel("Item Code:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('g');
cp.add(l = new JLabel("Product Restocking Fee: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('h');
cp.add(combo, c);
c.gridx = 1;
c.gridy = 0;
c.weightx = 1.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
cp.add(fields[0] = new JTextField(), c);
fields[0].setFocusAccelerator('a');
c.gridx = 1;
c.gridy = GridBagConstraints.RELATIVE;
cp.add(fields[1] = new JTextField(), c); fields[1].setFocusAccelerator('b');
cp.add(fields[2] = new JTextField(), c); fields[2].setFocusAccelerator('c');
cp.add(fields[3] = new JTextField(), c); fields[3].setFocusAccelerator('d');
cp.add(fields[4] = new JTextField(), c); fields[4].setFocusAccelerator('e');
cp.add(fields[5] = new JTextField(), c); fields[5].setFocusAccelerator('f');
cp.add(fields[6] = new JTextField(), c); fields[6].setFocusAccelerator('g');
cp.add(fields[7] = new JTextField(), c); fields[7].setFocusAccelerator('h');
cp.add(fields[8] = new JTextField(), c); fields[8].setFocusAccelerator('i');
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
cp.add(b = new JButton("OK"), c);
cp.add(b = new JButton("First"),c); // set up panel
cp.add(b = new JButton("Prev"),c);
cp.add(b = new JButton("Next"),c);
cp.add(b = new JButton("Last"),c);
b.setMnemonic('o');
f.pack();
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{
System.exit(0);
}
});
f.setVisible(true);
}
private void populateFields(int index) {
CD cd = product[index];
fields[0].setText(Long.toString(cd.getNumberCode()));
fields[1].setText(cd.getName());
fields[2].setText(Long.toString(cd.getUnits()));
fields[3].setText(Double.toString(cd.getPrice()));
fields[4].setText(Double.toString(cd.getSum()));
fields[5].setText(Double.toString(cd.totalAllInventory(product)));
fields[6].setText(cd.getCode());
fields[7].setText(Double.toString(cd.getSum()*.05));
}
}
class CD {
int itemNumber;
String name;
int units;
double price;
String itemCode;
public CD(int n, String name, double price, int units, String itemCo) {
itemNumber = n;
this.name = name;
this.price = price;
this.units = units;
itemCode = itemCo;
}
public int getNumberCode() { return itemNumber; }
public String getName() { return name; }
public int getUnits() { return units; }
public double getPrice() { return price; }
public double getSum() { return units*price; }
public String getCode() { return itemCode; }
public double totalAllInventory(CD[] cds) {
double total = 0;
for(int j = 0; j < cds.length; j++)
total += cds[j].getSum();
return total;
}
}
public class InventoryI {
String productnumber;
String name;
int numberofunits;
double priceperunit;
String itemcode;
// Create a new instance of Inventory
// main constructor for the class
public InventoryI(String Item_Number, String Item_Name, int Items_in_Stock,
double Item_Price, String Item_Code) {
productnumber = Item_Number;
name = Item_Name;
numberofunits = Items_in_Stock;
priceperunit = Item_Price;
itemcode = Item_Code;
}
public void setItemName(String Item_Name) {
// sets the items name
name = Item_Name;
}
public void setItemCode(String Item_Code) {
// sets the items name
itemcode = Item_Code;
}
public void setItemNumber(String Item_Number) { // Sets the Product =Number
// for the item
productnumber = Item_Number;
}
public void setItemsInStock(int Items_in_Stock) { // sets the =number of
// units in stock
numberofunits = Items_in_Stock;
}
public void setItemPrice(double Item_Price) { // sets the price of =the
// item
priceperunit = Item_Price;
}
public String getItemName() { // returns the Product Name of this item
return name;
}
public String getItemCode() { // returns the Product Name of this item
return itemcode;
}
public String getItemNumber() { // returns the Product Number of the =item
return productnumber;
}
public int getItemsInStock() { // returns how many units are in stock
return numberofunits;
}
public double getItemPrice() { // returns the price of the item
return priceperunit;
}
public double getInventoryIValue() { // returns the total value of =the stock
// for this item
return priceperunit * numberofunits;
}
public static double getTotalValueOfAllInventory(InventoryI [] inv) {
double tot = 0.0;
for(int i = 0; i < inv.length; i++)
tot += inv[i].getInventoryIValue();
return tot;
}
public static InventoryI[] sort(InventoryI [] inventory)
{
InventoryI temp[] = new InventoryI[1];
//sorting the array using Bubble Sort
for(int j = 0; j < inventory.length - 1; j++)
{
for(int k = 0; k < inventory.length - 1; k++)
{
if(inventory[k].getItemName().compareToIgnoreCase(inventory[k+1].getItemName()) > 0)
{
temp[0] = inventory[k];
inventory[k] = inventory[k+1];
inventory[k+1] = temp[0];
}//end if
}//end for loop
}//end for loop
return inventory;
}
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append("CD Title: \t").append(name).append("\n");
sb.append("Item Code: \t").append(itemcode).append("\n");
sb.append("Item #: \t").append(productnumber).append("\n");
sb.append("Number in stock:\t").append(numberofunits).append("\n");
sb.append("Price: \t").append(String.format("$%.2f%n", priceperunit));
sb.append("Inventory Value:\t").append(String.format("$%.2f%n", this.getInventoryIValue()));
return sb.toString();
}
}I forgot to say that my code compiles and runs showing the buttons but the buttons do nothing.
You actually define the buttons twice, once in the initCD() method and then again in showGUI(), but you do not add any ActionListeners (or Actions, both are valid) to be executed when the buttons are pressed.
How To Use Actions
here is the code with changes,
import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat; // used to format currency
import javax.swing.*;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class InventoryMain extends Frame implements ActionListener
{
CD[] product;
JTextField[] fields;
NumberFormat nf;
JButton b;
public void actionPerformed(ActionEvent e)
{
int index = ((JComboBox)e.getSource()).getSelectedIndex();
populateFields(index);
}
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception e)
{
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
InventoryMain test = new InventoryMain();
test.initCD();
test.showGUI();
test.populateFields(0);
}
/**
*
*/
public void initCD() {
//Create an array
product = new CD[10];
//fill in the classes
product[0] = new CD( 1, "Crowbar" , 20.00, 10, "00722");
product[1] = new CD( 2, "Pantera" , 20.00, 10, "00263");
product[2] = new CD( 3, "Ozzy" , 15.00, 10, "00142");
product[3] = new CD( 4, "Soulfly" , 18.00, 10, "00553");
product[4] = new CD( 5, "Down", 24.00, 10, "00789");
product[5] = new CD( 6, "God Forbid" , 10.00, 10, "00712");
product[6] = new CD( 7, "Black Label Society" , 16.00, 10, "00458" );
product[7] = new CD( 8, "Saint Vitus" , 15.00, 10, "00889");
product[8] = new CD( 9, "Clearlight" , 15.00, 10, "00897");
product[9] = new CD( 10, "Testament" , 15.00, 10, "00656");
//Sort elements in array in alphabetical order by product name
// product[0].sortItems(product);
b = new JButton("First"); // first button
b.addActionListener(this);
b = new JButton("Previous"); // previous button
b.addActionListener(this);
b = new JButton("Next"); // next button
b.addActionListener(this);
b = new JButton("Last"); // last button
}
// inner class for button event handling
private class ButtonHandler implements ActionListener
{
// handle button event
public void actionPerformed( ActionEvent event )
{
// System.out.println(event.getActionCommand());
// See which button was pressed
if (event.getActionCommand()== "Next"){
}
else if (event.getActionCommand()== "Prev"){
}
else if (event.getActionCommand()== "Last"){
}
else if (event.getActionCommand()== "First"){
}
} // end method actionPerformed
} // end private inner class ButtonHandler
private void showGUI() {
JLabel l;
JButton b;
fields = new JTextField[9];
JComboBox combo = new JComboBox();
for(int j = 0; j < product.length; j++)
combo.addItem(product[j].getName());
combo.addActionListener(this);
JFrame f = new JFrame("InventoryGUI");
Container cp = f.getContentPane();
cp.setLayout(new GridBagLayout());
cp.setBackground(UIManager.getColor("control"));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
c.gridwidth = 1;
c.gridheight = 1;
c.insets = new Insets(2, 2, 2, 2);
c.anchor = GridBagConstraints.EAST;
cp.add(l = new JLabel("Item Number:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('a');
cp.add(l = new JLabel("Item Name:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('b');
cp.add(l = new JLabel("Number of Units in Stock:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('c');
cp.add(l = new JLabel("Price per Unit: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('d');
cp.add(l = new JLabel("Total cost of This Item: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('e');
cp.add(l = new JLabel("Total Value of All Merchandise in Inventory: $",
SwingConstants.CENTER), c); l.setDisplayedMnemonic('f');
cp.add(l = new JLabel("Item Code:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('g');
cp.add(l = new JLabel("Product Restocking Fee: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('h');
cp.add(combo, c);
c.gridx = 1;
c.gridy = 0;
c.weightx = 1.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
cp.add(fields[0] = new JTextField(), c);
fields[0].setFocusAccelerator('a');
c.gridx = 1;
c.gridy = GridBagConstraints.RELATIVE;
cp.add(fields[1] = new JTextField(), c); fields[1].setFocusAccelerator('b');
cp.add(fields[2] = new JTextField(), c); fields[2].setFocusAccelerator('c');
cp.add(fields[3] = new JTextField(), c); fields[3].setFocusAccelerator('d');
cp.add(fields[4] = new JTextField(), c); fields[4].setFocusAccelerator('e');
cp.add(fields[5] = new JTextField(), c); fields[5].setFocusAccelerator('f');
cp.add(fields[6] = new JTextField(), c); fields[6].setFocusAccelerator('g');
cp.add(fields[7] = new JTextField(), c); fields[7].setFocusAccelerator('h');
cp.add(fields[8] = new JTextField(), c); fields[8].setFocusAccelerator('i');
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
cp.add(b = new JButton("OK"), c);
cp.add(b = new JButton("First"),c);
cp.add(b = new JButton("Prev"),c);
cp.add(b = new JButton("Next"),c);
cp.add(b = new JButton("Last"),c);
b.setMnemonic('o');
f.pack();
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{
System.exit(0);
}
});
f.setVisible(true);
}
private void populateFields(int index) {
CD cd = product[index];
fields[0].setText(Long.toString(cd.getNumberCode()));
fields[1].setText(cd.getName());
fields[2].setText(Long.toString(cd.getUnits()));
fields[3].setText(Double.toString(cd.getPrice()));
fields[4].setText(Double.toString(cd.getSum()));
fields[5].setText(Double.toString(cd.totalAllInventory(product)));
fields[6].setText(cd.getCode());
fields[7].setText(Double.toString(cd.getSum()*.05));
}
}
class CD {
int itemNumber;
String name;
int units;
double price;
String itemCode;
String command;
public CD(int n, String name, double price, int units, String itemCo) {
itemNumber = n;
this.name = name;
this.price = price;
this.units = units;
itemCode = itemCo;
}
public int getNumberCode() { return itemNumber; }
public String getName() { return name; }
public int getUnits() { return units; }
public double getPrice() { return price; }
public double getSum() { return units*price; }
public String getCode() { return itemCode; }
public String getActionnCommand() {return command; }
public double totalAllInventory(CD[] cds) {
double total = 0;
for(int j = 0; j < cds.length; j++)
total += cds[j].getSum();
return total;
}
}
public class InventoryI {
String productnumber;
String name;
int numberofunits;
double priceperunit;
String itemcode;
String command;
// Create a new instance of Inventory
// main constructor for the class
public InventoryI(String Item_Number, String Item_Name, int Items_in_Stock,
double Item_Price, String Item_Code) {
productnumber = Item_Number;
name = Item_Name;
numberofunits = Items_in_Stock;
priceperunit = Item_Price;
itemcode = Item_Code;
}
public void setItemName(String Item_Name) {
// sets the items name
name = Item_Name;
}
public void setItemCode(String Item_Code) {
// sets the items name
itemcode = Item_Code;
}
public void setItemNumber(String Item_Number) { // Sets the Product =Number
// for the item
productnumber = Item_Number;
}
public void setItemsInStock(int Items_in_Stock) { // sets the =number of
// units in stock
numberofunits = Items_in_Stock;
}
public void setItemPrice(double Item_Price) { // sets the price of =the
// item
priceperunit = Item_Price;
}
public String getItemName() { // returns the Product Name of this item
return name;
}
public String getItemCode() { // returns the Product Name of this item
return itemcode;
}
public String getItemNumber() { // returns the Product Number of the =item
return productnumber;
}
public int getItemsInStock() { // returns how many units are in stock
return numberofunits;
}
public double getItemPrice() { // returns the price of the item
return priceperunit;
}
public double getInventoryIValue() { // returns the total value of =the stock
// for this item
return priceperunit * numberofunits;
}
public static double getTotalValueOfAllInventory(InventoryI [] inv) {
double tot = 0.0;
for(int i = 0; i < inv.length; i++)
tot += inv[i].getInventoryIValue();
return tot;
}
public static InventoryI[] sort(InventoryI [] inventory)
{
InventoryI temp[] = new InventoryI[1];
//sorting the array using Bubble Sort
for(int j = 0; j < inventory.length - 1; j++)
{
for(int k = 0; k < inventory.length - 1; k++)
{
if(inventory[k].getItemName().compareToIgnoreCase(inventory[k+1].getItemName()) > 0)
{
temp[0] = inventory[k];
inventory[k] = inventory[k+1];
inventory[k+1] = temp[0];
}//end if
}//end for loop
}//end for loop
return inventory;
}
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append("CD Title: \t").append(name).append("\n");
sb.append("Item Code: \t").append(itemcode).append("\n");
sb.append("Item #: \t").append(productnumber).append("\n");
sb.append("Number in stock:\t").append(numberofunits).append("\n");
sb.append("Price: \t").append(String.format("$%.2f%n", priceperunit));
sb.append("Inventory Value:\t").append(String.format("$%.2f%n", this.getInventoryIValue()));
return sb.toString();
}
}b = new JButton("First"); // first button
b.addActionListener(this);
b = new JButton("Previous"); // previous button
b.addActionListener(this);
b = new JButton("Next"); // next button
b.addActionListener(this);
Still does not do anything. You are assigning "b" instances of new buttons (replacing the previous each time I might add), but the buttons that are getting added to the panel are being created in showGUI(). You need to add the action listener to the button that is being added to the panel. Also, your current action listener implementation is picking up the combo box index. Each button will need to have its own action to perform.
Ok, I changes it so the action listener is added to the buttons that are being added to the panel annd still nothing. by the way, i want to thank you for all your help and advice, they are much appreciated.
import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat; // used to format currency
import javax.swing.*;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class InventoryMain extends Frame implements ActionListener
{
CD[] product;
JTextField[] fields;
NumberFormat nf;
JButton b;
public void actionPerformed(ActionEvent e)
{
int index = ((JComboBox)e.getSource()).getSelectedIndex();
populateFields(index);
}
// inner class for button event handling
private class ButtonHandler implements ActionListener
{
// handle button event
public void actionPerformed( ActionEvent event )
{
System.out.println(event.getActionCommand());
// See which button was pressed
if (event.getActionCommand()== "Next"){
}
else if (event.getActionCommand()== "Prev"){
}
else if (event.getActionCommand()== "Last"){
}
else if (event.getActionCommand()== "First"){
}
} // end method actionPerformed
} // end private inner class ButtonHandler
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception e)
{
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
InventoryMain test = new InventoryMain();
test.initCD();
test.showGUI();
test.populateFields(0);
}
/**
*
*/
public void initCD() {
//Create an array
product = new CD[10];
//fill in the classes
product[0] = new CD( 1, "Crowbar" , 20.00, 10, "00722");
product[1] = new CD( 2, "Pantera" , 20.00, 10, "00263");
product[2] = new CD( 3, "Ozzy" , 15.00, 10, "00142");
product[3] = new CD( 4, "Soulfly" , 18.00, 10, "00553");
product[4] = new CD( 5, "Down", 24.00, 10, "00789");
product[5] = new CD( 6, "God Forbid" , 10.00, 10, "00712");
product[6] = new CD( 7, "Black Label Society" , 16.00, 10, "00458" );
product[7] = new CD( 8, "Saint Vitus" , 15.00, 10, "00889");
product[8] = new CD( 9, "Clearlight" , 15.00, 10, "00897");
product[9] = new CD( 10, "Testament" , 15.00, 10, "00656");
//Sort elements in array in alphabetical order by product name
// product[0].sortItems(product);
b = new JButton("First"); // first button
b = new JButton("Previous"); // previous button
b = new JButton("Next"); // next button
b = new JButton("Last"); // last button
}
private void showGUI() {
JLabel l;
JButton b;
fields = new JTextField[9];
JComboBox combo = new JComboBox();
for(int j = 0; j < product.length; j++)
combo.addItem(product[j].getName());
JFrame f = new JFrame("InventoryGUI");
Container cp = f.getContentPane();
cp.setLayout(new GridBagLayout());
cp.setBackground(UIManager.getColor("control"));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
c.gridwidth = 1;
c.gridheight = 1;
c.insets = new Insets(2, 2, 2, 2);
c.anchor = GridBagConstraints.EAST;
cp.add(l = new JLabel("Item Number:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('a');
cp.add(l = new JLabel("Item Name:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('b');
cp.add(l = new JLabel("Number of Units in Stock:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('c');
cp.add(l = new JLabel("Price per Unit: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('d');
cp.add(l = new JLabel("Total cost of This Item: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('e');
cp.add(l = new JLabel("Total Value of All Merchandise in Inventory: $",
SwingConstants.CENTER), c); l.setDisplayedMnemonic('f');
cp.add(l = new JLabel("Item Code:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('g');
cp.add(l = new JLabel("Product Restocking Fee: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('h');
cp.add(combo, c);
c.gridx = 1;
c.gridy = 0;
c.weightx = 1.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
cp.add(fields[0] = new JTextField(), c);
fields[0].setFocusAccelerator('a');
c.gridx = 1;
c.gridy = GridBagConstraints.RELATIVE;
cp.add(fields[1] = new JTextField(), c); fields[1].setFocusAccelerator('b');
cp.add(fields[2] = new JTextField(), c); fields[2].setFocusAccelerator('c');
cp.add(fields[3] = new JTextField(), c); fields[3].setFocusAccelerator('d');
cp.add(fields[4] = new JTextField(), c); fields[4].setFocusAccelerator('e');
cp.add(fields[5] = new JTextField(), c); fields[5].setFocusAccelerator('f');
cp.add(fields[6] = new JTextField(), c); fields[6].setFocusAccelerator('g');
cp.add(fields[7] = new JTextField(), c); fields[7].setFocusAccelerator('h');
cp.add(fields[8] = new JTextField(), c); fields[8].setFocusAccelerator('i');
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
cp.add(b = new JButton("OK"), c);
b.addActionListener(this);
cp.add(b = new JButton("First"),c);
b.addActionListener(this);
cp.add(b = new JButton("Prev"),c);
b.addActionListener(this);
cp.add(b = new JButton("Next"),c);
b.addActionListener(this);
cp.add(b = new JButton("Last"),c);
b.addActionListener(this);
b.setMnemonic('o');
f.pack();
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{
System.exit(0);
}
});
f.setVisible(true);
}
private void populateFields(int index) {
CD cd = product[index];
fields[0].setText(Long.toString(cd.getNumberCode()));
fields[1].setText(cd.getName());
fields[2].setText(Long.toString(cd.getUnits()));
fields[3].setText(Double.toString(cd.getPrice()));
fields[4].setText(Double.toString(cd.getSum()));
fields[5].setText(Double.toString(cd.totalAllInventory(product)));
fields[6].setText(cd.getCode());
fields[7].setText(Double.toString(cd.getSum()*.05));
}
}
class CD {
int itemNumber;
String name;
int units;
double price;
String itemCode;
String command;
public CD(int n, String name, double price, int units, String itemCo) {
itemNumber = n;
this.name = name;
this.price = price;
this.units = units;
itemCode = itemCo;
}
public int getNumberCode() { return itemNumber; }
public String getName() { return name; }
public int getUnits() { return units; }
public double getPrice() { return price; }
public double getSum() { return units*price; }
public String getCode() { return itemCode; }
public String getActionnCommand() {return command; }
public double totalAllInventory(CD[] cds) {
double total = 0;
for(int j = 0; j < cds.length; j++)
total += cds[j].getSum();
return total;
}
}
public class InventoryI {
String productnumber;
String name;
int numberofunits;
double priceperunit;
String itemcode;
String command;
// Create a new instance of Inventory
// main constructor for the class
public InventoryI(String Item_Number, String Item_Name, int Items_in_Stock,
double Item_Price, String Item_Code) {
productnumber = Item_Number;
name = Item_Name;
numberofunits = Items_in_Stock;
priceperunit = Item_Price;
itemcode = Item_Code;
}
public void setItemName(String Item_Name) {
// sets the items name
name = Item_Name;
}
public void setItemCode(String Item_Code) {
// sets the items name
itemcode = Item_Code;
}
public void setItemNumber(String Item_Number) { // Sets the Product =Number
// for the item
productnumber = Item_Number;
}
public void setItemsInStock(int Items_in_Stock) { // sets the =number of
// units in stock
numberofunits = Items_in_Stock;
}
public void setItemPrice(double Item_Price) { // sets the price of =the
// item
priceperunit = Item_Price;
}
public String getItemName() { // returns the Product Name of this item
return name;
}
public String getItemCode() { // returns the Product Name of this item
return itemcode;
}
public String getItemNumber() { // returns the Product Number of the =item
return productnumber;
}
public int getItemsInStock() { // returns how many units are in stock
return numberofunits;
}
public double getItemPrice() { // returns the price of the item
return priceperunit;
}
public double getInventoryIValue() { // returns the total value of =the stock
// for this item
return priceperunit * numberofunits;
}
public static double getTotalValueOfAllInventory(InventoryI [] inv) {
double tot = 0.0;
for(int i = 0; i < inv.length; i++)
tot += inv[i].getInventoryIValue();
return tot;
}
public static InventoryI[] sort(InventoryI [] inventory)
{
InventoryI temp[] = new InventoryI[1];
//sorting the array using Bubble Sort
for(int j = 0; j < inventory.length - 1; j++)
{
for(int k = 0; k < inventory.length - 1; k++)
{
if(inventory[k].getItemName().compareToIgnoreCase(inventory[k+1].getItemName()) > 0)
{
temp[0] = inventory[k];
inventory[k] = inventory[k+1];
inventory[k+1] = temp[0];
}//end if
}//end for loop
}//end for loop
return inventory;
}
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append("CD Title: \t").append(name).append("\n");
sb.append("Item Code: \t").append(itemcode).append("\n");
sb.append("Item #: \t").append(productnumber).append("\n");
sb.append("Number in stock:\t").append(numberofunits).append("\n");
sb.append("Price: \t").append(String.format("$%.2f%n", priceperunit));
sb.append("Inventory Value:\t").append(String.format("$%.2f%n", this.getInventoryIValue()));
return sb.toString();
}
}To be fair this program is in mess you should organize it little, good thing is you willing to work on it.
Bellow are some uptades for you, check the red marked parts.
PS: Can you please next time put each java file is separated code tags? Thanx
import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat; // used to format currency
import javax.swing.*;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class InventoryMain extends Frame implements ActionListener
{
CD[] product;
JTextField[] fields;
NumberFormat nf;
JButton jbtOk, jbtFirst, jbtPrev, jbtNext, jbtLast;
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception e)
{
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
InventoryMain test = new InventoryMain();
test.initCD();
test.showGUI();
test.populateFields(0);
}
/* DOESN'T DO ANYTHING
public void actionPerformed(ActionEvent e)
{
int index = ((JComboBox)e.getSource()).getSelectedIndex();
populateFields(index);
}
// inner class for button event handling
private class ButtonHandler implements ActionListener
{
// handle button event
public void actionPerformed( ActionEvent event )
{
System.out.println(event.getActionCommand());
// See which button was pressed
if (event.getActionCommand()== "Next"){
}
else if (event.getActionCommand()== "Prev"){
}
else if (event.getActionCommand()== "Last"){
}
else if (event.getActionCommand()== "First"){
}
} // end method actionPerformed
} // end private inner class ButtonHandler*/
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == jbtOk)
{
// add OK button functionality
System.out.println("OK pressed");
}
if(ae.getSource() == jbtFirst)
{
// add First button functionality
System.out.println("FIRST pressed");
}
if(ae.getSource() == jbtPrev)
{
// add Previous button functionality
System.out.println("PREVIOUS pressed");
}
if(ae.getSource() == jbtNext)
{
// add Next button functionality
System.out.println("NEXT pressed");
}
if(ae.getSource() == jbtLast)
{
// add Last button functionality
System.out.println("LAST pressed");
}
}
public void initCD()
{
//Create an array
product = new CD[10];
//fill in the classes
product[0] = new CD( 1, "Crowbar" , 20.00, 10, "00722");
product[1] = new CD( 2, "Pantera" , 20.00, 10, "00263");
product[2] = new CD( 3, "Ozzy" , 15.00, 10, "00142");
product[3] = new CD( 4, "Soulfly" , 18.00, 10, "00553");
product[4] = new CD( 5, "Down", 24.00, 10, "00789");
product[5] = new CD( 6, "God Forbid" , 10.00, 10, "00712");
product[6] = new CD( 7, "Black Label Society" , 16.00, 10, "00458" );
product[7] = new CD( 8, "Saint Vitus" , 15.00, 10, "00889");
product[8] = new CD( 9, "Clearlight" , 15.00, 10, "00897");
product[9] = new CD( 10, "Testament" , 15.00, 10, "00656");
//Sort elements in array in alphabetical order by product name
// product[0].sortItems(product);
/* WHAT IS THIS FOR ? ? ?
b = new JButton("First"); // first button
b = new JButton("Previous"); // previous button
b = new JButton("Next"); // next button
b = new JButton("Last"); // last button */
}
private void showGUI()
{
JLabel l;
/* ONE BUTTON DOESN'T DO FOR ALL ! ! !
ALSO THIS IS SECOND DECLARATION OF THE BUTTON, ONE ON THE START
JButton b;*/
fields = new JTextField[9];
JComboBox combo = new JComboBox();
for(int j = 0; j < product.length; j++)
combo.addItem(product[j].getName());
JFrame f = new JFrame("InventoryGUI");
Container cp = f.getContentPane();
cp.setLayout(new GridBagLayout());
cp.setBackground(UIManager.getColor("control"));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
c.gridwidth = 1;
c.gridheight = 1;
c.insets = new Insets(2, 2, 2, 2);
c.anchor = GridBagConstraints.EAST;
cp.add(l = new JLabel("Item Number:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('a');
cp.add(l = new JLabel("Item Name:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('b');
cp.add(l = new JLabel("Number of Units in Stock:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('c');
cp.add(l = new JLabel("Price per Unit: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('d');
cp.add(l = new JLabel("Total cost of This Item: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('e');
cp.add(l = new JLabel("Total Value of All Merchandise in Inventory: $",
SwingConstants.CENTER), c); l.setDisplayedMnemonic('f');
cp.add(l = new JLabel("Item Code:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('g');
cp.add(l = new JLabel("Product Restocking Fee: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('h');
cp.add(combo, c);
c.gridx = 1;
c.gridy = 0;
c.weightx = 1.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
cp.add(fields[0] = new JTextField(), c);
fields[0].setFocusAccelerator('a');
c.gridx = 1;
c.gridy = GridBagConstraints.RELATIVE;
cp.add(fields[1] = new JTextField(), c); fields[1].setFocusAccelerator('b');
cp.add(fields[2] = new JTextField(), c); fields[2].setFocusAccelerator('c');
cp.add(fields[3] = new JTextField(), c); fields[3].setFocusAccelerator('d');
cp.add(fields[4] = new JTextField(), c); fields[4].setFocusAccelerator('e');
cp.add(fields[5] = new JTextField(), c); fields[5].setFocusAccelerator('f');
cp.add(fields[6] = new JTextField(), c); fields[6].setFocusAccelerator('g');
cp.add(fields[7] = new JTextField(), c); fields[7].setFocusAccelerator('h');
cp.add(fields[8] = new JTextField(), c); fields[8].setFocusAccelerator('i');
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
jbtOk = new JButton("OK");
jbtOk.addActionListener(this);
jbtFirst = new JButton("First");
jbtFirst.addActionListener(this);
jbtPrev = new JButton("Previous");
jbtPrev.addActionListener(this);
jbtNext = new JButton("Next");
jbtNext.addActionListener(this);
jbtLast = new JButton("Last");
jbtLast.addActionListener(this);
cp.add(jbtOk, c);
cp.add(jbtFirst, c);
cp.add(jbtPrev, c);
cp.add(jbtNext, c);
cp.add(jbtLast, c);
/* INTERESTING SHORTCUT BUT YOU OVERWRITING YOUR BUTTON b
THAT IS ONE OF THE REASONS WHY NOTHING IS WORKING FOR YOU ! ! !
cp.add(b = new JButton("OK"), c);
b.addActionListener(this);
cp.add(b = new JButton("First"),c);
b.addActionListener(this);
cp.add(b = new JButton("Prev"),c);
b.addActionListener(this);
cp.add(b = new JButton("Next"),c);
b.addActionListener(this);
cp.add(b = new JButton("Last"),c);
b.addActionListener(this);*/
/* ASIGN MNEMONIC TO WHICH OF THE BUTTONS ? ? ?
b.setMnemonic('o');*/
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
/* ABOVE IS SIMPLER SOLUTION
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{
System.exit(0);
}
});*/
f.setVisible(true);
}
private void populateFields(int index) {
CD cd = product[index];
fields[0].setText(Long.toString(cd.getNumberCode()));
fields[1].setText(cd.getName());
fields[2].setText(Long.toString(cd.getUnits()));
fields[3].setText(Double.toString(cd.getPrice()));
fields[4].setText(Double.toString(cd.getSum()));
fields[5].setText(Double.toString(cd.totalAllInventory(product)));
fields[6].setText(cd.getCode());
fields[7].setText(Double.toString(cd.getSum()*.05));
}
}Thank you for the help, I was up all night last night and got my buttons to print out that they were pushed but I still can not get them to function so that if the list is at the first item and I push previous button the list will show the last item and so on. I have been trying to get my code to do that for the last 32 hours, I even fell asleep with my fingers on the keyboard and woke up from dreaming about java coding. lol lol. if you can point me in the right direction it would be much appreciated, dont get me wrong I'm not asking you to do it for me I'm just asking for a little help.
once again I want to thank you for your help.
It looks to me like you have written the whole thing in one go and now you're trying to back pedal.
What you should have done is to hit compile and run and check at each stage if it's correct!
If you keep a pointer to the current record int currentIndex; then moving within your array is trivial. You just increment the index as needed and populate the fields based on that index.
I'm sorry I am still new to this and do not understand the language yet, so I did not understand what you mean?
What Ezzaral is sugesting is create a variable which will hold value/position of currently selected item. On the start it will be zero as you wish to display first value from your array. When you press Next this value get increased by one. When you press Previous get decreased. Last it will change to length of your array minus one. If First selected the value will set to zero.
When this done you should thing what you want to happens when you reach last position of array. Do you want to start automaticaly from first array variable or you want to disable next move. Then apply same for first position in the array
i want to thank both of you for helping me.
ok, this is what I have done but the buttons still do not change the inventory to the next, previous, or the others.
import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat; // used to format currency
import javax.swing.*;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class InventoryMain extends Frame implements ActionListener
{
CD[] product;
JTextField[] fields;
NumberFormat nf;
JButton jbtOk, jbtFirst, jbtPrev, jbtNext, jbtLast;
static int dispProd = 0; // variable for actionEvents
// main method begins execution of java application
static JTextArea textArea;
public static void main(String[] args)
{
int i; // varialbe for looping
double total = 0; // variable for total inventory
try
{
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception e)
{
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
InventoryMain test = new InventoryMain();
test.initCD();
test.showGUI();
test.populateFields(0);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == jbtOk)
{
// add OK button functionality
System.out.println("OK pressed");
}
if(ae.getSource() == jbtFirst)
{
// add First button functionality
System.out.println("FIRST pressed");
}
if(ae.getSource() == jbtPrev)
{
// add Previous button functionality
System.out.println("PREVIOUS pressed");
}
if(ae.getSource() == jbtNext)
{
// add Next button functionality
System.out.println("NEXT pressed");
}
if(ae.getSource() == jbtLast)
{
// add Last button functionality
System.out.println("LAST pressed");
}
}
public void initCD() {
//Create an array
product = new CD[10];
//fill in the classes
product[0] = new CD( 1, "Crowbar" , 20.00, 10, "00722");
product[1] = new CD( 2, "Pantera" , 20.00, 10, "00263");
product[2] = new CD( 3, "Ozzy" , 15.00, 10, "00142");
product[3] = new CD( 4, "Soulfly" , 18.00, 10, "00553");
product[4] = new CD( 5, "Down", 24.00, 10, "00789");
product[5] = new CD( 6, "God Forbid" , 10.00, 10, "00712");
product[6] = new CD( 7, "Black Label Society" , 16.00, 10, "00458" );
product[7] = new CD( 8, "Saint Vitus" , 15.00, 10, "00889");
product[8] = new CD( 9, "Clearlight" , 15.00, 10, "00897");
product[9] = new CD( 10, "Testament" , 15.00, 10, "00656");
//Sort elements in array in alphabetical order by product name
// product[0].sortItems(product);
} private void showGUI() {
JLabel l;
JButton b;
fields = new JTextField[9];
JComboBox combo = new JComboBox();
for(int j = 0; j < product.length; j++)
combo.addItem(product[j].getName());
combo.addActionListener(this);
JFrame f = new JFrame("InventoryGUI");
Container cp = f.getContentPane();
cp.setLayout(new GridBagLayout());
cp.setBackground(UIManager.getColor("control"));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
c.gridwidth = 1;
c.gridheight = 1;
c.insets = new Insets(2, 2, 2, 2);
c.anchor = GridBagConstraints.EAST;
cp.add(l = new JLabel("Item Number:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('a');
cp.add(l = new JLabel("Item Name:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('b');
cp.add(l = new JLabel("Number of Units in Stock:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('c');
cp.add(l = new JLabel("Price per Unit: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('d');
cp.add(l = new JLabel("Total cost of This Item: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('e');
cp.add(l = new JLabel("Total Value of All Merchandise in Inventory: $",
SwingConstants.CENTER), c); l.setDisplayedMnemonic('f');
cp.add(l = new JLabel("Item Code:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('g');
cp.add(l = new JLabel("Product Restocking Fee: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('h');
cp.add(combo, c);
c.gridx = 1;
c.gridy = 0;
c.weightx = 1.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
cp.add(fields[0] = new JTextField(), c);
fields[0].setFocusAccelerator('a');
c.gridx = 1;
c.gridy = GridBagConstraints.RELATIVE;
cp.add(fields[1] = new JTextField(), c); fields[1].setFocusAccelerator('b');
cp.add(fields[2] = new JTextField(), c); fields[2].setFocusAccelerator('c');
cp.add(fields[3] = new JTextField(), c); fields[3].setFocusAccelerator('d');
cp.add(fields[4] = new JTextField(), c); fields[4].setFocusAccelerator('e');
cp.add(fields[5] = new JTextField(), c); fields[5].setFocusAccelerator('f');
cp.add(fields[6] = new JTextField(), c); fields[6].setFocusAccelerator('g');
cp.add(fields[7] = new JTextField(), c); fields[7].setFocusAccelerator('h');
cp.add(fields[8] = new JTextField(), c); fields[8].setFocusAccelerator('i');
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
jbtOk = new JButton("OK");
jbtOk.addActionListener(this);
jbtFirst = new JButton("First");
jbtFirst.addActionListener(this);
jbtPrev = new JButton("Previous");
jbtPrev.addActionListener(this);
jbtNext = new JButton("Next");
jbtNext.addActionListener(this);
jbtLast = new JButton("Last");
jbtLast.addActionListener(this);
cp.add(jbtOk, c);
cp.add(jbtFirst, c);
cp.add(jbtPrev, c);
cp.add(jbtNext, c);
cp.add(jbtLast, c);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
// assign actionListener and actionEvent for each button
jbtFirst.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
dispProd = 0;
} // end firstBtn actionEvent
}); // end firstBtn actionListener
jbtPrev.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
dispProd--;
if (dispProd < 0)
{
dispProd = 0;
}
dispProd = (product.length+dispProd-1) % product.length;
} // end prevBtn actionEvent
}); // end prevBtn actionListener
jbtLast.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
dispProd = product.length - 1;
} // end lastBtn actionEvent
}); // end lastBtn actionListener
jbtNext.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
dispProd++;
if (dispProd >= product.length)
{
dispProd = product.length - 1;
}
} // end nextBtn actionEvent
}); // end nextBtn actionListener
}
private void populateFields(int index) {
CD cd = product[index];
fields[0].setText(Long.toString(cd.getNumberCode()));
fields[1].setText(cd.getName());
fields[2].setText(Long.toString(cd.getUnits()));
fields[3].setText(Double.toString(cd.getPrice()));
fields[4].setText(Double.toString(cd.getSum()));
fields[5].setText(Double.toString(cd.totalAllInventory(product)));
fields[6].setText(cd.getCode());
fields[7].setText(Double.toString(cd.getSum()*.05));
}
}It is still working, you just do not see output on command line don't you? Or you do not know where this is comming from? Why you not getting action from "your" ActionListeners?
Well answer is very simple. You have 2 ActionListeners. One is top level which I created
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == jbtOk)
{
// add OK button functionality
System.out.println("OK pressed");
}
if(ae.getSource() == jbtFirst)
{
// add First button functionality
System.out.println("FIRST pressed");
}
if(ae.getSource() == jbtPrev)
{
// add Previous button functionality
System.out.println("PREVIOUS pressed");
}
if(ae.getSource() == jbtNext)
{
// add Next button functionality
System.out.println("NEXT pressed");
}
if(ae.getSource() == jbtLast)
{
// add Last button functionality
System.out.println("LAST pressed");
}
} and then there are yours anonymous inner class listeners like this one
jbtFirst.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
dispProd = 0;
} // end firstBtn actionEvent
}); // end firstBtn actionListener So all action events by buttons get catch by my event handle as it is top level instead of yours. Simply comment out content of my actionPerformed() method /* */, just content not whole or you get error for JComboBox to which you assign event but not handle anywhere
combo.addActionListener(this);
and do not forget to call a method for updating content of the fields, the one in red
jbtNext.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
dispProd++;
if (dispProd >= product.length)
{
dispProd = product.length - 1;
}
populateFields(dispProd);
} // end nextBtn actionEvent
}); // end nextBtn actionListener
PS: You may complitely remove my event handler once you implement anonymous inner class event handler for that combo box.
the next button needs to navagate to the next item when pushed and the previous button needs to navagate to the previous item and so on. The buttons just print out that they have been pushed and thats it. I am having a hard time understanding.
Just delete event handle created by me, create event handler for JComboBox and call following method
populateFields(dispProd);
to update your fields...
I did what you suggested and now I get these errors:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.JButton cannot be cast to javax.swing.JComboBox
at inventoryi.InventoryMain.actionPerformed(InventoryI.java:48)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6038)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
at java.awt.Component.processEvent(Component.java:5803)
at java.awt.Container.processEvent(Container.java:2058)
at java.awt.Component.dispatchEventImpl(Component.java:4410)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
at java.awt.Container.dispatchEventImpl(Container.java:2102)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
This is my code that I get errors
import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat; // used to format currency
import javax.swing.*;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class InventoryMain extends Frame implements ActionListener
{
CD[] product;
JTextField[] fields;
NumberFormat nf;
JButton jbtOk, jbtFirst, jbtPrev, jbtNext, jbtLast;
JLabel label; // logo
JPanel buttonJPanel; // panel to hold buttons
String nameText;
private int index;
int i; // varialbe for looping
double total = 0; // variable for total inventory
static int dispProd = 0; // variable for actionEvents
static JTextArea textArea;
public void actionPerformed(ActionEvent e)
{
int index = ((JComboBox)e.getSource()).getSelectedIndex();
populateFields(dispProd);
}
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception e)
{
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
InventoryMain test = new InventoryMain();
test.initCD();
test.showGUI();
test.populateFields(0);
}
public void initCD() {
//Create an array
product = new CD[10];
//fill in the classes
product[0] = new CD( 1, "Crowbar" , 20.00, 10, "00722");
product[1] = new CD( 2, "Pantera" , 20.00, 10, "00263");
product[2] = new CD( 3, "Ozzy" , 15.00, 10, "00142");
product[3] = new CD( 4, "Soulfly" , 18.00, 10, "00553");
product[4] = new CD( 5, "Down", 24.00, 10, "00789");
product[5] = new CD( 6, "God Forbid" , 10.00, 10, "00712");
product[6] = new CD( 7, "Black Label Society" , 16.00, 10, "00458" );
product[7] = new CD( 8, "Saint Vitus" , 15.00, 10, "00889");
product[8] = new CD( 9, "Clearlight" , 15.00, 10, "00897");
product[9] = new CD( 10, "Testament" , 15.00, 10, "00656");
//Sort elements in array in alphabetical order by product name
// product[0].sortItems(product);
}
private void showGUI() {
JLabel l;
JButton b;
fields = new JTextField[9];
JComboBox combo = new JComboBox();
for(int j = 0; j < product.length; j++)
combo.addItem(product[j].getName());
combo.addActionListener(this);
Icon logo = new ImageIcon("C:/logo.jpg"); // load logo
label = new JLabel(logo); // create logo label
label.setToolTipText("Company Logo"); // create tooltip
textArea = new JTextArea(product[3] + "\n"); // create textArea for
// product display
JFrame f = new JFrame("CD Inventory");
Container cp = f.getContentPane();
cp.setLayout(new GridBagLayout());
cp.setBackground(UIManager.getColor("control"));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
c.gridwidth = 1;
c.gridheight = 1;
c.insets = new Insets(2, 2, 2, 2);
c.anchor = GridBagConstraints.EAST;
cp.add(l = new JLabel("Item Number:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('a');
cp.add(l = new JLabel("Item Name:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('b');
cp.add(l = new JLabel("Number of Units in Stock:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('c');
cp.add(l = new JLabel("Price per Unit: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('d');
cp.add(l = new JLabel("Total cost of This Item: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('e');
cp.add(l = new JLabel("Total Value of All Merchandise in Inventory: $",
SwingConstants.CENTER), c); l.setDisplayedMnemonic('f');
cp.add(l = new JLabel("Item Code:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('g');
cp.add(l = new JLabel("Product Restocking Fee: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('h');
cp.add(combo, c);
c.gridx = 1;
c.gridy = 0;
c.weightx = 1.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
cp.add(fields[0] = new JTextField(), c);
fields[0].setFocusAccelerator('a');
c.gridx = 1;
c.gridy = GridBagConstraints.RELATIVE;
cp.add(fields[1] = new JTextField(), c); fields[1].setFocusAccelerator('b');
cp.add(fields[2] = new JTextField(), c); fields[2].setFocusAccelerator('c');
cp.add(fields[3] = new JTextField(), c); fields[3].setFocusAccelerator('d');
cp.add(fields[4] = new JTextField(), c); fields[4].setFocusAccelerator('e');
cp.add(fields[5] = new JTextField(), c); fields[5].setFocusAccelerator('f');
cp.add(fields[6] = new JTextField(), c); fields[6].setFocusAccelerator('g');
cp.add(fields[7] = new JTextField(), c); fields[7].setFocusAccelerator('h');
cp.add(fields[8] = new JTextField(), c); fields[8].setFocusAccelerator('i');
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
jbtOk = new JButton("OK");
jbtOk.addActionListener(this);
jbtFirst = new JButton("First");
jbtFirst.addActionListener(this);
jbtPrev = new JButton("Previous");
jbtPrev.addActionListener(this);
jbtNext = new JButton("Next");
jbtNext.addActionListener(this);
jbtLast = new JButton("Last");
jbtLast.addActionListener(this);
cp.add(jbtOk, c);
cp.add(jbtFirst, c);
cp.add(jbtPrev, c);
cp.add(jbtNext, c);
cp.add(jbtLast, c);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
// assign actionListener and actionEvent for each button
jbtFirst.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
dispProd = 0;
} // end firstBtn actionEvent
}); // end firstBtn actionListener
jbtPrev.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
dispProd--;
if (dispProd < 0)
{
dispProd = product.length - 1;
}
dispProd = (product.length+dispProd-1) % product.length;
} // end prevBtn actionEvent
}); // end prevBtn actionListener
jbtLast.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
dispProd = product.length - 1;
} // end lastBtn actionEvent
}); // end lastBtn actionListener
jbtNext.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
dispProd++;
if (dispProd >= product.length - 1)
{
dispProd = 0;
}
} // end nextBtn actionEvent
}); // end nextBtn actionListener
}
private void populateFields(int index) {
CD cd = product[index];
fields[0].setText(Long.toString(cd.getNumberCode()));
fields[1].setText(cd.getName());
fields[2].setText(Long.toString(cd.getUnits()));
fields[3].setText(Double.toString(cd.getPrice()));
fields[4].setText(Double.toString(cd.getSum()));
fields[5].setText(Double.toString(cd.totalAllInventory(product)));
fields[6].setText(cd.getCode());
fields[7].setText(Double.toString(cd.getSum()*.05));
} class CD {
int itemNumber;
String name;
int units;
double price;
String itemCode;
String command;
public CD(int n, String name, double price, int units, String itemCo) {
itemNumber = n;
this.name = name;
this.price = price;
this.units = units;
itemCode = itemCo;
}
public int getNumberCode() { return itemNumber; }
public String getName() { return name; }
public int getUnits() { return units; }
public double getPrice() { return price; }
public double getSum() { return units*price; }
public String getCode() { return itemCode; }
public String getActionnCommand() {return command; }
public double totalAllInventory(CD[] cds) {
double total = 0;
for(int j = 0; j < cds.length; j++)
total += cds[j].getSum();
return total;
}
}
public class InventoryI {
String productnumber;
String name;
String Text;
int numberofunits;
double priceperunit;
String itemcode;
String command;
// Create a new instance of Inventory
// main constructor for the class
public InventoryI(String Item_Number, String Item_Name, int Items_in_Stock,
double Item_Price, String Item_Code) {
productnumber = Item_Number;
name = Item_Name;
numberofunits = Items_in_Stock;
priceperunit = Item_Price;
itemcode = Item_Code;
}
public void setItemName(String Item_Name) {
// sets the items name
name = Item_Name;
}
public void setItemCode(String Item_Code) {
// sets the items name
itemcode = Item_Code;
}
public void setItemNumber(String Item_Number) { // Sets the Product =Number
// for the item
productnumber = Item_Number;
}
public void setItemsInStock(int Items_in_Stock) { // sets the =number of
// units in stock
numberofunits = Items_in_Stock;
}
public void setItemPrice(double Item_Price) { // sets the price of =the
// item
priceperunit = Item_Price;
}
public String getItemName() { // returns the Product Name of this item
return name;
}
public String getItemCode() { // returns the Product Name of this item
return itemcode;
}
public String getItemNumber() { // returns the Product Number of the =item
return productnumber;
}
public int getItemsInStock() { // returns how many units are in stock
return numberofunits;
}
public double getItemPrice() { // returns the price of the item
return priceperunit;
}
public double getInventoryIValue() { // returns the total value of =the stock
// for this item
return priceperunit * numberofunits;
}
public static double getTotalValueOfAllInventory(InventoryI [] inv) {
double tot = 0.0;
for(int i = 0; i < inv.length; i++)
tot += inv[i].getInventoryIValue();
return tot;
}
public static InventoryI[] sort(InventoryI [] inventory)
{
InventoryI temp[] = new InventoryI[1];
//sorting the array using Bubble Sort
for(int j = 0; j < inventory.length - 1; j++)
{
for(int k = 0; k < inventory.length - 1; k++)
{
if(inventory[k].getItemName().compareToIgnoreCase(inventory[k+1].getItemName()) > 0)
{
temp[0] = inventory[k];
inventory[k] = inventory[k+1];
inventory[k+1] = temp[0];
}//end if
}//end for loop
}//end for loop
return inventory;
}
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append("CD Title: \t").append(name).append("\n");
sb.append("Item Code: \t").append(itemcode).append("\n");
sb.append("Item #: \t").append(productnumber).append("\n");
sb.append("Number in stock:\t").append(numberofunits).append("\n");
sb.append("Price: \t").append(String.format("$%.2f%n", priceperunit));
sb.append("Inventory Value:\t").append(String.format("$%.2f%n", this.getInventoryIValue()));
return sb.toString();
}
}I don't think this is best way to implement event handler for JComboBox
public void actionPerformed(ActionEvent e)
{
int index = ((JComboBox)e.getSource()).getSelectedIndex();
populateFields(dispProd);
} aslo I moved your declaration of JComboBox from ShowGUI() on the start with other variables only initialization is left there. You OK button doesn't do anything as you did not create anonymous event handler for it, like other buttons, and has no action declared in top level event handler with JComboBox
import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat; // used to format currency
import javax.swing.*;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class InventoryMain extends Frame implements ActionListener
{
CD[] product;
JTextField[] fields;
NumberFormat nf;
JButton jbtOk, jbtFirst, jbtPrev, jbtNext, jbtLast;
JLabel label; // logo
JPanel buttonJPanel; // panel to hold buttons
String nameText;
JComboBox combo; // New place to declare combo box
private int index;
int i; // varialbe for looping
double total = 0; // variable for total inventory
static int dispProd = 0; // variable for actionEvents
static JTextArea textArea;
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception e)
{
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
InventoryMain test = new InventoryMain();
test.initCD();
test.showGUI();
test.populateFields(0);
}
public void initCD() {
//Create an array
product = new CD[10];
//fill in the classes
product[0] = new CD( 1, "Crowbar" , 20.00, 10, "00722");
product[1] = new CD( 2, "Pantera" , 20.00, 10, "00263");
product[2] = new CD( 3, "Ozzy" , 15.00, 10, "00142");
product[3] = new CD( 4, "Soulfly" , 18.00, 10, "00553");
product[4] = new CD( 5, "Down", 24.00, 10, "00789");
product[5] = new CD( 6, "God Forbid" , 10.00, 10, "00712");
product[6] = new CD( 7, "Black Label Society" , 16.00, 10, "00458" );
product[7] = new CD( 8, "Saint Vitus" , 15.00, 10, "00889");
product[8] = new CD( 9, "Clearlight" , 15.00, 10, "00897");
product[9] = new CD( 10, "Testament" , 15.00, 10, "00656");
//Sort elements in array in alphabetical order by product name
// product[0].sortItems(product);
}
private void showGUI() {
JLabel l;
JButton b;
fields = new JTextField[9];
combo = new JComboBox(); // combo box initialization left sa was
for(int j = 0; j < product.length; j++)
combo.addItem(product[j].getName());
combo.addActionListener(this);
Icon logo = new ImageIcon("C:/logo.jpg"); // load logo
label = new JLabel(logo); // create logo label
label.setToolTipText("Company Logo"); // create tooltip
textArea = new JTextArea(product[3] + "\n"); // create textArea for
// product display
JFrame f = new JFrame("CD Inventory");
Container cp = f.getContentPane();
cp.setLayout(new GridBagLayout());
cp.setBackground(UIManager.getColor("control"));
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
c.gridwidth = 1;
c.gridheight = 1;
c.insets = new Insets(2, 2, 2, 2);
c.anchor = GridBagConstraints.EAST;
cp.add(l = new JLabel("Item Number:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('a');
cp.add(l = new JLabel("Item Name:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('b');
cp.add(l = new JLabel("Number of Units in Stock:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('c');
cp.add(l = new JLabel("Price per Unit: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('d');
cp.add(l = new JLabel("Total cost of This Item: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('e');
cp.add(l = new JLabel("Total Value of All Merchandise in Inventory: $",
SwingConstants.CENTER), c); l.setDisplayedMnemonic('f');
cp.add(l = new JLabel("Item Code:", SwingConstants.CENTER), c); l.setDisplayedMnemonic('g');
cp.add(l = new JLabel("Product Restocking Fee: $", SwingConstants.CENTER), c); l.setDisplayedMnemonic('h');
cp.add(combo, c);
c.gridx = 1;
c.gridy = 0;
c.weightx = 1.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;
cp.add(fields[0] = new JTextField(), c);
fields[0].setFocusAccelerator('a');
c.gridx = 1;
c.gridy = GridBagConstraints.RELATIVE;
cp.add(fields[1] = new JTextField(), c); fields[1].setFocusAccelerator('b');
cp.add(fields[2] = new JTextField(), c); fields[2].setFocusAccelerator('c');
cp.add(fields[3] = new JTextField(), c); fields[3].setFocusAccelerator('d');
cp.add(fields[4] = new JTextField(), c); fields[4].setFocusAccelerator('e');
cp.add(fields[5] = new JTextField(), c); fields[5].setFocusAccelerator('f');
cp.add(fields[6] = new JTextField(), c); fields[6].setFocusAccelerator('g');
cp.add(fields[7] = new JTextField(), c); fields[7].setFocusAccelerator('h');
cp.add(fields[8] = new JTextField(), c); fields[8].setFocusAccelerator('i');
c.weightx = 0.0;
c.fill = GridBagConstraints.NONE;
jbtOk = new JButton("OK");
jbtOk.addActionListener(this);
jbtFirst = new JButton("First");
jbtFirst.addActionListener(this);
jbtPrev = new JButton("Previous");
jbtPrev.addActionListener(this);
jbtNext = new JButton("Next");
jbtNext.addActionListener(this);
jbtLast = new JButton("Last");
jbtLast.addActionListener(this);
cp.add(jbtOk, c);
cp.add(jbtFirst, c);
cp.add(jbtPrev, c);
cp.add(jbtNext, c);
cp.add(jbtLast, c);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
// assign actionListener and actionEvent for each button
jbtFirst.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
dispProd = 0;
populateFields(dispProd); // missing method call for update
} // end firstBtn actionEvent
}); // end firstBtn actionListener
jbtPrev.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
dispProd--;
if (dispProd < 0)
{
dispProd = product.length - 1;
}
//WHAT IS THIS FOR??
//dispProd = (product.length+dispProd-1) % product.length;
populateFields(dispProd); // missing method call for update
} // end prevBtn actionEvent
}); // end prevBtn actionListener
jbtLast.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
dispProd = product.length - 1;
populateFields(dispProd); // missing method call for update
} // end lastBtn actionEvent
}); // end lastBtn actionListener
jbtNext.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
dispProd++;
if (dispProd >= product.length - 1)
{
dispProd = 0;
}
populateFields(dispProd); // Missing method call for update
} // end nextBtn actionEvent
}); // end nextBtn actionListener
}
// event handler for combo box
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == combo)
{
//System message, I do not know what you wish to do with combo box
System.out.println("Selected option: " + combo.getSelectedIndex() );
}
}
private void populateFields(int index) {
CD cd = product[index];
fields[0].setText(Long.toString(cd.getNumberCode()));
fields[1].setText(cd.getName());
fields[2].setText(Long.toString(cd.getUnits()));
fields[3].setText(Double.toString(cd.getPrice()));
fields[4].setText(Double.toString(cd.getSum()));
fields[5].setText(Double.toString(cd.totalAllInventory(product)));
fields[6].setText(cd.getCode());
fields[7].setText(Double.toString(cd.getSum()*.05));
}
}