如何从10个文本字段中获取值并使用一个按钮将选项输出到文本字段或区域? (带代码)

时间:2013-11-28 14:34:46

标签: java swing jbutton jtextfield

我们正在尝试设计一组文本字段,用户可以根据他们想要的产品数量输入值。我们有一个名为checkout的按钮。

基本上,有两个类,一个名为FoodDept(所有文本区域和结帐按钮),一个名为Checkout,其中有文本字段或区域,我可以输出用户指示的选项或数字。这基本上是我所需要的。

package shopping;
import java.util.*;

public class foodDept extends javax.swing.JFrame {

    /**
     * Creates new form foodDept
     */
    int apple;
    int banana;
    double a = 0;
    double b = 0;


    public foodDept() {
        initComponents();
        apple=0;
        banana=0;
    }

    /**
     * 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() {

        appleLabel = new javax.swing.JLabel();
        appleField = new javax.swing.JTextField();
        backBtn = new javax.swing.JButton();
        bananaLabel = new javax.swing.JLabel();
        bananaField = new javax.swing.JTextField();
        checkoutBtn = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        appleLabel.setText("Apple ($1.99):");

        appleField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                appleFieldActionPerformed(evt);
            }
        });

        backBtn.setText("Back");
        backBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backBtnActionPerformed(evt);
            }
        });

        bananaLabel.setText("Banana ($0.99):");

        checkoutBtn.setText("jButton1");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(backBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 152, Short.MAX_VALUE)
                        .addComponent(checkoutBtn))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(appleLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(appleField))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(bananaLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(bananaField, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(appleLabel)
                    .addComponent(appleField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bananaLabel)
                    .addComponent(bananaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 59, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(backBtn)
                    .addComponent(checkoutBtn))
                .addContainerGap())
        );

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

    private void backBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
        new dept().setVisible(true);
        dispose();
    }                                       

    void setApple(int a){
        apple=a;
    }
    int getApple(){
    return apple;
    }

    public double getTotal(){
    return a+b;

    }
    private void appleFieldActionPerformed(java.awt.event.ActionEvent evt) {                                           

    }                                          

    public void checkoutBtnActionPerformed(java.awt.event.ActionEvent evt) {                                            

        try{
            double priceOfapple = 1.99;
            int quantity = Integer.parseInt(appleField.getText());
            double totalamount = priceOfapple*quantity;
            checkout.resultField.setText(totalamount);
        }


        b = Double.parseDouble(bananaField.getText());

        foodList fL = new foodList(apple,banana);

        if(a > 0){
            a=a*1.99;
        }

        if(b > 0){
            b=b*0.99;
        } 


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

        //ArrayList<Double> orderList = new ArrayList<Double>();//ARRAYYYYY

        //here

        //for(int x = 0; x<= orderList.size();x++){

        //}   

        foodDept a = new foodDept();

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new foodDept().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    public javax.swing.JTextField appleField;
    private javax.swing.JLabel appleLabel;
    private javax.swing.JButton backBtn;
    private javax.swing.JTextField bananaField;
    private javax.swing.JLabel bananaLabel;
    public javax.swing.JButton checkoutBtn;
    // End of variables declaration                   
}

**********************************************************************************

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package shopping;
import java.util.ArrayList;
import shopping.foodDept;
import shopping.foodDept;
import shopping.foodDept;
/**
 *
 * @author Kevin
 */
public class checkout extends javax.swing.JFrame {

    /**
     * Creates new form checkout
     */
    public checkout() {
        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() {

        backBtn = new javax.swing.JButton();
        purchaseBtn = new javax.swing.JButton();
        resultField = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        backBtn.setText("Back");
        backBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backBtnActionPerformed(evt);
            }
        });

        purchaseBtn.setText("Purchase");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(resultField)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(backBtn)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 148, Short.MAX_VALUE)
                        .addComponent(purchaseBtn)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(resultField, javax.swing.GroupLayout.DEFAULT_SIZE, 89, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(purchaseBtn)
                    .addComponent(backBtn))
                .addContainerGap())
        );

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

    private void backBtnActionPerformed(java.awt.event.ActionEvent evt) {                                        
        new foodDept().setVisible(true);
        dispose();
    }                                       



    /**
     * @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(checkout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(checkout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(checkout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(checkout.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>



        //for(int x = 0; x<= orderList.size();x++){
            //resultField.setText(orderList.get(x));
            //}

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new checkout().setVisible(true);
            }




        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton backBtn;
    private javax.swing.JButton purchaseBtn;
    public javax.swing.JTextField resultField;
    // End of variables declaration                   
}

1 个答案:

答案 0 :(得分:0)

在开始之前,一些偏离主题的建议:

  • 请阅读Java Code Conventions 并坚持使用它们,因为它们使您的代码更具可读性。
  • 尝试在不使用GUI构建器的情况下制作GUI类,并花一些时间学习Swing并自己编写课程。您将学习构建器“隐藏”您的许多内容,并且您的代码将更简单,更清晰。
  • 每个Swing应用 只有一个JFrame。请看一下这个主题:The Use of Multiple JFrames, Good/Bad Practice?
  • 怀疑因为backBtn存在,你正在尝试做一种向导。如果是这种情况,我建议您查看CardLayout。 SO中也有很多例子。

那么所需的两个课程就在那里,你只需要找到沟通方式。一种方法是将List<String>传递给Checkout类,以便在初始化JTextArea时将其作为数据:

public class Checkout extends JDialog {

    List<String> dataToBeDisplayed;

    ...

    public void setDataToBeDisplayed(List<String> data) {
        this.dataToBeDisplayed = data;
    }

    private void initComponents() {
        JTextArea textArea = new JTextArea(20,30);
        for(String line : dataToBeDisplayed) {
            textArea.append(line + System.lineSeparator());
        }
        getContentPane().add(new JScrollPane(textArea));
    }
}

在对话框变为可见之前必须设置List,如下所示:

Checkout checkout = new Checkout(this, true);
checkout.setDataToBeDisplayed(data); // data must be created and populated before this call
checkout.setVisible(true);