簡體   English   中英

文本字段onchange驗證

[英]Textfield onchange validation

我正在使用以下代碼編寫貸款計算器,但是當我嘗試驗證用戶的輸入時,我無法讓setText運行。 我沒有收到任何編譯錯誤,只是無法正常工作。 我有以下代碼:

public class LoanCalculator extends JFrame {
  // Create text fields for interest rate,
// year, loan amount, monthly payment, and total payment
private JTextField jtfAnnualInterestRate = new JTextField("5");
private JTextField jtfNumberOfYears = new JTextField("10");
private JTextField jtfLoanAmount = new JTextField("10000");
private JTextField jtfMonthlyPayment = new JTextField("106.07");
private JTextField jtfTotalPayment = new JTextField("12727.86");

// Create a Compute Payment button
private JButton jbtClear = new JButton("Reset Fields");

public LoanCalculator() {
// Panel p1 to hold labels and text fields
JPanel p1 = new JPanel(new GridLayout(5, 2));
p1.add(new JLabel("Annual Interest Rate"));
p1.add(jtfAnnualInterestRate);
p1.add(new JLabel("Number of Years"));
p1.add(jtfNumberOfYears);
p1.add(new JLabel("Loan Amount"));
p1.add(jtfLoanAmount);
p1.add(new JLabel("Monthly Payment"));
p1.add(jtfMonthlyPayment);
p1.add(new JLabel("Total Payment"));
p1.add(jtfTotalPayment);
p1.setBorder(new
TitledBorder("Enter loan amount, interest rate, and year"));
jtfTotalPayment.setEditable(false);
jtfMonthlyPayment.setEditable(false);

// Panel p2 to hold the button
JPanel p2 = new JPanel(new FlowLayout(FlowLayout.RIGHT));
p2.add(jbtClear);

// Add the panels to the frame
add(p1, BorderLayout.CENTER);
add(p2, BorderLayout.SOUTH);

// Register listeners
jbtClear.addActionListener(new ButtonListener());
jtfAnnualInterestRate.getDocument().addDocumentListener(new DocListener());
jtfNumberOfYears.getDocument().addDocumentListener(new DocListener());
jtfLoanAmount.getDocument().addDocumentListener(new DocListener());
}

/** Handle textfield changes */
class DocListener implements DocumentListener {
 public void insertUpdate(DocumentEvent e) { validate(); }
 public void removeUpdate(DocumentEvent e) { }
 public void changedUpdate(DocumentEvent e) { }

 public void validate() {
     //get values from text fields
     double interest = Double.parseDouble(jtfAnnualInterestRate.getText());
 int year = Integer.parseInt(jtfNumberOfYears.getText());
 double loanAmt = Double.parseDouble(jtfLoanAmount.getText());
 Loan loan = new Loan(interest, year, loanAmt);


 //validate field values and shift focus if needed
 if (! (interest >= 1 && interest <= 10)){
     JOptionPane.showMessageDialog(null, 
        "interest must be between 1 and 10 percent");
     jtfAnnualInterestRate.setText("5");                   //THIS DOESN'T RUN
     jtfAnnualInterestRate.requestFocus(true);
 }       
 //display monthly and total payments
 else {
      jtfMonthlyPayment.setText(String.format("%.2f", 
                          loan.getMonthlyPayment()));
      jtfTotalPayment.setText(String.format("%.2f", 
                  loan.getTotalPayment()));
 }
 }
}

/** Handle the Reset button Code not included */
}

public static void main(String[] args) {
 LoanCalculator frame = new LoanCalculator();
 frame.pack();
 frame.setTitle("LoanCalculator");
 Dimension screenSize =
   Toolkit.getDefaultToolkit().getScreenSize();
 int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
// Locate the upper-left corner at (x, y)
int x =  3 * (screenWidth - frame.getWidth()) / 4;
int y = (screenHeight - frame.getHeight()) /2;
frame.setLocation(x, y);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

知道我哪里出錯了嗎?

您不能在其自己的DocumentListener內對JTextComponent進行突變,至少不能直接對其進行突變。 我知道兩種可能的解決方案:

1)將文本更改排隊到Runnable內部的EDT上:

if (!(interest >= 1 && interest <= 10)) {
   JOptionPane.showMessageDialog(null, "interest must be between 1 and 10 percent");
   SwingUtilities.invokeLater(new Runnable() {
      public void run() {
         jtfAnnualInterestRate.setText("5"); // THIS DOESN'T RUN
         jtfAnnualInterestRate.requestFocus(true);
      }
   });

2)使用DocumentFilter


編輯
關於您的問題的注意事項:

它只是不起作用。 我有以下代碼:

它所做的不只是“不起作用”。 實際上,它引發了一個重要的異常,該異常准確地描述了您的代碼在做什么錯以及在哪里

Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Attempt to mutate in notification
    at javax.swing.text.AbstractDocument.writeLock(Unknown Source)
    at javax.swing.text.AbstractDocument.replace(Unknown Source)
    at javax.swing.text.JTextComponent.setText(Unknown Source)
    at pkg.LoanCalculator$DocListener.validate(LoanCalculator.java:78) // your numbers will be different
    at pkg.LoanCalculator$DocListener.insertUpdate(LoanCalculator.java:58) // ditto

下次您問類似的問題時,您可能想在問題中發布信息豐富的異常堆棧跟蹤。 這將幫助我們實現自我。


編輯2
同樣在下一次,請嘗試僅發布編譯所必需且與您的問題相關的代碼。 例如,您只需要發布JTextField,DocumentListener並將其顯示在簡單的JOptionPane中即可。

import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;

public class LoanCalcSscce {
   protected static final double MIN_INTEREST = 0;
   protected static final double MAX_INTEREST = 10;

   public static void main(String[] args) {
      final JTextField jtfAnnualInterestRate = new JTextField("5");
      jtfAnnualInterestRate.getDocument().addDocumentListener(
            new DocumentListener() {

               @Override
               public void removeUpdate(DocumentEvent e) {
                  validate(e);
               }

               @Override
               public void insertUpdate(DocumentEvent e) {
                  validate(e);
               }

               @Override
               public void changedUpdate(DocumentEvent e) {
                  validate(e);
               }

               public void validate(DocumentEvent e) {
                  final Document doc = e.getDocument();
                  try {
                     String text = doc.getText(0, doc.getLength()).trim();
                     double interest = Double.parseDouble(text);

                     if (!(interest >= MIN_INTEREST && interest <= MAX_INTEREST)) {
                        JOptionPane.showMessageDialog(null,
                              "interest must be between 1 and 10 percent");
                        SwingUtilities.invokeLater(new Runnable() {
                           public void run() {
                              jtfAnnualInterestRate.setText("5");
                              jtfAnnualInterestRate.requestFocus(true);
                           }
                        });
                     }
                  } catch (BadLocationException e1) {
                     e1.printStackTrace();
                  } catch (NumberFormatException nfe) {
                     // inform user and set interest to baseline.
                  }
               }
            });
      JOptionPane.showMessageDialog(null, jtfAnnualInterestRate);
   }
}

而且,我們可以更輕松地分析您的代碼並幫助您解決它。 這稱為sscce


編輯3
為了我的錢,我不會在DocumentListener中驗證我的輸入,因為這可能會在輸入尚未完成時嘗試驗證。 當用戶決定通過按下“提交”(或任何您稱呼它)按鈕來提交數據時,我將進行所有驗證。 換句話說,我將在ActinoListener中進行驗證。 例外:如果輸入只能是數字,或者只能是小寫字母,或者其他可以驗證部分輸入也很重要的東西,則可以在DocumentFilter中進行驗證。


編輯4
正如MadProgrammer在評論中建議的那樣,還認真考慮了使用InputVerifier作為當用戶離開輸入字段(此處為JTextField)時驗證輸入的一種不錯的方法: InputVerifier教程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM