Results 1 to 12 of 12
  1. #1
    s34nn4 is offline Member
    Join Date
    Nov 2008
    Posts
    9
    Rep Power
    0

    Default [SOLVED] Checkbox new to Java

    Hi there everyone Im currently a novice in Java. My problem is I would like to put an Item on my applet... Using Checkbox I would like the user to click a certian box for an Item so they can purchase and automatically add the sum and will appear the total amount at the bottom of the applet I just think that its more convient doing that. Just to clarify these is only apply on the item that was checked by the user and will display the sum right after the calculate button. can that be done using checkbox?
    here is my current sample code though Im still figuring out how to deal with this for 2days. Please help me Im just new to Java. Thanks in advance.

    Java Code:
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    
    
    public class MidMP2 extends Applet implements ItemListener,ActionListener
    
            
    {
    
    String mouse,mousei,mr;
    int m1=16,m2=30;
        
    Label companynameLabel = new Label ("Electronics & Accessories");
    Label outputLabel = new Label("We will deliver your order on time!");
    
    
      
       
        Checkbox mouse2 = new Checkbox ("\n Mouse",false);
              
        Checkbox mouse3 = new Checkbox ("\n Printer",false);
      
        Checkbox hiddenbox = new Checkbox("",true);
        
        Button calcButton = new Button ("Calculate");
        public void init() {
           
            setBackground(Color.orange);
            add(companynameLabel);          
            add(mouse2);
                mouse2.addItemListener(this);
            add(mouse3);
                mouse3.addItemListener(this);
          
            add(calcButton);
            calcButton.addActionListener(this);
            add(outputLabel);
           
    
        }
         
            
               
                public void itemStateChanged(ItemEvent choice)
                {
                  
                    
             
                       int price;
                       
                       
                       
                        
                        if (mouse2.getState())
                           price =16;
                        else if (mouse3.getState())
                           price = 14;
                        else 
                           price = 0;
                      
                    outputLabel.setForeground(Color.black);
                    outputLabel.setText("This Item Cost "+ Math.round(price)+ " Dollars");
                }
                       public void actionPerformed(ActionEvent e)
         
         {
               try
               {
                           String  args=e.getActionCommand();
                           
                          int price1=Integer.parseInt(mr);
                          if(args =="Calculation")
                          
                              if(mouse2.getState())
         z
                         if (price1 >= 16 )
                                throw new NumberFormatException();
                        
                        if
                            (price1 == 16)
                           outputLabel.setText("your total"+(m2));
                                
               }
               catch(NumberFormatException a)
                
               {         
                  outputLabel.setText("your total "+(m1)); 
                   
               }
                       }
    }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,573
    Rep Power
    23

    Default

    Can you describe what your program currently does? And what needs to be fixed/added to make it do what you want it to do?

    The code you've posted does NOT compile. Please clean it up so that it compiles.

  3. #3
    s34nn4 is offline Member
    Join Date
    Nov 2008
    Posts
    9
    Rep Power
    0

    Default

    Norm sorry for the long wait and thanks for your help.

    Java Code:
    
    /*
     * This is an applet that is use to get an order.
     * it display the cost right after it was clicked and all the active box must calculate the sum to get the total price.
     * 
     */
    
    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    
    
    public class MidMP2 extends Applet implements ItemListener,ActionListener
    
            
    {
    
    
        
            int price ;
           
          
    Label companynameLabel = new Label ("Electronics & Accessories");
    Label outputLabel = new Label("We will deliver your order on time!");
    
    
      /*
       *this is all the sample items but there's more to include after Im done.
       * I'll add more items if I figure out what to do to calcute the checked boxes.
        
       */ 
        Checkbox mousecheckBox = new Checkbox ("\n Mouse",false);
              
        Checkbox printercheckBox = new Checkbox ("\n Printer",false);
      
        Checkbox speakercheckBox = new Checkbox ("\n Speaker",false);
        
        Checkbox inkCartcheckBox = new Checkbox ("\n Ink Cartridge");
        
        Checkbox hiddenbox = new Checkbox("",true);
        
        
        
        Button calcButton = new Button ("Calculate");
       
        //the reset button is not working... what shall i put to reset the checkbox?
        
        Button resetButton = new Button ("Reset");
                   
                    
        public void init() {
             setSize(200,150);
            setBackground(Color.orange);
            add(companynameLabel);        
            
            add(printercheckBox);
                printercheckBox.addItemListener(this);
                printercheckBox.requestFocus();
            add(mousecheckBox);
                mousecheckBox.addItemListener(this);
                mousecheckBox.requestFocus();
            add(speakercheckBox);
                speakercheckBox.addItemListener(this);
            add(inkCartcheckBox);
                inkCartcheckBox.addItemListener(this);
            add(calcButton);
            calcButton.addActionListener(this);
            add(resetButton);
            resetButton.addActionListener(this);
            add(outputLabel);
        
                    
    
        }
         
            
               
        @SuppressWarnings("empty-statement")
                public void itemStateChanged(ItemEvent choice)
                {
       
                   
          
                    
                                           
                        if (printercheckBox.getState())
                           price =16;
                      
                        else if (mousecheckBox.getState())
                           price = 14;
                       
                        else if (speakercheckBox.getState())
                            
                            price = 18;
                                    
                        else if (inkCartcheckBox.getState())
                                price =12;
                        
                        
                        else 
                            price=0;
                      
                     
                     
                    outputLabel.setForeground(Color.black);
                    outputLabel.setText("the price of this is " +(price));
                   
                }
                       public void actionPerformed(ActionEvent e)
         
         {
               try
               {
                           String  args=e.getActionCommand();
                          
                         if  (args =="Calculation");
                                                 
                         if
                              (price  == 0)
                             
                           
                                throw new NumberFormatException();
                     
                    
                      
                         
                               
                           {
                              outputLabel.setText("Your Total Order is "+(price));
                           }            
              
               }
               
               catch(NumberFormatException a)
                
                           {         
                               outputLabel.setText("Please Choose an Order");
                               outputLabel.setForeground(Color.red);
                  
                
                  
                  hiddenbox.setState(true);  
                  {
                              String  args=e.getActionCommand();
                              
                           if (args=="Reset")
                       
                               //
                      
                          
                      {
                  }
                      
    }
    }
    }
    }

  4. #4
    s34nn4 is offline Member
    Join Date
    Nov 2008
    Posts
    9
    Rep Power
    0

    Default

    What would be the missing link to calculate the checked box?

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    A problem that I see here is that everything is in one big huge unhappy class. Why not split things off? For instance you could have a small StoreItem class that would hold the item's name, it's price and any other pertinent bits of info that may be necessary, a ShoppingCart class that would gather the things selected together and a GUI to show the results. This way when it comes time to calculate the total price, the GUI simply asks the ShoppingCart to tally the results of all its items, and the shopping cart does this by iterating through its list of StoreItems asking each its price and perhaps count (though count hasn't been implemented in your GUI yet).

    The key here is to divide and conquer.

  6. #6
    s34nn4 is offline Member
    Join Date
    Nov 2008
    Posts
    9
    Rep Power
    0

    Default

    thanks a for the info.

    btw can you give a sample codes where I can seperate this class?

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    btw can you give a sample codes where I can seperate this class?
    Nope as that would be cheating and I don't condone cheating. I would gladly help you with your code though.

  8. #8
    s34nn4 is offline Member
    Join Date
    Nov 2008
    Posts
    9
    Rep Power
    0

    Default Solved

    None of which are needed such as declaring the another class.
    everything is fine though. however i just miss the logic.

    here you go to prove that no need to declare another class.

    Java Code:
    import java.awt.*;
    import java.applet.*; 
    import java.awt.event.*; 
    
    public class shoppingcart extends Applet implements ActionListener
    {
    //labels declared
    Label welcomeLabel = new Label (" E&A corporation ");
    Label price = new Label("The total price is $0");
    Label current = new Label("The current price is $0");
    Label setLabel = new Label("Select a pheriperals");
    
    //string text declared
    String currentString = new String();
    String priceString = new String();
    
    
    //checkboxes identified
    Checkbox printerBox = new Checkbox("Printer $225");
    Checkbox headsetBox = new Checkbox("headset $155");
    Checkbox inkBox = new Checkbox("ink (black & white) $40");
    Checkbox ink2Box = new Checkbox("colored ink $50");
    Checkbox speakerBox = new Checkbox("Speaker $65");
    Checkbox mouseBox = new Checkbox("Mouse $30");
    Checkbox keyboardBox = new Checkbox("keyBoard $95");
    Checkbox monitorBox = new Checkbox("LCD Monitor $300");
    Checkbox usbBox = new Checkbox("USB Flash Drive $60");
    Button calcButton = new Button ("Calculate");
    Button resetButton = new Button ("Reset");
    Label outputLabel = new Label("Click the button ");
    Label outputLabel2 = new Label("to get the Total Price ");
    
    
    //price variables of the services declared along with the totalPrice
    int totalPrice = 0;
    int printerBoxPrice = 225, headsetBoxPrice = 155, inkBoxPrice = 40, ink2BoxPrice =50;
    int speakerBoxPrice = 65, mouseBoxPrice = 30, keyboardBoxPrice = 95,  monitorBoxPrice =300, usbBoxPrice = 60;
    
    public void init()
    {
    setFont(new Font ("tahoma", Font.PLAIN,16));
    setSize(200,550);
    setBackground (Color.orange);
    add(welcomeLabel);
    add(setLabel);
    add(printerBox);
    add(headsetBox);
    add(inkBox);
    add(ink2Box);
    add(speakerBox);
    add(mouseBox);
    add(keyboardBox);
    add(monitorBox);
    add(usbBox);
    add(current);
    add(calcButton);
        calcButton.addActionListener(this);
    add(resetButton);
        resetButton.addActionListener(this);
    add(outputLabel);
    add(outputLabel2);
    add(price);
    }
    
    
    
    public void actionPerformed(ActionEvent e)
    {
    
    
    if (printerBox.getState())
    
    currentString = ("The current price is $"+ Integer.toString
    (printerBoxPrice));
    
    if (headsetBox.getState())
    
    currentString = ("The current price is $"+ Integer.toString (headsetBoxPrice))
    ;
    
    if (inkBox.getState())
    
    currentString = ("The current price is $"+ Integer.toString (inkBoxPrice))
    ;
    
    if (ink2Box.getState())
    
    currentString = ("The current price is $"+ Integer.toString (ink2BoxPrice))
    ;
    
    if (speakerBox.getState())
    
    currentString = ("The current price is $"+ Integer.toString (speakerBoxPrice))
    ;
    
    if (mouseBox.getState())
    
    currentString = ("The current price is $"+ Integer.toString (mouseBoxPrice))
    ;
    
    if (keyboardBox.getState())
    
    currentString = ("The current price is $"+ Integer.toString (keyboardBoxPrice)
    );
    
    if (monitorBox.getState())
    
    currentString = ("The current price is $"+ Integer.toString (monitorBoxPrice)
    );
    
    
    if (usbBox.getState())
    
    currentString = ("The current price is $"+ Integer.toString (usbBoxPrice))
    ;
    
    
    current.setText (currentString);
    
    //total price is calculated
    totalPrice = 0;
    
    if (printerBox.getState())
    totalPrice += printerBoxPrice;
    
    if (headsetBox.getState())
    totalPrice += headsetBoxPrice;
    
    if (inkBox.getState())
    totalPrice += inkBoxPrice;
    
    if (ink2Box.getState())
    totalPrice += ink2BoxPrice;
    
    if (speakerBox.getState())
    totalPrice += speakerBoxPrice;
    
    if (mouseBox.getState())
    totalPrice += mouseBoxPrice;
    
    if (keyboardBox.getState())
    totalPrice += keyboardBoxPrice;
    
    if (monitorBox.getState())
    totalPrice += monitorBoxPrice;
    
    if (usbBox.getState())
    totalPrice += usbBoxPrice;
    
    
    priceString = ("The total price is $" + Integer.toString (totalPrice));
    price.setText (priceString);
    
    
    printerBox.setState(false);
    headsetBox.setState(false);
    inkBox.setState(false);
    ink2Box.setState(false);
    speakerBox.setState(false);
    mouseBox.setState(false);
    keyboardBox.setState(false);
    monitorBox.setState(false);
    usbBox.setState(false);
               }
    
    
     
     }

  9. #9
    s34nn4 is offline Member
    Join Date
    Nov 2008
    Posts
    9
    Rep Power
    0

    Default

    so there is no need to seperate it.

    just a simple code though.

    thank for your help buddy...

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    I'm not talking about need, though, I'm talking about writing good code, code that would be easy to debug and extend. Congrats on solving this.

    and you're welcome,... I think?
    Last edited by Fubarable; 11-09-2008 at 02:03 PM.

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    For instance, here's a similar program that I created a few yrs ago when learning Java creates a Sandwich. It would be a lot more complicated, more difficult to debug, and much more difficult to extend if not split into different classes.

    Java Code:
    class SWIngredient
    {
        private String name;
        private double cost;
    
        public SWIngredient(String name, double cost)
        {
            this.name = name;
            this.cost = cost;
        }
        public String getName()
        {
            return name;
        }
        public double getPrice()
        {
            return cost;
        }
        
        @Override
        public String toString()
        {
            return name + " " + cost;
        }
        
    }
    Java Code:
    import java.util.ArrayList;
    import java.util.List;
    
    class SWSandwich
    {
        private List<SWIngredient> ingredients = new ArrayList<SWIngredient>();
        private Size size;
        
        public SWSandwich()
        {}
        
        public SWSandwich(Size size)
        {
            this.size = size;
        }
        
        public void setSize(Size size)
        {
            this.size = size;
        }
        
        public void addIngredient(SWIngredient ingredient)
        {
            ingredients.add(ingredient);
        }
        
        public void clear()
        {
          ingredients.clear();
        }
        
        public double calcPrice()
        {
            double price = 0.0;
            price += size.getPrice();
            for (SWIngredient ingredient : ingredients)
            {
                price += ingredient.getPrice();
            }
            return price;
        }
        
        @Override
        public String toString()
        {
            StringBuilder sb = new StringBuilder();
            sb.append(size.toString().toLowerCase() + ", ");
            for (SWIngredient ingredient : ingredients)
            {
                sb.append(ingredient.getName() + " ");
            }
            return sb.toString(); 
        }
        
        static enum Size
        {
            SMALL(2.50), MEDIUM(3.50), LARGE(4.50);
            
            private double price;
            
            private Size(double price)
            {
                this.price = price;
            }
            
            public double getPrice()
            {
                return price;
            }
        }
    }
    Java Code:
    // imports abbreviated for posting purposes only. 
    import java.awt.*;
    import java.awt.event.*;
    import java.text.NumberFormat;
    import java.util.*;
    import javax.swing.*;
    
    class SWSandwichGui extends JPanel
    {
      private static final int STRUT_SIZE = 20;
      private static final String CALCULATE_PRICE = "Calculate Price";
      private static final String CLEAR = "Clear";
      private static final String EXIT = "Exit";
      private JComboBox sizeCombo = new JComboBox(SWSandwich.Size.values());
      private Integer[] countArray =
      {
        0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 25, 30, 35, 40, 45, 50, 75, 100
      };
      private JComboBox countCombo = new JComboBox(countArray);
      private JTextField priceField = new JTextField();
    
      //** here I use the Ingredient class objects
      private Map<SWIngredient, JCheckBox> ingredientMap = new HashMap<SWIngredient, JCheckBox>();
      private SWIngredient[] ingredientList =
      {
        new SWIngredient("Ham", 2.50), 
        new SWIngredient("Swiss Cheese", 0.75),
        new SWIngredient("American Cheese", 0.75),
        new SWIngredient("Pepperoni", 3.25), 
        new SWIngredient("Olives", 1.25),
        new SWIngredient("Onions", 0.25),
      };
    
      SWSandwichGui()
      {
        setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    
        JPanel sizePane = new JPanel(new BorderLayout(15, 0));
        sizePane.add(new JLabel("Size:"), BorderLayout.WEST);
        sizePane.add(sizeCombo, BorderLayout.CENTER);
        JPanel countPane = new JPanel(new BorderLayout(15, 0));
        countPane.add(new JLabel("Count:"), BorderLayout.WEST);
        countPane.add(countCombo, BorderLayout.CENTER);
        countCombo.setSelectedIndex(-1);
        sizeCombo.setSelectedIndex(-1);
    
        JPanel sizeCountPane = new JPanel(new GridLayout(1, 0, 25, 0));
        sizeCountPane.add(sizePane);
        sizeCountPane.add(countPane);
        add(sizeCountPane);
        add(Box.createVerticalStrut(STRUT_SIZE));
    
        JPanel ingredientPane = new JPanel(new GridLayout(0, 3, 5, 5));
        for (int i = 0; i < ingredientList.length; i++)
        {
          JCheckBox cb = new JCheckBox(ingredientList[i].getName());
          ingredientMap.put(ingredientList[i], cb);
          ingredientPane.add(cb);
        }
        add(ingredientPane);
        add(Box.createVerticalStrut(STRUT_SIZE));
    
        JPanel pricePanel = new JPanel(new BorderLayout(15, 0));
        pricePanel.add(new JLabel("Calculated Price"), BorderLayout.WEST);
        pricePanel.add(priceField, BorderLayout.CENTER);
        priceField.setEditable(false);
        add(pricePanel);
        add(Box.createVerticalStrut(STRUT_SIZE));
    
        JButton priceButton = new JButton(CALCULATE_PRICE);
        JButton clearButton = new JButton(CLEAR);
        JButton exitButton = new JButton(EXIT);
    
        ButtonListener btnListener = new ButtonListener();
        priceButton.addActionListener(btnListener);
        clearButton.addActionListener(btnListener);
        exitButton.addActionListener(btnListener);
        JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 20, 0));
        buttonPanel.add(priceButton);
        buttonPanel.add(clearButton);
        buttonPanel.add(exitButton);
        add(buttonPanel);
      }
    
      private class ButtonListener implements ActionListener
      {
        // ** this is where the model comes into play
        @Override
        public void actionPerformed(ActionEvent e)
        {
          String command = e.getActionCommand();
          if (command.equals(CALCULATE_PRICE))
          {
            if (countCombo.getSelectedIndex() == -1 || sizeCombo.getSelectedIndex() == -1)
            {
              return;
            }
            int count = (Integer) countCombo.getSelectedItem();
            SWSandwich sandwich = new SWSandwich(); // here I use the "model" 
            sandwich.setSize((SWSandwich.Size) sizeCombo.getSelectedItem());
            for (SWIngredient ingredient : ingredientList)
            {
              if (ingredientMap.get(ingredient).isSelected())
              {
                sandwich.addIngredient(ingredient);
                System.out.println(ingredient);
              }
            }
            double price = count * sandwich.calcPrice();
            NumberFormat nf = NumberFormat.getCurrencyInstance();
            priceField.setText(nf.format(price));
    
          }
          else if (command.equals(CLEAR))
          {
            for (SWIngredient ingredient : ingredientList)
            {
              ingredientMap.get(ingredient).setSelected(false);
            }
            priceField.setText("");
            sizeCombo.setSelectedIndex(-1);
            countCombo.setSelectedIndex(-1);
          }
          else if (command.equals(EXIT))
          {
            Container window = SWSandwichGui.this.getTopLevelAncestor();
            if (window instanceof Window)
            {
              ((Window) window).dispose();
            }
          }
        }
      }
    
      private static void createAndShowUI()
      {
        JFrame frame = new JFrame("SandwichGui");
        frame.getContentPane().add(new SWSandwichGui());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    
      public static void main(String[] args)
      {
        java.awt.EventQueue.invokeLater(new Runnable()
        {
          public void run()
          {
            createAndShowUI();
          }
        });
      }
    }

  12. #12
    RogyRorcE is offline Member
    Join Date
    Apr 2009
    Posts
    1
    Rep Power
    0

    Default flea market cart

    Hello guys

    I think of buying the following: "shopping-cart-script net/ecommerce-threats-558964977f150e3c58a8ef3fa729c574 html ]ecommerce web site hosting " - it is something like online shopping cart
    I am going to buy the license, is it realy needed?
    I hope you help me I need consulting

    Thanks in advance,

    PS: and sorry for my english, I am from Denmark

Similar Threads

  1. How to wrap words in checkbox,push buttons
    By gunjan.raizada in forum SWT / JFace
    Replies: 3
    Last Post: 08-05-2008, 12:24 PM
  2. How to construct checkbox in rtf document using iText?
    By soumyanil in forum Advanced Java
    Replies: 0
    Last Post: 07-28-2008, 11:05 AM
  3. How to retain the checkbox selected after page load...?
    By prabhurangan in forum JavaServer Pages (JSP) and JSTL
    Replies: 0
    Last Post: 07-24-2008, 08:13 AM
  4. How to use ItemListener for CheckBox class
    By Java Tip in forum javax.swing
    Replies: 0
    Last Post: 04-23-2008, 08:18 PM
  5. checkbox
    By Alan in forum AWT / Swing
    Replies: 3
    Last Post: 05-18-2007, 10:10 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •