繁体   English   中英

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

[英]While loop GUI button won't work on second press

我正在做一个收银机程序。 当我单击“签出”按钮时,将出现输入对话框,进行输入,然后在不输入任何内容并单击确定或按“取消”时关闭/停止while循环。 之后,它将显示数据。 当我第二次单击“签出”时,将不会出现输入对话框,您无法输入更多内容,因此我必须在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){ ...的循环将永远不会再次输入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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