Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Need help understanding this code!

  1. #1
    Member
    Join Date
    Sep 2012
    Posts
    32
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Need help understanding this code!

    I have a midterm coming up tomorrow night, and it's basically us reading a set of codes and seeing where the errors are and what set of codes are needed to make the program compile succesfully.


    Here is the program I am using to review for the midterm, it is a menu which uses frames and panels, and has the user interact with check boxes to pick what items he/she wants, then lists the invoice of all the transactions.

    Breakfast.java

    import javax.swing.JOptionPane;
    import javax.swing.JFrame;
    import javax.swing.*;
    import java.text.NumberFormat;
    import java.awt.Font;
     
    public class Breakfast
    {
        public static JFrame frame;
        static public void main(String[] args)
        {
          frame = new JFrame ("Ben's Breakfast Bar Menu");  // creates frame with "Ben's Breakfast Bar Menu" as title
          frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); // Sets the X button to close the program
     
          MenuOptionsPanel panel = new MenuOptionsPanel(); // calls upon MenuOptionsPanel class
          frame.getContentPane().add (panel); 
     
          frame.pack();
          frame.setLocation(200,300);
          frame.setVisible(true);
        }
     
        public static void  displayInvoice(JCheckBox[] items,float[] prices,String[] namesOfItems)
        {		
            NumberFormat money = NumberFormat.getCurrencyInstance();
    	float costOfItems=0.0f;
            String message = "";
            message+= "You ordered:\n------------------------------\n";
    	message+= String.format("%-24s%6s\n","Food Item","Price")+"\n";	
    	for (int index=0; index != items.length; index++)
    	{
                if (items[index].isSelected())
                {
    		costOfItems += prices[index];
                    message += String.format("%-24s%6s\n", namesOfItems[index], 
                                                               money.format(prices[index]));
     
                }
    	}
     
    	message +="\n------------------------------\n";
    	message +=String.format("%-24s%6s","AMOUNT TO PAY",  money.format(costOfItems));
    	message +=            "\n------------------------------\n\n";
    	message +="Thank you - enjoy your meal!";
     	JTextArea text = new JTextArea(message);
    	text.setBorder(null);
    	text.setOpaque(false);
    	text.setFont(new Font("Monospaced", Font.PLAIN, 14) );
            MenuOptionsPanel.frame2.setVisible(false);
    	JOptionPane.showMessageDialog(null, text);        
    	}
    }

    MenuOptionsPanel.java

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
     
    public class MenuOptionsPanel extends JPanel
    {
     
       private static JLabel prompt;
       private static JRadioButton one, two, three;
       private static MenuPanel mp;
       public static JFrame frame2;
     
       //-----------------------------------------------------------------
       //  Sets up a panel with a label and a set of radio buttons
       //  that present options to the user.
       //-----------------------------------------------------------------
       public MenuOptionsPanel()
       {
          setLayout(new GridLayout(4,1));       
          prompt = new JLabel ("Choose your option?");
          prompt.setFont (new Font ("Helvetica", Font.BOLD, 24));
     
          one = new JRadioButton ("Choose from the Menu");
          one.setBackground (Color.green);
          two = new JRadioButton ("Display Purchase Invoice");
          two.setBackground (Color.green);
          three = new JRadioButton ("Exit");
          three.setBackground (Color.green);
     
          ButtonGroup group = new ButtonGroup();
          group.add (one);
          group.add (two);
          group.add (three);
     
          MenuOptionListener mol = new MenuOptionListener();
          one.addActionListener (mol);
          two.addActionListener (mol);
          three.addActionListener (mol);
     
          add (prompt);
          add (one);
          add (two);
          add (three);
     
          setBackground (Color.green);
          setPreferredSize (new Dimension(400, 100));
       }
     
       //*****************************************************************
       //  Represents the listener for the radio buttons
       //*****************************************************************
       private class MenuOptionListener implements ActionListener
       {
          //--------------------------------------------------------------
          //  Calls the method to process the option for which radio
          //  button was pressed.
          //--------------------------------------------------------------
          public void actionPerformed (ActionEvent event)
          {
             Object source = event.getSource();
     
             if (source == one)
             {
               mp = new MenuPanel(); // instantiates the MenuPanel class 
               frame2 = new JFrame("Breakfast Menu");
               frame2.setDefaultCloseOperation (JFrame.DO_NOTHING_ON_CLOSE);           
               frame2.getContentPane().add(mp);
               frame2.setLocation(500,100);  // Adds parameters and coordinates for the panel 
               frame2.pack();
               frame2.setVisible(true);
             }
             else
                if (source == two)
                   Breakfast.displayInvoice(MenuPanel.items, MenuPanel.prices, MenuPanel.namesOfItems);
                else
                {   
                    String message; 
                    message = "Thanks for Dining at Bobs\nHope you enjoyed your meal";
                    JOptionPane.showMessageDialog (null, message);
                    System.exit(0);
     
                }
          }
       }
    }

    MenuPanel.java

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.NumberFormat;
     
    public class MenuPanel extends JPanel {
        private static NumberFormat fmt = NumberFormat.getCurrencyInstance(); 
        //NumberFormat is abstract base class for all number formats. Provides 
        //interface for formatting and parsing numbers.
        //getCurrencyInstance = returns a currency format for the spcecified locale
     
        //private boolean[] selectedItems;
     
        private JLabel foodColLabel,priceColLabel,priceLabel;
        public static JCheckBox[] items;
        private int numberOfItems;
        private JButton checkOut;
        public static String[] namesOfItems = {"Eggs","Blueberry Pancakes",
                                "Bagels with Cream Cheese",
            		     "English Muffin","Yogurt",
                                     "Corned Beef Hash","Toast",
    				     "Fries","Tea","Coffee","Hot Chocolate"};
        public static float[] prices = {2.75f,4.0f,1.5f,0.95f,1.0f,1.75f,
                                        0.75f,1.0f,0.75f,1.20f,1.95f};		
        // sets each price to the corresponding item. iE 2.75 for eggs etc
        public MenuPanel()
        {
     
    	numberOfItems = namesOfItems.length;		
    	//selectedItems = new boolean[numberOfItems];
    		// set layout
    	setLayout(new GridLayout(numberOfItems+2,2)); //sets the rows and collums
    		// insert labels 
    	foodColLabel = new JLabel("MenuItems");
    	priceColLabel = new JLabel("Price of Items");
    	add(foodColLabel);
    	add(priceColLabel);
    		// insert a check box for each item
    	items = new JCheckBox[numberOfItems];
    	for (int index=0; index != numberOfItems; index++)
    	// for (initialization; termination; increment
            // Keep in mind: intilization expression initializes the loop, executed 
            // once as the loop beings.
            // When terminaion expression evalutes to false, the loop terminates
     
            {
     
                items[index] = new JCheckBox(namesOfItems[index],false);
                items[index].setBackground (Color.green);
                add(items[index]);
                priceLabel = new JLabel(fmt.format(prices[index]));
                add(priceLabel);                
    		//	item[index].addItemListener(this);		}
            }
            checkOut = new JButton("CheckOut");
            ButtonListener bl = new ButtonListener();
            checkOut.addActionListener(bl);
     	add(checkOut);       
            setBackground (Color.green);
            setPreferredSize (new Dimension(400, 500));
       }        
     
     
        private class ButtonListener implements ActionListener
       {
          //--------------------------------------------------------------
          //  Calls the method when Button is pressed
          //--------------------------------------------------------------
          public void actionPerformed (ActionEvent event)
          {
             Object source = event.getSource();
     
             if (source == checkOut)
             {
             //  Breakfast.frame.setVisible(false);
               Breakfast.displayInvoice(items,prices,namesOfItems);
             }
          }
       }
    }

    As you can see I have added some notes, however I am having trouble understanding the boolean arguements in the code.

    For example, in the MenuPanel.java class, there is a segment of the code which states:

        {
     
                items[index] = new JCheckBox(namesOfItems[index],false);
                items[index].setBackground (Color.green);
                add(items[index]);
                priceLabel = new JLabel(fmt.format(prices[index]));
                add(priceLabel);                
    		//	item[index].addItemListener(this);		}
            }

    What does the items[index] = new JCheckBox(namesOfItems[index],false); what does the "false" mean?

    Same thing here:
       if (source == checkOut)
             {
             //  Breakfast.frame.setVisible(false);
               Breakfast.displayInvoice(items,prices,namesOfItems);
             }

    I am having trouble understanding the boolean value of (false)



    Another question:
    message +=String.format("%-24s%6s","AMOUNT TO PAY", money.format(costOfItems));

    I am having trouble understanding the %-24s and %6s, I know this statement is for the placement of the expression, so -24s would mean 24 characters to the left correct? and 6s would mean 6 characters to the right? Does the s mean string? So it would mean 24 strings to the left? What does the s represent? Also, what is the difference between %-24s and %-24f? Is the usage of s and f depending on what value the expression is printing?


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Need help understanding this code!

    What does the items[index] = new JCheckBox(namesOfItems[index],false); what does the "false" mean?
    What does the documentation say?

    Answers to both of your questions could have been found through any decent search engine and a little effort. The documentation to the language answers both questions.

    Correction. ...answers all of your questions. Do some reading and ask any questions you have left.

Similar Threads

  1. NEEDING HELP UNDERSTANDING A CODE FROM THREE CLASSES!!!
    By BlackShadow in forum Java Theory & Questions
    Replies: 1
    Last Post: April 6th, 2012, 11:11 PM
  2. NEEDING HELP UNDERSTANDING A CODE FROM THREE CLASSES!!!
    By BlackShadow in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 5th, 2012, 10:29 AM
  3. Help with understanding simple GUI Code
    By jordan123 in forum What's Wrong With My Code?
    Replies: 6
    Last Post: March 21st, 2012, 04:19 PM
  4. Problem understanding Java code modification
    By eagle09 in forum What's Wrong With My Code?
    Replies: 12
    Last Post: June 26th, 2011, 05:13 PM
  5. Help understanding this code
    By Zepx in forum Java Theory & Questions
    Replies: 2
    Last Post: October 20th, 2009, 11:18 AM