JFormattedTextField使用

 例1:
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4. import javax.swing.event.*;
  5. import javax.swing.text.*;
  6. import java.beans.PropertyChangeListener;
  7. import java.beans.PropertyChangeEvent;
  8. import java.text.*;
  9. /**
  10.  * FormatterFactoryDemo.java requires no other files.
  11.  */
  12. public class FormatterFactoryDemo extends JPanel
  13.                                   implements PropertyChangeListener {
  14.     //Values for the text fields
  15.     private double amount = 100000;
  16.     private double rate = .075;  //7.5 %
  17.     private int numPeriods = 30;
  18.     //Labels to identify the fields
  19.     private JLabel amountLabel;
  20.     private JLabel rateLabel;
  21.     private JLabel numPeriodsLabel;
  22.     private JLabel paymentLabel;
  23.     //Strings for the labels
  24.     private static String amountString = "Loan Amount: ";
  25.     private static String rateString = "APR (%): ";
  26.     private static String numPeriodsString = "Years: ";
  27.     private static String paymentString = "Monthly Payment: ";
  28.     //Fields for data entry
  29.     private JFormattedTextField amountField;
  30.     private JFormattedTextField rateField;
  31.     private JFormattedTextField numPeriodsField;
  32.     private JFormattedTextField paymentField;
  33.     //Formats to format and parse numbers
  34.     private NumberFormat amountDisplayFormat;
  35.     private NumberFormat amountEditFormat;
  36.     private NumberFormat percentDisplayFormat;
  37.     private NumberFormat percentEditFormat;
  38.     private NumberFormat paymentFormat;
  39.     public FormatterFactoryDemo() {
  40.         super(new BorderLayout());
  41.         setUpFormats();
  42.         double payment = computePayment(amount,
  43.                                         rate,
  44.                                         numPeriods);
  45.         //Create the labels.
  46.         amountLabel = new JLabel(amountString);
  47.         rateLabel = new JLabel(rateString);
  48.         numPeriodsLabel = new JLabel(numPeriodsString);
  49.         paymentLabel = new JLabel(paymentString);
  50.         //Create the text fields and set them up.
  51.         amountField = new JFormattedTextField(//格式化文本框
  52.                             new DefaultFormatterFactory(//格式化工厂
  53.                                 new NumberFormatter(amountDisplayFormat),//总数量默认的格式
  54.                                 new NumberFormatter(amountDisplayFormat),//总数量显示时的格式
  55.                                 new NumberFormatter(amountEditFormat)));//总数量编辑时的格式
  56.         amountField.setValue(new Double(amount));
  57.         amountField.setColumns(10);
  58.         amountField.addPropertyChangeListener("value"this);
  59.         NumberFormatter percentEditFormatter =//百分比的编辑格式
  60.                 new NumberFormatter(percentEditFormat) {
  61.             public String valueToString(Object o)
  62.                   throws ParseException {
  63.                 Number number = (Number)o;
  64.                 if (number != null) {
  65.                     double d = number.doubleValue() * 100.0;
  66.                     number = new Double(d);
  67.                 }
  68.                 return super.valueToString(number);
  69.             }
  70.             public Object stringToValue(String s)
  71.                    throws ParseException {
  72.                 Number number = (Number)super.stringToValue(s);
  73.                 if (number != null) {
  74.                     double d = number.doubleValue() / 100.0;
  75.                     number = new Double(d);
  76.                 }
  77.                 return number;
  78.             }
  79.         };
  80.         rateField = new JFormattedTextField(
  81.                              new DefaultFormatterFactory(
  82.                                 new NumberFormatter(percentDisplayFormat),
  83.                                 new NumberFormatter(percentDisplayFormat),
  84.                                 percentEditFormatter));
  85.         rateField.setValue(new Double(rate));
  86.         rateField.setColumns(10);
  87.         rateField.addPropertyChangeListener("value"this);
  88.         numPeriodsField = new JFormattedTextField();
  89.         numPeriodsField.setValue(new Integer(numPeriods));
  90.         numPeriodsField.setColumns(10);
  91.         numPeriodsField.addPropertyChangeListener("value"this);
  92.         paymentField = new JFormattedTextField(paymentFormat);
  93.         paymentField.setValue(new Double(payment));
  94.         paymentField.setColumns(10);
  95.         paymentField.setEditable(false);
  96.         paymentField.setForeground(Color.red);
  97.         //Tell accessibility tools about label/textfield pairs.
  98.         amountLabel.setLabelFor(amountField);
  99.         rateLabel.setLabelFor(rateField);
  100.         numPeriodsLabel.setLabelFor(numPeriodsField);
  101.         paymentLabel.setLabelFor(paymentField);
  102.         //Lay out the labels in a panel.
  103.         JPanel labelPane = new JPanel(new GridLayout(0,1));
  104.         labelPane.add(amountLabel);
  105.         labelPane.add(rateLabel);
  106.         labelPane.add(numPeriodsLabel);
  107.         labelPane.add(paymentLabel);
  108.         //Layout the text fields in a panel.
  109.         JPanel fieldPane = new JPanel(new GridLayout(0,1));
  110.         fieldPane.add(amountField);
  111.         fieldPane.add(rateField);
  112.         fieldPane.add(numPeriodsField);
  113.         fieldPane.add(paymentField);
  114.         //Put the panels in this panel, labels on left,
  115.         //text fields on right.
  116.         setBorder(BorderFactory.createEmptyBorder(20202020));
  117.         add(labelPane, BorderLayout.CENTER);
  118.         add(fieldPane, BorderLayout.LINE_END);
  119.     }
  120.     /** Called when a field's "value" property changes. */
  121.     public void propertyChange(PropertyChangeEvent e) {
  122.         Object source = e.getSource();
  123.         if (source == amountField) {
  124.             amount = ((Number)amountField.getValue()).doubleValue();
  125.         } else if (source == rateField) {
  126.             rate = ((Number)rateField.getValue()).doubleValue();
  127.         } else if (source == numPeriodsField) {
  128.             numPeriods = ((Number)numPeriodsField.getValue()).intValue();
  129.         }
  130.         double payment = computePayment(amount, rate, numPeriods);
  131.         paymentField.setValue(new Double(payment));
  132.     }
  133.     /**
  134.      * Create the GUI and show it.  For thread safety,
  135.      * this method should be invoked from the
  136.      * event-dispatching thread.
  137.      */
  138.     private static void createAndShowGUI() {
  139.         //Create and set up the window.
  140.         JFrame frame = new JFrame("FormatterFactoryDemo");
  141.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  142.         //Create and set up the content pane.
  143.         JComponent newContentPane = new FormatterFactoryDemo();
  144.         newContentPane.setOpaque(true); //content panes must be opaque
  145.         frame.setContentPane(newContentPane);
  146.         //Display the window.
  147.         frame.pack();
  148.         frame.setVisible(true);
  149.     }
  150.     public static void main(String[] args) {
  151.         //Schedule a job for the event-dispatching thread:
  152.         //creating and showing this application's GUI.
  153.         javax.swing.SwingUtilities.invokeLater(new Runnable() {
  154.             public void run() {
  155.                 createAndShowGUI();
  156.             }
  157.         });
  158.     }
  159.     //Compute the monthly payment based on the loan amount,
  160.     //APR, and length of loan.
  161.     double computePayment(double loanAmt, double rate, int numPeriods) {
  162.         double I, partial1, denominator, answer;
  163.         numPeriods *= 12;        //get number of months
  164.         if (rate > 0.001) {
  165.             I = rate / 12.0;         //get monthly rate from annual
  166.             partial1 = Math.pow((1 + I), (0.0 - numPeriods));
  167.             denominator = (1 - partial1) / I;
  168.         } else { //rate ~= 0
  169.             denominator = numPeriods;
  170.         }
  171.         answer = (-1 * loanAmt) / denominator;
  172.         return answer;
  173.     }
  174.     //Create and set up number formats. These objects also
  175.     //parse numbers input by user.
  176.     private void setUpFormats() {
  177.         amountDisplayFormat = NumberFormat.getCurrencyInstance();//获得货币的格式化实例
  178.         amountDisplayFormat.setMinimumFractionDigits(0);//设置小数部分的最小位数,默认为0
  179.         amountDisplayFormat.setMaximumFractionDigits(10);//设置小数部分的最大位数,默认为0
  180.         amountEditFormat = NumberFormat.getNumberInstance();//获得数字的格式化实例
  181.         amountEditFormat.setMinimumFractionDigits(0);//设置小数部分的最小位数 ,默认为0
  182.         amountEditFormat.setMaximumFractionDigits(10)//设置小数部分的最大位数,默认为0
  183.         percentDisplayFormat = NumberFormat.getPercentInstance();
  184.         percentDisplayFormat.setMinimumFractionDigits(2);//默认小数部分最大为0
  185.         percentEditFormat = NumberFormat.getNumberInstance();
  186.         percentEditFormat.setMinimumFractionDigits(2);//默认小数部分最大为0
  187.         paymentFormat = NumberFormat.getCurrencyInstance();//获得货币的格式化实例
  188.     }
  189. }
例2
  1. import java.awt.*;
  2. import javax.swing.*;
  3. import javax.swing.text.*;
  4. import java.util.*;
  5. import java.text.*;
  6. public class FormattedSample {
  7.   public static void main (String args[]) throws ParseException {
  8.     JFrame f = new JFrame("JFormattedTextField Sample");
  9.     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  10.     Container content = f.getContentPane();
  11.     content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
  12.     // Four-digit year, followed by month name and day of month,
  13.     // each separated by two dashes (--)
  14.     DateFormat format = 
  15.       new SimpleDateFormat("yyyy--MMMM--dd");
  16.     DateFormatter df = new DateFormatter(format);
  17.     JFormattedTextField ftf1 = new 
  18.       JFormattedTextField(df);
  19.     ftf1.setValue(new Date());
  20.     content.add(ftf1);
  21.     // US Social Security number
  22.     MaskFormatter mf1 = 
  23.       new MaskFormatter("###-##-####");
  24.     mf1.setPlaceholderCharacter('_');
  25.     JFormattedTextField ftf2 = new 
  26.       JFormattedTextField(mf1);
  27.     content.add(ftf2);
  28.     // US telephone number
  29.     MaskFormatter mf2 = 
  30.       new MaskFormatter("(###) ###-####");
  31.     JFormattedTextField ftf3 = new 
  32.       JFormattedTextField(mf2);
  33.     content.add(ftf3);
  34.     f.setSize(300100);
  35.     f.show();
  36.   }
  37. }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值