0

We're trying to design a set of Textfields where users can enter a value depending on how much quantity of the product they want. We have one button called checkout.

Basically, 2 classes, One called FoodDept (where all the textfields are and the checkout Button), and one called Checkout where there is a textfield or Area where i can output the choices or numbers the user indicated. That is basicallly all I need.

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                   
}
dic19
  • 17,821
  • 6
  • 40
  • 69
Shinji
  • 1,799
  • 2
  • 11
  • 13

1 Answers1

0

Before start, some off-topic advices:

  • Please read about Java Code Conventions and stick to them because they make your code more readable.
  • Try to make your GUI classes without using GUI builders and spend some time learning about Swing and writing your classes by your own hand. You'll learn lot of things that builder "hides" you and your code will be simpler and cleaner.
  • Every Swing application should have only one JFrame. Take a look to this topic: The Use of Multiple JFrames, Good/Bad Practice?
  • I suspect because of backBtn presence that you're trying to do a kind of wizard. If this is the case I'd suggest you take a look to CardLayout. There are plenty of examples in SO too.

Well the two classes needed are there, you just have to find out the way to communicate them. One approach would be passing a List<String> to the Checkout class so when the JTextArea is initialized it can take this list as data:

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));
    }
}

The List must be set before the dialog becomes visible, just like this:

Checkout checkout = new Checkout(this, true);
checkout.setDataToBeDisplayed(data); // data must be created and populated before this call
checkout.setVisible(true);
Community
  • 1
  • 1
dic19
  • 17,821
  • 6
  • 40
  • 69
  • Is there a way to utilize the CardLayout method easier by using the netbeans GUI builder? – Shinji Nov 29 '13 at 09:49
  • I would say you can make all your cards, `JPanel`s, using GUI builder. Then you can design the main dialog and place a `JPanel` and set `CardLayout` as its layout manager. Keeping this in mind and looking the tutorial you can make it :) @Shinji – dic19 Nov 29 '13 at 10:38