如何锁定JTextFeild以仅接受数字值和小数

时间:2018-10-01 17:14:48

标签: java

好的,所以我制作了一个基本的银行程序,并试图找出如何将用户输入锁定为仅数字和小数位,然后将这些数字用作存款和取款(按钮尚未设置)是否可能将textFeild锁定为数字,还是我必须使用其他输入源?

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Interface {

    public static void main (String[]args){     

        JFrame f=new JFrame("User Bank (Version 0.03.5)");

        double ammount = 0;
        double Depo = 0;
        double Withd= 0;
        double Interest= 4; 

        JLabel actions;
        actions=new JLabel("Last transactions");
        actions.setBounds(950,325,600,200);
        f.add(actions);

        JLabel Interst;
        Interst=new JLabel("NOTE THAT ALL TRANSACTIONS HAVE A 4% FEE");
        Interst.setBounds(950,250,600,200);
        f.add(Interst);

        JLabel LastDepo;
        LastDepo=new JLabel("Your last Deposite was "+Depo+" with the 4% transactions rate made it "+(((Depo/100)*4)+Depo));
        LastDepo.setBounds(950,400,600,200);
        f.add(LastDepo);

        JLabel LastWith;
        LastWith=new JLabel("Your last Withdrawel was "+Withd+" with the 4% transactions rate made it "+(((-Withd/100)*Interest)+Withd));
        LastWith.setBounds(950,500,600,200);
        f.add(LastWith);

        JLabel AmmountL;
        AmmountL=new JLabel("ammount");
        AmmountL.setBounds(340,300,300,100);
        f.add(AmmountL);

        JTextField depot=new JTextField();
        depot.setBounds(400,450,95,15);
        f.add(depot);

        JButton depo=new JButton("Deposite");
        depo.setBounds(400,500,95,30);
        f.add(depo);

        JTextField WithdT=new JTextField();
        WithdT.setBounds(400,550,95,15);
        f.add(WithdT);  

        JButton withd=new JButton("WithDraw");
        withd.setBounds(400,600,95,30);
        f.add(withd);

        JLabel Ammount;
        Ammount=new JLabel("$"+(ammount+Depo-Withd));
        Ammount.setBounds(400,300,300,100);
        f.add(Ammount);

        f.setSize(1920,1080);
        f.setLayout(null);
        f.setVisible(true);
        f.setResizable(false);

    }

}

1 个答案:

答案 0 :(得分:0)

MaskFormatter()JFormattedTextField()一起使用,其中#是小数点前后的整数值。

MaskFormatter yourformatter = new MaskFormatter("####.###");
JFormattedTextField yourtextfield = new JFormattedTextField();