如何使用按钮作为双数据类型将JTextField输入存储为变量



尝试创建一个名为CashInsert的变量作为double,然后我创建了CashAmounttxt = CashInsert,但失败了,还有我如何添加动作侦听器,以便在单击按钮时将插入的量存储在变量内部的框中?

这是我的代码:

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class CashPay extends javax.swing.JFrame {
    private JLabel cashamountlbl;
    private JButton Calculatebtn;
    private JLabel CashChangelbl;
    private JTextField CashAmounttxt;
    private double ChangeLeft;
    private double CashInsert;

    /**
    * Auto-generated main method to display this JFrame
    */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                CashPay inst = new CashPay();
                inst.setLocationRelativeTo(null);
                inst.setVisible(true);
            }
        });
    }
    public CashPay() {
        super();
         CashAmounttxt = CashInsert;
        initGUI();
    }
    private void initGUI() {
        try {
            setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            getContentPane().setLayout(null);
            cashamountlbl = new JLabel();
            getContentPane().add(cashamountlbl);
            cashamountlbl.setText("Enter Cash Amount");
            cashamountlbl.setBounds(41, 65, 105, 34);
            cashamountlbl.setBackground(new java.awt.Color(128,0,255));
            CashAmounttxt = new JTextField();
            getContentPane().add(CashAmounttxt);
            CashAmounttxt.setBounds(215, 71, 87, 23);
            CashChangelbl = new JLabel();
            getContentPane().add(CashChangelbl);
            CashChangelbl.setBounds(190, 117, 158, 109);
            CashChangelbl.setBackground(new java.awt.Color(255,128,64));
            Calculatebtn = new JButton();
            getContentPane().add(Calculatebtn);
            Calculatebtn.setText("Calculate Total");
            Calculatebtn.setBounds(46, 203, 93, 23);
            pack();
            setSize(400, 300);
        } catch (Exception e) {
            //add your error handling code here
            e.printStackTrace();
        }
    }
}

使用Double.toString()将Double值转换为字符串,并使用JTextField.setText()将其显示在UI中。对于相反的转换,请使用JTextField.getText()和Double.parseDouble().

最新更新