【问题标题】:While loop GUI button won't work on second press虽然循环 GUI 按钮在第二次按下时不起作用
【发布时间】:2015-11-17 09:15:15
【问题描述】:

我正在制作一个收银机程序。当我单击 Checkout 按钮时,将出现输入对话框,接受输入,然后在您没有输入任何内容并确定或按取消时关闭/停止 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(""); 的重置按钮。清除文本字段。如果这将是一个更简单的地方来实现这一点。

感谢您的宝贵时间!

【问题讨论】:

  • 我看到您将keepShopping 分配给false............但是您是否再次将其分配回true?我不相信,所以在你的while(keepShopping) 块末尾添加keepShopping = true

标签: java user-interface while-loop


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-01-23
    • 2021-03-16
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多