Java School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a Java Expert!

Join 300,495 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,848 people online right now. Registration is fast and FREE... Join Now!




GUI display of subclass values

 

GUI display of subclass values, Need to display value from array (extends portion)

woodygeo

1 Jul, 2009 - 01:35 PM
Post #1

New D.I.C Head
*

Joined: 15 Jun, 2009
Posts: 2

Hello -

I am working on the same inventory program that many people over the last couple of years have. I have looked through these forums, and have not been able to glean my answer from existing topics.

I have a class that creates an array of items (class-TradingCards), and then a subclass that allows for an additional value (subclass- RankAdded new value - cardrank).

I have created the GUI with the logo, and the buttons for "First Entry" "Next" "Previous" and "Last" and they all work.

All the fields from the TradingCards class display on the GUI fine.

I am having trouble displaying the field from the "extends" array (the cardrank field).

I had hoped to display the rank when it exists, but just display "No Rank" when there isn't one.

The data was loaded at the top of the Main - regular class data first, then subclass next.

* I have tried referring directly to the RankAdded array, but values were always null.
* I have added a "toString()" method to my subclass, then the GUI display showed two fields combined/appended (cardname field from TradingCard class and the rankcard field from RankAdded class)

I am going to post the entire code (long!), since I am not sure which parts you would need to give advice.

Thank you in advance for any help.


Main.java code below.....
CODE

package inventoryprogram4;

/*

*
*/
import java.text.DecimalFormat;//for formatting currency
import java.util.Arrays; //for the sort of 'arrays' from java API



/**
* Ken
*/
public class Main {

public static void main(String[] args) {
        

        CardInventory inventory = new CardInventory();
        TradingCards card;

         card = new TradingCards(88, "Wheels08DaleJr",5, 2.25);
        inventory.addCards(card);


        card = new TradingCards(99, "Wheels08Carl",99, 5.25);
        inventory.addCards(card);

        card = new TradingCards(48, "Wheels08Jimmie",1, 0.99);
        inventory.addCards(card);

        card = new TradingCards(43, "Wheels08RPetty",7, 10.25);
        inventory.addCards(card);

        card = new TradingCards(24, "Wheels08JGordon",3, 1.25);
        inventory.addCards(card);

        card = new TradingCards(96, "Wheels08Bobby",2, 4.25);
        inventory.addCards(card);

        inventory.printInventory();




        RankAdded card1 = new RankAdded(18, "Wheels08KBusch", 3, 0.15, "43");
        RankAdded card2 = new RankAdded(41, "Wheels08JMayfield", 1, 1.05, "42");

        System.out.println("\n2 new cards added with new field for Driver" +
                "Ranking");
        System.out.println("\n\nRank for Kyle Busch: " + card1.getRank());
        System.out.println("Re-stock fee for Kyle Busch " +
                "card: " + inventory.formatter.format(card1.getRestockingFee()));


        System.out.println("\n\nRank for Jeremy" +
                "Mayfield: " + card2.getRank());
        System.out.println("Re-stock fee for Jeremy Mayfield" +
                "card: " + inventory.formatter.format(card2.getRestockingFee()));



        inventory.addCards(card1);
        inventory.addCards(card2);

      
        inventory.printInventory();

        GUIa gui = new GUIa(inventory);
        // Start the GUI

        }

}
/*

*/


//public class TradingCards {
    class TradingCards implements Comparable {
    // Declarations
    private String cardname;
    private int quantity;
    private double value;
    private int cardnumber = 0;

    // "Zero" out constructor.

    public TradingCards() {
        this(0,"Unknown",0,0.00);
    }

    // Constructor for specific entry of variables.
    public TradingCards(int cardNumber, String itemname, int quantityOnHand, double itemprice) {
        cardnumber = cardNumber;
        setName(itemname);
        setQuantityOnHand(quantityOnHand);
        setPrice(itemprice);
    }

    // Method to set the cardNumber for display
    public void setNumber(int cardNumber) {
        cardnumber = cardNumber;
    }
    // Method to set the name
    public void setName(String itemname) {
        cardname = itemname;
    }


    // Sets quantity on hand and if negative, defaults to zero.
    public void setQuantityOnHand(int quantityOnHand) {
        if (quantityOnHand > 0) {
            quantity = quantityOnHand;
        }
        else { quantity = 0; }
    }


    // Set value of a product and defaults it to zero if negative.
    public void setPrice(double itemPrice) {
        if (itemPrice > 0.00) {
            value = itemPrice;
        }
        else { value = 0.00; }
    }

    // Get the product's card number, name, others
    public int getNumber() {
        return cardnumber;
    }

    public String getName() {
        return cardname;
    }

    public int getQuantityOnHand() {
        return quantity;
    }

    public double getPrice() {
        return value;
    }

    // Calculate the value of quantity on this particular item.
    public double getItemValue() {
        return (value * (double)quantity);
    }
    public int compareTo(Object object) {
        return cardname.compareTo(((TradingCards) object).getName());
    }


    public String toString() {
        return cardname;

}

}
/**
*
* @author Ken
*/





class CardInventory{


    // Setup an array of Cards (set it to hold 50 items)
    private int inventorySize;// = 50;

    private TradingCards items[] = new TradingCards[50];
    
    DecimalFormat formatter = new DecimalFormat("$##,###.00");

    
     // method calculates total value of inventory
    public double getTotalValue()
    {
  
       double totalValue = 0;
       for (int i = 0; i < inventorySize; i++)
            totalValue += items[i].getItemValue();
       return totalValue;
    } // end getTotalValue

    
    
    CardInventory()//constructor for 'inventorySize' variable
    {
    inventorySize = 0;
    }

    
    public int getQuantityOnHand(int m)
    {        
        return items[m].getQuantityOnHand();        
    }

    
    public double getCardValue(int b)
    {
        return items[b].getPrice();      
    }

    
    public int getCardNumber(int c)
    {
        return items[c].getNumber();
    }


    public String getReFee(int d)
    {
        return formatter.format(items[d].getItemValue() * .05);
    }


    public String getRankInv(int e)
    {
        return "No Rank";        
    }



    public int getinventorySize()
     {
     return inventorySize;
     }


    
    // Adds cards to the array in first spot available
    public void addCards(TradingCards item) {
        {
            items[inventorySize] = item;
            ++inventorySize;
              return;

            
        }
    }
/*
    //************************************new addcards test
    public void addCardsRank(RankAdded rcard)
    {
    rankCard[inventorySize] = rcard;
    ++inventorySize;
    return;

    }
*/





    public TradingCards getCards(int n) //use in GUI
    {// protects n and keep in range
       if (n<0)
           n = 0;
       else if (n >= inventorySize)
           n = inventorySize - 1;
       return items[n];
     }


public void sort()
{
    Arrays.sort(items, 0, inventorySize);
}
    // Method to print inventroy
    public void printInventory() {
        System.out.println("\nPrinting items in inventory...\n");

        boolean hasItems = false;

        sort();


        for (TradingCards item : items) {
            if (item != null)            {
                hasItems = true;

                System.out.println(item.toString() + " Quantity: "
                        + item.getQuantityOnHand() + " Value of Stock: "
                        + formatter.format(item.getItemValue()));
            }
            
        }
System.out.printf("\nTotal value of the inventory is $%.2f\n", getTotalValue());

        // Message if inventory is zero.
        if (!hasItems) { System.out.println("There are " +
                "no cards in inventory.\n"); }
    }


    }
class RankAdded extends TradingCards {
    // Holds the drivers rank in the standings
    private String cardrank;



    public RankAdded(int cardNumber, String itemname, int quantityOnHand,
            double itemprice, String rank) {

        super(cardNumber, itemname, quantityOnHand, itemprice);
        cardrank = rank;
    }


    public void setRank(String rank) {
        cardrank = rank;
    }

    

    public String getRank() {
        
    return cardrank;
      
    }

    // Overrides getItemValue() in TradingCards class
    // adding a 5% restocking fee on top
    public double getItemValue() {
        return super.getItemValue() * 1.05;
    }

    // calculates just the 5% restocking fee
    public double getRestockingFee() {
        return super.getItemValue() * .05;
    }
}




GUIa.java below.....

CODE

/*
* Ken
*/
package inventoryprogram4;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Icon;
import javax.swing.ImageIcon;

/**
*
* @author Ken
*/
public class GUIa extends JFrame {

    private CardInventory inventory;                  // create new reference to object
    //private RankAdded RankAdder;
    private JPanel jpOuterPanel;               // for outermost frame
    private JPanel jpInstructsPanel;          // the instructions
    private JLabel jlCurrentCardName;         //the current data header
    private JLabel jlCurrentQuantity;  // the data contents
   // next line for test of Rank *********
    private JLabel jlCurrentRank;
    // end test**************************
    private JLabel jlCurrentValue;
    private JLabel jlCurrentCardNumber;
    private JLabel jlCurrentReFee;
    private JTextField jtfValue;                 // for data acquisition
    private JButton jbNext;                      // Next button
    private JButton jbFirst;
    private JButton jbPrev;
    private JButton jbLast;

    private int CurrentCard;             //selecting the current card
    private JLabel jlIconJpg;


    //GUIa(CardInventory inventory)
    GUIa(CardInventory inventory)
    {

        super(" NASCAR Trading Card Inventory Program");
        //*************
        //RankAdded rank = new RankAdded();
        this.inventory = inventory;
        CurrentCard = 0;

        // creates outer panel
        JPanel jp;


        jpOuterPanel = new JPanel();
        jpOuterPanel.setLayout(new BoxLayout(jpOuterPanel, BoxLayout.Y_AXIS));
        

        // creates title line
        jpInstructsPanel = new JPanel();
        jpInstructsPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
        JLabel jLabel = new JLabel("Click on the 'Next Entry' button to see the next Card");
        jpInstructsPanel.add(jLabel);
        jpOuterPanel.add(jpInstructsPanel);



        

        Icon logo = new ImageIcon(getClass().getResource("logo.gif"));
            
            jlIconJpg = new JLabel(logo, SwingConstants.RIGHT);
            jlIconJpg.setToolTipText("Company Logo");
            jpOuterPanel.add(jlIconJpg);
            

        // creates current data line
        jp = new JPanel();
        jp.setLayout(new FlowLayout(FlowLayout.LEFT));
        jlCurrentCardName = new JLabel("" + inventory.getCards(CurrentCard));
        jp.add(jlCurrentCardName);
        jpOuterPanel.add(jp);

        // creates the data contents display line
        jp = new JPanel();
        jp.setLayout(new FlowLayout(FlowLayout.LEFT));
        jlCurrentQuantity = new JLabel("" +
                inventory.getQuantityOnHand(CurrentCard));
        jp.add(jlCurrentQuantity);
        jpOuterPanel.add(jp);


        // creates the value of current card
        jp = new JPanel();
        jp.setLayout(new FlowLayout(FlowLayout.LEFT));
        jlCurrentValue = new JLabel("" +
                inventory.getCardValue(CurrentCard));
        jp.add(jlCurrentValue);
        jpOuterPanel.add(jp);


        // creates the card number of the current card
        jp = new JPanel();
        jp.setLayout(new FlowLayout(FlowLayout.LEFT));
        jlCurrentCardNumber = new JLabel("" + inventory.getCardNumber(CurrentCard));
        jp.add(jlCurrentCardNumber);
        jpOuterPanel.add(jp);

        // creates the restock fee of the current card
        jp = new JPanel();
        jp.setLayout(new FlowLayout(FlowLayout.LEFT));
        jlCurrentReFee = new JLabel("" + inventory.getReFee(CurrentCard));
        jp.add(jlCurrentReFee);
        jpOuterPanel.add(jp);

        // test of Rank *************************************
         // creates the rank of the current card
        jp = new JPanel();
        jp.setLayout(new FlowLayout(FlowLayout.LEFT));
        jlCurrentRank = new JLabel("" + (inventory.getRankInv(CurrentCard)));
        jp.add(jlCurrentRank);
        jpOuterPanel.add(jp);








        //create text field for data acquisition
        jp = new JPanel();
        jp.add(new JLabel("Value of Card collection:"));
        jp.setLayout(new FlowLayout(FlowLayout.CENTER));
        jtfValue = new JTextField(4);
        jtfValue.setText("$" + inventory.getTotalValue());
        jtfValue.setEditable(false);
        jp.add(jtfValue);
        jpOuterPanel.add(jp);

        updateFields();                // updates field after next button

        

        //************************************************************
        //BUTTONS
        // set up and add the FIRST button
        jp = new JPanel();
        jp.setLayout(new FlowLayout(FlowLayout.CENTER));
        jbFirst = new JButton("First Entry");
        jbFirst.addActionListener(new FirstButtonHandler());
        jp.add(jbFirst);
        jpOuterPanel.add(jp);

        // set up and add the PREVIOUS button
        jp = new JPanel();
        jp.setLayout(new FlowLayout(FlowLayout.CENTER));
        jbPrev = new JButton("Previous Entry");
        jbPrev.addActionListener(new PrevButtonHandler());
        jp.add(jbPrev);
        jpOuterPanel.add(jp);


        // set up and add the NEXT button
        jp = new JPanel();
        jp.setLayout(new FlowLayout(FlowLayout.CENTER));
        jbNext = new JButton("Next Entry");
        jbNext.addActionListener(new NextButtonHandler());
        jp.add(jbNext);
        jpOuterPanel.add(jp);


        // set up and add the LAST button
        jp = new JPanel();
        jp.setLayout(new FlowLayout(FlowLayout.CENTER));
        jbLast = new JButton("Last Entry");
        jbLast.addActionListener(new LastButtonHandler());
        jp.add(jbLast);
        jpOuterPanel.add(jp);

        //end Buttons
        //*******************************************************************


        // quit application when window is closed
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(200, 200, 600, 500); // set frame location and size

        // set up the outer panel, turn it on.
        setContentPane(jpOuterPanel);
        setResizable(true);
        setVisible(true);

    } // end GUI constructor

    private void updateFields() // updates info on the current card
    {
        jlCurrentCardName.setText((CurrentCard + 1) + ": " +
                inventory.getCards(CurrentCard));

        jlCurrentCardNumber.setText("Card Number = " +
                inventory.getCardNumber(CurrentCard));

        jlCurrentQuantity.setText("Quantity on hand of this card = " +
                inventory.getQuantityOnHand(CurrentCard));

        jlCurrentValue.setText("Value (per card) = " +
                inventory.getCardValue(CurrentCard));

        jlCurrentReFee.setText("Restock fee for this card = " +
                inventory.getReFee(CurrentCard));

        jlCurrentRank.setText("Rank for this driver = " +
                inventory.getRankInv(CurrentCard));








    } // end updateFields method



//**********************************************************************
//Button handlers



    // inner class to handle the NEXT button
    class NextButtonHandler implements ActionListener {

        public void actionPerformed(ActionEvent event) {    // sequences through the inventory
            ++CurrentCard;
            if (CurrentCard < inventory.getinventorySize()) {
                updateFields();
            } else {
                //jbNext.setEnabled(false);
                CurrentCard = 0;
                updateFields();
            }
        } // end method
    }// end inner class

  
   // inner class to handle the FIRST button
    class FirstButtonHandler implements ActionListener {

        public void actionPerformed(ActionEvent event) {    // assigns CurrentCard to FIRST
            CurrentCard = 0;
             {
                updateFields();

                //jbFirst.setEnabled(false);
            }
        } // end method
    }// end inner class


    // inner class to handle the PREVIOUS button
    class PrevButtonHandler implements ActionListener {

        public void actionPerformed(ActionEvent event) {    // sequences through the inventory
            --CurrentCard;
            if (CurrentCard < 0)
            {
                CurrentCard = (inventory.getinventorySize() -1);
                updateFields();
            } else
            {
                updateFields();
                //jbPrev.setEnabled(false);
            }
        } // end method
    }// end inner class

    // inner class to handle the LAST button
    class LastButtonHandler implements ActionListener {

        public void actionPerformed(ActionEvent event) {    // assigns CurrentCard index to last in array
            CurrentCard = (inventory.getinventorySize() - 1);

                updateFields();

                //jbLast.setEnabled(false);

        } // end method
    }// end inner class

    //***********************************************************************

}// end class GUI



User is offlineProfile CardPM
+Quote Post


Martyr2

RE: GUI Display Of Subclass Values

1 Jul, 2009 - 03:31 PM
Post #2

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 7,246



Thanked: 820 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
Ok, you have a design problem here that I will do my best to try and explain. Your class CardInventory has an array of TradingCards objects. TradingCards is the base class for your RankAdded class.

You can add objects to this array of type TradingCards or RankAdded because they are a type of TradingCards object. However, Java can only assume that all objects in that array are of type TradingCards... the base class. That means that it doesn't know about anything implemented in RankAdded class, where you have your rank setup.

In other words, it sees an array of TradingCards objects, not a list of TradingCards and RankAdded objects.

To fix this we need to first check if the current item in the array is of type "RankAdded" and if it is, cast it back to a RankAdded object so we can call its getRank() method which will return the rank to the GUI.

Here is how your getRankInv() method should look....

CODE

public String getRankInv(int e)
{
     // Check if this item is of the type "RankAdded"
     // Then cast it back to RankAdded so we can call its getRank() method
     if (items[e] instanceof RankAdded) {
          RankAdded rank = (RankAdded)items[e];
          return rank.getRank();
     }
     else { return "No Rank"; }
}


Once you make this change you should then see the rank appearing on the GUI labels for your two items.

Now I suggest you study what I am doing here because it is important that you know what is going on here. Since RankAdded is a type of TradingCards, it will fit in the array, but Java can only know as much as what is defined in a TradingCards object. It can't see the added functionality in RankAdded objects.

What we are doing is checking if the object we are accessing in the array is a RankAdded class and then telling java to treat it as a RankAdded object by casting it back. Then it will see the getRank method.

Hope this helps!

"At DIC we be RankAdding code ninjas... we are those guys with the highest ranking trading card on the block, those guys you just hate because you are jealous" decap.gif
User is offlineProfile CardPM
+Quote Post

woodygeo

RE: GUI Display Of Subclass Values

1 Jul, 2009 - 06:36 PM
Post #3

New D.I.C Head
*

Joined: 15 Jun, 2009
Posts: 2

Martyr2 is awesome!!

That piece of code worked perfectly - I ran across the instanceOf function yesterday, but could not figure out if it would help me with this. ...Yes, it does make sense what it is doing - that also explains why when I used the "toString()" method it was giving me both field's values - it was only looking at the main class.

Thank you Again!!!! Very helpful!!!!!
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 11/8/09 04:52AM

Live Java Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month