亚洲av成人无遮挡网站在线观看,少妇性bbb搡bbb爽爽爽,亚洲av日韩精品久久久久久,兔费看少妇性l交大片免费,无码少妇一区二区三区

  免費(fèi)注冊(cè) 查看新帖 |

Chinaunix

  平臺(tái) 論壇 博客 文庫(kù)
最近訪問(wèn)板塊 發(fā)新帖
查看: 1444 | 回復(fù): 0
打印 上一主題 下一主題

How to Use Formatted Text Fields(為 GUI 文本框添加驗(yàn)證器) [復(fù)制鏈接]

論壇徽章:
0
跳轉(zhuǎn)到指定樓層
1 [收藏(0)] [報(bào)告]
發(fā)表于 2007-07-13 10:09 |只看該作者 |倒序?yàn)g覽

                                                How to Use Formatted Text Fields
如何使用格式化的文本框
   
原文地址
    格式化的文本框?yàn)殚_(kāi)發(fā)者提供了一種在文本框中只輸入有效字符集的方式。
尤其是 JFormattedTextField 類(lèi)在功能上添加了繼承自 JTextField 類(lèi)的一個(gè) formatter
(格式化方法)和一個(gè)對(duì)象值。 formatter 將字段值翻譯成它顯示的文本,也將文本翻譯成值。
    Formatted text fields provide a way for developers to specify the valid
set of characters that can be typed in a text field. Specifically, the
JFormattedTextField class adds a formatter and an object value to the
features inherited from the JTextField class. The formatter translates
the field's value into the text it displays, and the text into the
field's value.
    Using the formatters that Swing provides, you can set up formatted text fields to type dates and numbers in localized formats. Another kind of formatter enables you to use a character mask to specify the set of characters that can be typed at each position in the field. For example, you can specify a mask for typing phone numbers in a particular format, such as (XX) X-XX-XX-XX-XX.
    使用 Swing 提供的 formatters,可以設(shè)置在文本字段中鍵入本地化的日期和數(shù)字。還有一種 formatter 可以讓您使用一個(gè)字符掩碼來(lái)特指可以在字段內(nèi)每個(gè)位置上鍵入的字符集。例如,可以為鍵入一定格式的電話號(hào)碼--如 (XX) X-XX-XX-XX-XX)--指定一個(gè)掩碼。
    If the possible values of a formatted text field have an obvious order, use a spinner instead. A spinner uses a formatted text field by default, but adds two buttons that enable the user to choose a value in a sequence.
    如果格式化的文本字段的可能值具有明顯順序,那么應(yīng)該改用 spinner。spinner 默認(rèn)情況下使用一個(gè)格式化的文本字段,只是多加了兩個(gè)按鈕,以便用戶(hù)選擇序列中的一個(gè)值。
    Another alternative or adjunct to using a formatted text field is installing an input verifier on the field. A component's input verifier is called when the component nearly loses the keyboard focus. The input verifier enables you to check whether the value of the component is valid and optionally change it or stop the focus from being transferred.
    使用格式化的文本字段的另一個(gè)選擇或另一個(gè)修飾方法是在字段上加裝一個(gè)驗(yàn)證器。在組件即將失去鍵盤(pán)焦點(diǎn)時(shí)調(diào)用組件的輸入驗(yàn)證器。輸入驗(yàn)證器可以讓您檢查組件的值是否有效,然后選擇修改該值或者選擇停止傳遞。
    This GUI uses formatted text fields to display numbers in four different formats.
    GUI 使用格式化的文本字段以四種不同的格式顯示數(shù)值。
   

    A snapshot of FormattedTextFieldDemo
    FormattedTextFieldDemo 屏幕截圖
Try this:
嘗試以下方法:
    1. Click the Launch button to run FormattedTextFieldDemo using Java? Web Start (download JDK 6). Alternatively, to compile and run the example yourself, consult the example index.
    1. 單擊“啟動(dòng)”,使用 java web start (
下載 JDK 6
)運(yùn)行 FormattedTextFieldDemo。您也可以自己編譯和運(yùn)行這個(gè)例子,請(qǐng)參考
示例索引頁(yè)
。
              
啟動(dòng)
FormattedTextFieldDemo 應(yīng)用程序
    2. Experiment with different loan amounts, annual percentage rates (APRs), and loan lengths.
    Note that as long as the text you type is valid, the Month Payment field is updated when you press Enter or move the focus out of the field that you are editing.
    2. 實(shí)驗(yàn)填入一些其他貸款金額,年率(APRs)和貸款期限。請(qǐng)注意,只要您輸入的值有效,那么月付(Month Payment)字段應(yīng)付在按 Enter 鍵或?qū)⒔裹c(diǎn)移出所編譯的字段的時(shí)候更新。
     
    3. Type invalid text such as "abcd" in the Loan Amount field and then press Enter.
    The Month Payment field remains the same. When you move the focus from the Loan Amount field, the text reverts to the field's last valid value.
    3. 在貸款金額(Loan Amount)字段輸入無(wú)效的文字,如“abcd”,然后按 Enter 鍵。月付字段保持不變。當(dāng)焦點(diǎn)移出貸款金額(Loan Amount)字段時(shí),文本又恢復(fù)到上次輸入到該字段的有效值了。
    4. Type marginally valid text such as "2000abcd" in the Loan Amount field and press Enter.
    The Monthly Payment field is updated, though the Loan Amount field still displays 2000abcd. When you move the focus from the Loan Amount field, the text it displays is updated to a neatly formatted version of its value, for example, "2,000".
    4. 在貸款金額(Loan Amount)字段輸入有限的有效文本如 "2000abcd" 然后按 Enter 鍵。月付字段被更新,然而貸款金額字段仍顯示 2000abcd。當(dāng)焦點(diǎn)移出貸款金額(Loan Amount)字段時(shí),文本被更新為原值的一個(gè)整齊的格式化的版本,如 "2000"。
以下為 FormattedTextFieldDemo.java 代碼:
               
               
               
               
               
               
                package components;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
import java.text.*;
/**
* FormattedTextFieldDemo.java requires no other files.
*
* It implements a mortgage calculator that uses four
* JFormattedTextFields.
*/
public class FormattedTextFieldDemo extends JPanel
                                    implements PropertyChangeListener {
    //Values for the fields
    private double amount = 100000;
    private double rate = 7.5;  //7.5%
    private int numPeriods = 30;
    //Labels to identify the fields
    private JLabel amountLabel;
    private JLabel rateLabel;
    private JLabel numPeriodsLabel;
    private JLabel paymentLabel;
    //Strings for the labels
    private static String amountString = "Loan Amount: ";
    private static String rateString = "APR (%): ";
    private static String numPeriodsString = "Years: ";
    private static String paymentString = "Monthly Payment: ";
    //Fields for data entry
    private JFormattedTextField amountField;
    private JFormattedTextField rateField;
    private JFormattedTextField numPeriodsField;
    private JFormattedTextField paymentField;
    //Formats to format and parse numbers
    private NumberFormat amountFormat;
    private NumberFormat percentFormat;
    private NumberFormat paymentFormat;
    public FormattedTextFieldDemo() {
        super(new BorderLayout());
        setUpFormats();
        double payment = computePayment(amount,
                                        rate,
                                        numPeriods);
        //Create the labels.
        amountLabel = new JLabel(amountString);
        rateLabel = new JLabel(rateString);
        numPeriodsLabel = new JLabel(numPeriodsString);
        paymentLabel = new JLabel(paymentString);
        //Create the text fields and set them up.
        amountField = new JFormattedTextField(amountFormat);
        amountField.setValue(new Double(amount));
        amountField.setColumns(10);
        amountField.addPropertyChangeListener("value", this);
        rateField = new JFormattedTextField(percentFormat);
        rateField.setValue(new Double(rate));
        rateField.setColumns(10);
        rateField.addPropertyChangeListener("value", this);
        numPeriodsField = new JFormattedTextField();
        numPeriodsField.setValue(new Integer(numPeriods));
        numPeriodsField.setColumns(10);
        numPeriodsField.addPropertyChangeListener("value", this);
        paymentField = new JFormattedTextField(paymentFormat);
        paymentField.setValue(new Double(payment));
        paymentField.setColumns(10);
        paymentField.setEditable(false);
        paymentField.setForeground(Color.red);
        //Tell accessibility tools about label/textfield pairs.
        amountLabel.setLabelFor(amountField);
        rateLabel.setLabelFor(rateField);
        numPeriodsLabel.setLabelFor(numPeriodsField);
        paymentLabel.setLabelFor(paymentField);
        //Lay out the labels in a panel.
        JPanel labelPane = new JPanel(new GridLayout(0,1));
        labelPane.add(amountLabel);
        labelPane.add(rateLabel);
        labelPane.add(numPeriodsLabel);
        labelPane.add(paymentLabel);
        //Layout the text fields in a panel.
        JPanel fieldPane = new JPanel(new GridLayout(0,1));
        fieldPane.add(amountField);
        fieldPane.add(rateField);
        fieldPane.add(numPeriodsField);
        fieldPane.add(paymentField);
        //Put the panels in this panel, labels on left,
        //text fields on right.
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        add(labelPane, BorderLayout.CENTER);
        add(fieldPane, BorderLayout.LINE_END);
    }
    /** Called when a field's "value" property changes. */
    public void propertyChange(PropertyChangeEvent e) {
        Object source = e.getSource();
        if (source == amountField) {
            amount = ((Number)amountField.getValue()).doubleValue();
        } else if (source == rateField) {
            rate = ((Number)rateField.getValue()).doubleValue();
        } else if (source == numPeriodsField) {
            numPeriods = ((Number)numPeriodsField.getValue()).intValue();
        }
        double payment = computePayment(amount, rate, numPeriods);
        paymentField.setValue(new Double(payment));
    }
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event dispatch thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("FormattedTextFieldDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Add contents to the window.
        frame.add(new FormattedTextFieldDemo());
        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
    public static void main(String[] args) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                //Turn off metal's use of bold fonts
            UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
            }
        });
    }
    //Compute the monthly payment based on the loan amount,
    //APR, and length of loan.
    double computePayment(double loanAmt, double rate, int numPeriods) {
        double I, partial1, denominator, answer;
        numPeriods *= 12;        //get number of months
        if (rate > 0.01) {
            I = rate / 100.0 / 12.0;         //get monthly rate from annual
            partial1 = Math.pow((1 + I), (0.0 - numPeriods));
            denominator = (1 - partial1) / I;
        } else { //rate ~= 0
            denominator = numPeriods;
        }
        answer = (-1 * loanAmt) / denominator;
        return answer;
    }
    //Create and set up number formats. These objects also
    //parse numbers input by user.
    private void setUpFormats() {
        amountFormat = NumberFormat.getNumberInstance();
        percentFormat = NumberFormat.getNumberInstance();
        percentFormat.setMinimumFractionDigits(3);
        paymentFormat = NumberFormat.getCurrencyInstance();
    }
}
               
               

本文來(lái)自ChinaUnix博客,如果查看原文請(qǐng)點(diǎn):http://blog.chinaunix.net/u/21951/showart_339025.html
您需要登錄后才可以回帖 登錄 | 注冊(cè)

本版積分規(guī)則 發(fā)表回復(fù)

  

北京盛拓優(yōu)訊信息技術(shù)有限公司. 版權(quán)所有 京ICP備16024965號(hào)-6 北京市公安局海淀分局網(wǎng)監(jiān)中心備案編號(hào):11010802020122 niuxiaotong@pcpop.com 17352615567
未成年舉報(bào)專(zhuān)區(qū)
中國(guó)互聯(lián)網(wǎng)協(xié)會(huì)會(huì)員  聯(lián)系我們:huangweiwei@itpub.net
感謝所有關(guān)心和支持過(guò)ChinaUnix的朋友們 轉(zhuǎn)載本站內(nèi)容請(qǐng)注明原作者名及出處

清除 Cookies - ChinaUnix - Archiver - WAP - TOP