简体   繁体   中英

While loop GUI button won't work on second press

I am making a cash register program. When I click the Checkout button the input dialogue box will come up, take input, and then close/stop the while loop when you enter nothing and ok or press cancel. After this it will show the data. When I click Checkout a second time the input dialogue box will not appear for you to enter more and I have to rerun the project in java to use it a second time. How can I change this to where after it ends and displays the data, pressing the checkout button again will do the same thing again as pressing it the first time?

import java.text.NumberFormat;
import javax.swing.JOptionPane;

public class CashRegisterGUI extends javax.swing.JFrame {
NumberFormat nF = NumberFormat.getCurrencyInstance();

private double purchase;                
private int numItems;                   


boolean keepShopping = true;            

/**
 * Creates new form CashRegisterGUI
 */
public CashRegisterGUI() {
    initComponents();
    purchase=0;
    numItems=0;
}

// set method to add item price
public void recordPurchase ( double itemPrice )
{ purchase = purchase + itemPrice ;
 numItems++;}

// get method to get purchase total
public double getPurchase () { return purchase ; }

// get method to get number of items
public int getItems () { return numItems; }



/**
 * 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();
    txtPrice = new javax.swing.JTextField();
    jLabel2 = new javax.swing.JLabel();
    txtSub = new javax.swing.JTextField();
    jLabel3 = new javax.swing.JLabel();
    txtItems = new javax.swing.JTextField();
    jLabel4 = new javax.swing.JLabel();
    txtTax = new javax.swing.JTextField();
    jLabel5 = new javax.swing.JLabel();
    txtTotal = new javax.swing.JTextField();
    bttnCheckout = new javax.swing.JButton();
    bttnReset = new javax.swing.JButton();
    bttnExit = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Dylans Grocery Calculator");

    jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    jLabel1.setText("Item Price");

    jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    jLabel2.setText("Sub Total");

    jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    jLabel3.setText("Number of Items");

    jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
    jLabel4.setText("Sales Tax");

    jLabel5.setText("Total Sale");

    bttnCheckout.setText("Checkout");
    bttnCheckout.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bttnCheckoutActionPerformed(evt);
        }
    });

    bttnReset.setText("Reset");
    bttnReset.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bttnResetActionPerformed(evt);
        }
    });

    bttnExit.setText("Exit");
    bttnExit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bttnExitActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(13, 13, 13)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2)
                        .addComponent(jLabel3)
                        .addComponent(jLabel4)
                        .addComponent(jLabel5))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(txtTotal, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
                        .addComponent(txtTax)
                        .addComponent(txtItems)
                        .addComponent(txtSub)
                        .addComponent(txtPrice)))
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 12, Short.MAX_VALUE)
                    .addComponent(bttnCheckout, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(bttnReset, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(bttnExit, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(txtPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(31, 31, 31)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel2)
                .addComponent(txtSub, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(29, 29, 29)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel3)
                .addComponent(txtItems, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(28, 28, 28)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel4)
                .addComponent(txtTax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(31, 31, 31)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel5)
                .addComponent(txtTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 51, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(bttnCheckout)
                .addComponent(bttnReset)
                .addComponent(bttnExit))
            .addContainerGap())
    );

    pack();
}// </editor-fold>                        

private void bttnExitActionPerformed(java.awt.event.ActionEvent evt) {                                         
    //exit system upon exit bttnexit press by user
    System.exit(0);
}                                        

private void bttnResetActionPerformed(java.awt.event.ActionEvent evt) {                                          
    //set text fields back to empty
    txtPrice.setText("");
    txtSub.setText("");
    txtTax.setText("");
    txtTotal.setText("");
    txtItems.setText("");
}                                         

private void bttnCheckoutActionPerformed(java.awt.event.ActionEvent evt) {                                             
//checkout button 
double itemPrice;  
double subTotal;                                         
double salesTax;                         
double totalSale;     

//Intialiaze subTotal
subTotal = 0;

while (keepShopping){                                       //loop if true
    try{
     String newItemPrice = JOptionPane.showInputDialog(this,
     "Enter item price:", "Enter price",
      JOptionPane.PLAIN_MESSAGE);



     if ((newItemPrice !=null) && (newItemPrice.length() >0)) //check input
        { 
        itemPrice = Double.parseDouble(newItemPrice);         
        subTotal = itemPrice + subTotal;                      //get subtotal
        txtPrice.setText(nF.format(itemPrice));               //show item price
        txtSub.setText(nF.format(subTotal));                  //show subtotal
        numItems ++;                                          //count items
        txtItems.setText(Integer.toString(numItems));         //show items

        }

    else
        { 
        keepShopping = false;                                 //end loop
        salesTax = .065 * subTotal;                           //get salestax  
        txtTax.setText(nF.format(salesTax));                  //show salestax
        totalSale = subTotal + salesTax;                      //get total
        txtTotal.setText(nF.format(totalSale));               //show total
        } 

        }
    catch(NumberFormatException e)                    // catches bad data        
       {
        JOptionPane.showMessageDialog(this,
        "Your input must be numeric!",
        "Bad data!", JOptionPane.ERROR_MESSAGE);
       }
       }

}                                            

/**
 * @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(CashRegisterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(CashRegisterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(CashRegisterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(CashRegisterGUI.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() {
            CashRegisterGUI frame = new CashRegisterGUI();
            frame.setVisible(true);
            frame.setLocationRelativeTo(null);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton bttnCheckout;
private javax.swing.JButton bttnExit;
private javax.swing.JButton bttnReset;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JTextField txtItems;
private javax.swing.JTextField txtPrice;
private javax.swing.JTextField txtSub;
private javax.swing.JTextField txtTax;
private javax.swing.JTextField txtTotal;
// End of variables declaration                   
}

I also have a reset button that only has .setText(""); to clear the textfields. If this would be a simpler spot to achieve this.

Thank you for your time!

In your bttnResetActionPerformed event handler, set keepShoppng back to true.

Otherwise, when your bttnCheckoutActionPerformed method is called, the loop while (keepShopping){ ... will never be entered again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM