简体   繁体   English

JTextField返回用户输入为零

[英]JTextField returns user input as zero

double myintc;
        double myint1;
         double calW;

final JTextField WeightField = new JTextField();
        WeightField.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //String s = WeightField.getText();
             myintc = Double.parseDouble(WeightField.getText());

calW = myintc*1.5;
        calA =myint1*2.2;

final JButton button = new JButton("Continue");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            // Proceeding to Payment Interface when we Click Continue Buttom    
                ChickenPay window = new ChickenPay();
                window.frmChickenPurchase.setVisible(true);
                frmChicjenPurchase.setVisible(false);
                JOptionPane.showMessageDialog(button, "Abbattoir is equal to  "+ calW);

After user input of number. 用户输入号码后。 to Get calW it always output 0 also myintc says null 为了得到它总是输出0,myintc也说null

 myintc = Double.parseDouble(WeightField.getText());

I tried calW= Double.parseDouble(WeightField.getText()) *1.5; 我尝试了calW= Double.parseDouble(WeightField.getText()) *1.5;

I still get error. 我仍然会出错。 Please help 请帮忙

http://i.stack.imgur.com/14ul2.png http://i.stack.imgur.com/14ul2.png

This is the whole code 这是整个代码

package pos;

import java.awt.EventQueue;
import pos.ChickenPay;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import java.awt.BorderLayout;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.BoxLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.Window;
import java.awt.Choice;
import javax.swing.JFormattedTextField;
import javax.swing.JCheckBox;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.awt.TextField;

public class ChickenSales {


    JFrame frmChicjenPurchase;
    private JTextField textField;
    public static int ws;
    public static int ab;
    public double myintc;
    double myint1;
    public static double calW;
    public static double calA;
    int tPrice;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ChickenSales window = new ChickenSales();
                    window.frmChicjenPurchase.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public ChickenSales() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frmChicjenPurchase = new JFrame();
        frmChicjenPurchase.setTitle("Chicken Purchase");
        frmChicjenPurchase.setSize(400, 300);
        frmChicjenPurchase.setLocationRelativeTo(null);
        frmChicjenPurchase.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        GridBagLayout gridBagLayout = new GridBagLayout();
        gridBagLayout.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0};
        gridBagLayout.rowHeights = new int[]{55, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        gridBagLayout.columnWeights = new double[]{1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
        gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
        frmChicjenPurchase.getContentPane().setLayout(gridBagLayout);

        JLabel lblChickenInformation = new JLabel("Chicken Information");
        lblChickenInformation.setFont(new Font("Calisto MT", Font.BOLD, 16));
        lblChickenInformation.setForeground(new Color(0, 0, 0));
        GridBagConstraints gbc_lblChickenInformation = new GridBagConstraints();
        gbc_lblChickenInformation.gridwidth = 4;
        gbc_lblChickenInformation.insets = new Insets(0, 0, 5, 5);
        gbc_lblChickenInformation.gridx = 3;
        gbc_lblChickenInformation.gridy = 0;
        frmChicjenPurchase.getContentPane().add(lblChickenInformation, gbc_lblChickenInformation);

        JLabel lblWeight = new JLabel("Weight (kg)");
        GridBagConstraints gbc_lblWeight = new GridBagConstraints();
        gbc_lblWeight.gridwidth = 3;
        gbc_lblWeight.insets = new Insets(0, 0, 5, 5);
        gbc_lblWeight.gridx = 2;
        gbc_lblWeight.gridy = 1;
        frmChicjenPurchase.getContentPane().add(lblWeight, gbc_lblWeight);

        final JTextField WeightField = new JTextField();
        WeightField.addActionListener(new ActionListener( ) {
            public void actionPerformed(ActionEvent e) {
                //String s = WeightField.getText();
            // myintc = Double.parseDouble(WeightField.getText());

            }
        });
        WeightField.setColumns(5);
        WeightField.setToolTipText("Enter Weight betwwen 2-8 kg");
        GridBagConstraints gbc_WeightField = new GridBagConstraints();
        gbc_WeightField.anchor = GridBagConstraints.WEST;
        gbc_WeightField.insets = new Insets(0, 0, 5, 0);
        gbc_WeightField.gridx = 7;
        gbc_WeightField.gridy = 1;
        frmChicjenPurchase.getContentPane().add(WeightField, gbc_WeightField);

        JLabel lblAge = new JLabel("Age");
        GridBagConstraints gbc_lblAge = new GridBagConstraints();
        gbc_lblAge.insets = new Insets(0, 0, 5, 5);
        gbc_lblAge.gridx = 3;
        gbc_lblAge.gridy = 3;
        frmChicjenPurchase.getContentPane().add(lblAge, gbc_lblAge);

        final JFormattedTextField AgeField = new JFormattedTextField();
        AgeField.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //String B = AgeField.getText();
                try{

                    myint1 = Double.parseDouble(AgeField.getText());
                            if(myint1>=6 && myint1 <=24){

                            }
                                        }
                catch (Exception e1){
                    System.out.println("Weight ranges between 2-8kg");

                }
                            }
            //END AGE HERE
        });
        AgeField.setToolTipText("Enter Age betwwen 6-24 months");
        AgeField.setColumns(5);
        GridBagConstraints gbc_AgeField = new GridBagConstraints();
        gbc_AgeField.anchor = GridBagConstraints.WEST;
        gbc_AgeField.insets = new Insets(0, 0, 5, 0);
        gbc_AgeField.gridx = 7;
        gbc_AgeField.gridy = 3;
        frmChicjenPurchase.getContentPane().add(AgeField, gbc_AgeField);

        JLabel lblBreed = new JLabel("Breed");
        GridBagConstraints gbc_lblBreed = new GridBagConstraints();
        gbc_lblBreed.insets = new Insets(0, 0, 5, 5);
        gbc_lblBreed.gridx = 3;
        gbc_lblBreed.gridy = 5;
        frmChicjenPurchase.getContentPane().add(lblBreed, gbc_lblBreed);

        // ACTION LISTENER 4 BREED
        final Choice BreedChoice = new Choice();
        BreedChoice.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {

                String wa = BreedChoice.getSelectedItem();
                switch (wa){
                case "W":
                 ws =100;
                    break;
                case "X":
                     ws =150;
                        break;
                case "Y":
                     ws =200;
                        break;
                case "Z":
                     ws =350;
                        break;
                    default:


                }



            }
        });

        BreedChoice.add("--");
        BreedChoice.add("W");
        BreedChoice.add("X");
        BreedChoice.add("Y");
        BreedChoice.add("Z");




        GridBagConstraints gbc_BreedChoice = new GridBagConstraints();
        gbc_BreedChoice.insets = new Insets(0, 0, 5, 0);
        gbc_BreedChoice.anchor = GridBagConstraints.WEST;
        gbc_BreedChoice.gridx = 7;
        gbc_BreedChoice.gridy = 5;
        frmChicjenPurchase.getContentPane().add(BreedChoice, gbc_BreedChoice);

        JLabel lblAbattoir = new JLabel("Abattoir Service");
        GridBagConstraints gbc_lblAbattoir = new GridBagConstraints();
        gbc_lblAbattoir.insets = new Insets(0, 0, 5, 5);
        gbc_lblAbattoir.gridx = 3;
        gbc_lblAbattoir.gridy = 7;
        frmChicjenPurchase.getContentPane().add(lblAbattoir, gbc_lblAbattoir);

        final JCheckBox abbattoirCheckBox = new JCheckBox("");
        abbattoirCheckBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            boolean selected = abbattoirCheckBox.getModel().isSelected();
            if (selected){
                ab =50;
            }
            }
        });

        //LOGIC STARTS HERE
        calW = myintc*1.5;
        calA =myint1*2.2;



        //---------------


        abbattoirCheckBox.setToolTipText("Costs N50");
        GridBagConstraints gbc_abbattoirCheckBox = new GridBagConstraints();
        gbc_abbattoirCheckBox.insets = new Insets(0, 0, 5, 0);
        gbc_abbattoirCheckBox.anchor = GridBagConstraints.WEST;
        gbc_abbattoirCheckBox.gridx = 7;
        gbc_abbattoirCheckBox.gridy = 7;
        frmChicjenPurchase.getContentPane().add(abbattoirCheckBox, gbc_abbattoirCheckBox);

        final JButton button = new JButton("Continue");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            // Proceeding to Payment Interface when we Click Continue Buttom    
                ChickenPay window = new ChickenPay();
                window.frmChickenPurchase.setVisible(true);
                frmChicjenPurchase.setVisible(false);
                JOptionPane.showMessageDialog(button, "Abbattoir is equal to  "+ calW);
            }
        });
        GridBagConstraints gbc_button = new GridBagConstraints();
        gbc_button.anchor = GridBagConstraints.ABOVE_BASELINE;
        gbc_button.insets = new Insets(0, 0, 5, 5);
        gbc_button.gridx = 5;
        gbc_button.gridy = 8;
        frmChicjenPurchase.getContentPane().add(button, gbc_button);



        JPanel marginPanel = new JPanel();
        marginPanel.setBounds(5, 5, 5, 5);
        GridBagConstraints gbc_marginPanel = new GridBagConstraints();
        gbc_marginPanel.insets = new Insets(0, 0, 0, 5);
        gbc_marginPanel.fill = GridBagConstraints.BOTH;
        gbc_marginPanel.gridx = 0;
        gbc_marginPanel.gridy = 9;
        frmChicjenPurchase.getContentPane().add(marginPanel, gbc_marginPanel);






    }

}

A JTextField 's action listener is only called when Enter is pressed while the focus is in the JTextField . 仅当焦点位于JTextField时,按下Enter才能调用JTextField的动作侦听器。 If the user types a number in the field, and then tabs away, or clicks a button, then the action listener will not be called, so your variable myintc will remain uninitialized. 如果用户在该字段中键入数字,然后移开选项卡或单击按钮,则将不会调用操作侦听器,因此变量myintc将保持未初始化状态。

The parsing of the JTextField should be moved into the button's action listener, to ensure it is performed when the Continue button is pressed. 应该将JTextField的解析移到该按钮的动作侦听器中,以确保在按下Continue按钮时执行该解析。

eg) 例如)

final JTextField WeightField = new JTextField();
// (no action listener required here)

final JButton button = new JButton("Continue");
button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        myintc = Double.parseDouble(WeightField.getText());
        calW = myintc*1.5;
        // Remainder of "Proceeding to Payment" code
    }
});

After user input of number. 用户输入号码后。 to Get calW it always output 0 also myintc says null 为了得到它总是输出0,myintc也说null

calW is always zero, because in your entire codes, you did not change its value at all. calW始终为零,因为在您的整个代码中,您根本没有更改其值。

The only place where you assigned a value to it is in the initialize() method. 为它分配值的唯一位置是initialize()方法。 However you assign it as: 但是,您将其分配为:

calW = myintc*1.5;  //myintc is 0!

myintc was not initialized at all, hence a default 0 value will be assigned to it, causing calW to be initialized to 0 as well. myintc根本没有初始化,因此将为其分配默认的0值,从而导致calW也被初始化为0

Since calW was initialized as zero and there is no further update on this variable, you always get 0 for calW . 由于calW被初始化为零,并且此变量没有进一步的更新,因此calW始终为0


Some Suggestions: 一些建议:

  • You are creating too many static variables and your implementation code was thrown in one huge class. 您创建了太多的静态变量,并且您的实现代码被抛出到一个巨大的类中。 You don't need static variables for a program like this. 对于这样的程序,您不需要静态变量。 Instead, you can create customized container class such as a customized JPanel with all the components it needs. 相反,您可以使用其所需的所有组件创建自定义的容器类,例如自定义的JPanel。 This way, your classes are self-contained and it will be much more easier to read and maintain. 这样,您的类是自包含的,它将更易于阅读和维护。

  • Declare your variables into proper scope and access them with getters and setters. 将变量声明为适当的范围,并使用getter和setter访问它们。

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

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