【问题标题】:How to take values from 10 textFields and using one button to output the choices into a textField or Area? (With code)如何从 10 个文本字段中获取值并使用一个按钮将选项输出到文本字段或区域? (带代码)
【发布时间】:2013-11-28 14:34:45
【问题描述】:

我们正在尝试设计一组文本字段,用户可以在其中输入一个值,具体取决于他们想要的产品数量。我们有一个称为结帐的按钮。

基本上,有 2 个类,一个称为 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                   
}

【问题讨论】:

    标签: java swing jbutton jtextfield


    【解决方案1】:

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

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

    所需的两个类都在那里,你只需要找出沟通它们的方法。一种方法是将List&lt;String&gt; 传递给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);
    

    【讨论】:

    • 有没有办法通过使用 netbeans GUI builder 来更轻松地利用 CardLayout 方法?
    • 我想说你可以使用 GUI builder 制作你所有的卡片,JPanels。然后您可以设计主对话框并放置JPanel 并将CardLayout 设置为其布局管理器。牢记这一点并查看教程,您可以做到:) @Shinji
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-24
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    相关资源
    最近更新 更多