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 8 of 8

Thread: Arrays, JButton, and Action Listener

  1. #1
    Junior Member
    Join Date
    Sep 2013
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Arrays, JButton, and Action Listener

    Hi all,

    I have this homework assignment that I'm having trouble with. I'm to create a shopping cart with a JCombo box that offers the buyer four items to choose from and quantity. The issue I'm having is programming the "Buy Button". I need it to keep a running tally of items selected for purchase. For example, if I select Item 1 from the JCombcoBox and click buy, then select item 2 and a different quantity and click buy it keeps a running total of both item 1 and item 2 etc. I'm not sure what to place in JButtonActionPerformed to accomplish this. It needs to output what I bought to the JTextArea as well as keep a running total. Also, how do I program the clear button? I dropped a JButton on the JFrameForm and add an action listener to it.

    Here's what I have so far. I used a JFrameForm to create the GUI.

    Can anyone point me in the right direction?

    Here's the code I'm asking about:

        private void buyJButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
            // TODO add your handling code here:
        }                                          
     
        private void clearJButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
            // TODO add your handling code here:
        }                                            
     
        private void itemsJComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {                                                
     
            int itemindex = itemsJComboBox.getSelectedIndex();
     
            priceJTextField.setText(String.valueOf(prices[itemindex]));
     
     
        }

    And here's all my code:

    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    /**
     *
     * @author info3000-stu02
     */
    public class ShoppingCart extends javax.swing.JFrame {
     
        /**
         * Creates new form ShoppingCart
         */
        public ShoppingCart() {
            initComponents();
        }
     
        /**
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
     
            jLabel1 = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            itemsBoughtJTextArea = new javax.swing.JTextArea();
            itemsJComboBox = new javax.swing.JComboBox();
            buyJButton = new javax.swing.JButton();
            jLabel2 = new javax.swing.JLabel();
            jLabel3 = new javax.swing.JLabel();
            jLabel4 = new javax.swing.JLabel();
            quantityJTextField = new javax.swing.JTextField();
            priceJTextField = new javax.swing.JTextField();
            totalJTextField = new javax.swing.JTextField();
            clearJButton = new javax.swing.JButton();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
            jLabel1.setText("Item Bought");
     
            itemsBoughtJTextArea.setEditable(false);
            itemsBoughtJTextArea.setColumns(20);
            itemsBoughtJTextArea.setRows(5);
            jScrollPane1.setViewportView(itemsBoughtJTextArea);
     
            itemsJComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }));
            itemsJComboBox.addItemListener(new java.awt.event.ItemListener() {
                public void itemStateChanged(java.awt.event.ItemEvent evt) {
                    itemsJComboBoxItemStateChanged(evt);
                }
            });
     
            buyJButton.setText("Buy");
            buyJButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    buyJButtonActionPerformed(evt);
                }
            });
     
            jLabel2.setText("Quantity");
     
            jLabel3.setText("Price");
     
            jLabel4.setText("Total");
     
            quantityJTextField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
            quantityJTextField.setText("0");
     
            priceJTextField.setEditable(false);
            priceJTextField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
     
            totalJTextField.setEditable(false);
            totalJTextField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
     
            clearJButton.setText("Clear");
            clearJButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    clearJButtonActionPerformed(evt);
                }
            });
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createSequentialGroup()
                            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(18, 18, 18)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(itemsJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(priceJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(buyJButton, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(clearJButton, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))))
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(272, 272, 272)
                                    .addComponent(jLabel4))))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGap(23, 23, 23)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(332, 332, 332)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(14, 14, 14)
                                    .addComponent(jLabel2)
                                    .addGap(102, 102, 102)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel3)
                                        .addComponent(totalJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addComponent(quantityJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addContainerGap(229, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(35, 35, 35)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(33, 33, 33)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel2)
                                .addComponent(jLabel3))))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(itemsJComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(quantityJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(priceJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGap(150, 150, 150)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel4)
                                .addComponent(totalJTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(buyJButton)
                        .addComponent(clearJButton))
                    .addGap(102, 102, 102))
            );
     
            pack();
        }// </editor-fold>                        
     
        private void buyJButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
            // TODO add your handling code here:
        }                                          
     
        private void clearJButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
            // TODO add your handling code here:
        }                                            
     
        private void itemsJComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {                                                
     
            int itemindex = itemsJComboBox.getSelectedIndex();
     
            priceJTextField.setText(String.valueOf(prices[itemindex]));
     
     
        }                                               
     
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(ShoppingCart.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(ShoppingCart.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(ShoppingCart.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(ShoppingCart.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
     
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ShoppingCart().setVisible(true);
                }
            });
        }
     
        private double prices[] = {1.25, 1.75, 2.93,5.45,2.09};
        // Variables declaration - do not modify                     
        private javax.swing.JButton buyJButton;
        private javax.swing.JButton clearJButton;
        private javax.swing.JTextArea itemsBoughtJTextArea;
        private javax.swing.JComboBox itemsJComboBox;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JLabel jLabel4;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextField priceJTextField;
        private javax.swing.JTextField quantityJTextField;
        private javax.swing.JTextField totalJTextField;
        // End of variables declaration                   
    }


  2. #2
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Arrays, JButton, and Action Listener

    Maybe use a class to represent purchased items. It would contain information about the item (description, ID, price) as well as quantity ordered. Then add those objects to a Collection in the ShoppingCart.
    Improving the world one idiot at a time!

  3. #3
    Junior Member
    Join Date
    Sep 2013
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Arrays, JButton, and Action Listener

    Ok....I've looked at it some more and I'm still not getting it.

    What I need to do is have the buyJButton get the name of the item, price selected in the drop down menu (JComboBox) and multiply the quantity times the price of the item and write that to the totalJTextField as well as to the JTextArea. I've tried several things and I can't get it to work.

    private void buyJButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
     
            int itemindex = itemsJComboBox.getSelectedIndex();
     
            int total = itemsJComboBox.getSelectedIndex * quantity;

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Arrays, JButton, and Action Listener

    getSelectedIndex() returns the index of the selected item. In other words, the 5th item in the JComboBox might be 20.00. getSelectedIndex() returns '4' (the 5th item), not 20.00. Review the JComboBox methods to determine which method will return what you're after. Note the TYPE of the item returned so that you apply any necessary casting or parsing before trying to use it.

  5. #5
    Junior Member
    Join Date
    Sep 2013
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Arrays, JButton, and Action Listener

    THank you. I've got it mostly figured out. The only problem I'm still having is writing to my itemsBoughtJTextArea. I want to write to it what has been bought. Also, I'm not sure where to start on coding my clearJButton to reset everything.

    private void buyJButtonActionPerformed(java.awt.event.ActionEvent evt) {                                           
     
            int itemindex = itemsJComboBox.getSelectedIndex();
     
            int quantity = Integer.parseInt(quantityJTextField.getText());
     
          totalJTextField.setText(String.valueOf(prices[itemindex] * quantity)); 
     
          itemsBoughtJTextArea.setText(itemsJComboBox());

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Arrays, JButton, and Action Listener

    Different components have different ways to clear them. If the component has a setText() method, you can clear by calling theComponent.setText( "" ); // empty quotes. If you've provided a blank item in your JComboBox list of items (usually at index 0), you can set the JComboBox to show index 0, or whatever index shows the blank item. Check the API for each component's methods to determine the appropriate method to do what you want.

  7. #7
    Junior Member
    Join Date
    Sep 2013
    Posts
    12
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Arrays, JButton, and Action Listener

    Thanks, I got that working. Any thoughts on printing to the jTextArea the item name and purchase price?

    I've tried this but it does not work:

    itemsBoughtJTextArea.append("\n"+JComboBox.getSelectedIndex());

    It prints 1. I'm guessing that's the item 1 in the index.

  8. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Arrays, JButton, and Action Listener

    Yes, you're collecting and printing the selected index. You want the item at the index, not the index itself.

Similar Threads

  1. JMenuItem action Listener
    By WackoMako in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 11th, 2012, 12:59 PM
  2. Action Listener
    By Suzanne in forum What's Wrong With My Code?
    Replies: 7
    Last Post: May 29th, 2010, 10:50 AM
  3. Beginner Help (Action Listener)
    By gradstudent in forum AWT / Java Swing
    Replies: 2
    Last Post: April 30th, 2010, 10:26 AM
  4. Action Listener
    By kray66 in forum AWT / Java Swing
    Replies: 2
    Last Post: April 19th, 2010, 03:26 PM
  5. Need Help Action Listener....
    By vhizent23 in forum AWT / Java Swing
    Replies: 2
    Last Post: October 9th, 2009, 01:46 PM