虽然循环 GUI 按钮在第二次按下时不起作用



我正在制作一个收银机程序。当我单击"结账"按钮时,输入对话框将出现,接受输入,然后在您未输入任何内容并确定或按取消时关闭/停止while循环。之后,它将显示数据。当我第二次单击Checkout时,输入对话框将不会出现,您可以输入更多信息,我必须用java重新运行该项目才能第二次使用它。我如何将其更改为在它结束并显示数据后,再次按下结账按钮将再次执行与第一次按下相同的操作?

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                   
}

我还有一个重置按钮,它只有.setText(");以清除文本字段。如果这将是一个更简单的点来实现这一点。

感谢您抽出时间!

bttnResetActionPerformed事件处理程序中,将keepShoppng设置回true。

否则,当调用bttnCheckoutActionPerformed方法时,循环while (keepShopping){ ...将不再被输入。

最新更新