2016-10-10 44 views
-2

我正在做這種形式,要求名稱,姓氏,性別,身高等... 我已經添加keyTyped操作處理程序來做完整性檢查,(只能命名字母,年齡最大2數字等)如何刷新JTextField的值以匹配實際值?

事情是,檢查工作,但我可以在窗體中看到的價值與實際價值不匹配,例如我爲高度寫'1.333'(以米爲單位),檢查器完成它的工作並告訴只接受像1.33這樣的值的用戶。

所以我用

formattedTextField.setText(StringUtils.substring(formattedTextField.getText(), 0, 4)); 

如果我在文本字段寫1.333,存儲的實際值是1.33,但1.333停留在文本字段

這是我已經試過

formattedTextField = new JFormattedTextField(); 
    formattedTextField.addKeyListener(new KeyAdapter() { 
     @Override 
     public void keyTyped(KeyEvent arg0) { 
      String re1="^([+-]?\\d*\\.?\\d*)$"; 
      System.out.println(formattedTextField.getText().matches(re1)); 
      if(formattedTextField.getText().length() >= 1 && formattedTextField.getText().matches(re1) == true) 
      {      

       if(formattedTextField.getText().length() >= 3) 
       { 
        final BalloonTip balloonTip = new BalloonTip(
          formattedTextField, 
          new JLabel("<html>Solo se aceptan valores de altura, como 1.66, 1.76, 1.88, etc..</html>"), 
          style, 
          BalloonTip.Orientation.LEFT_ABOVE, 
          BalloonTip.AttachLocation.ALIGNED, 
          20, 10, 
          false 
         ); 
        TimingUtils.showTimedBalloon(balloonTip, 4500); 
        formattedTextField.setText(StringUtils.substring(formattedTextField.getText(), 0, 4)); 



       } 
      } 

     } 
    }); 
contentPane.add(formattedTextField, "cell 2 9,growx,aligny center"); 

Example

+4

按評論到您的[前一個問題(http://stackoverflow.com/questions/ 39864104/how-can-add-a-button-to-get-two-values),請創建併發布有效的[mcve]。這不是你的整個計劃,而是一個非常簡短的程序,可以向我們展示你的問題。 –

+0

你永遠不想在Swing文本組件上使用KeyListener。如果您想要更好的答案,請再次提出您的問題。 –

回答

2

試試這個: 的Cre吃了3個全局變量:

private String oldValue; 
private final Pattern pattern = Pattern.compile("^\\d+\\.?\\d{0,2}$"); 
private Matcher matcher; 

而你需要存儲舊值和正則表達式comprare新的價值

formattedTextField.addKeyListener(new KeyAdapter() { 
    public void keyPressed(KeyEvent evt) { 
      oldValue = formattedTextField.getText(); 
    } 

    public void keyReleased(KeyEvent evt) { 
     matcher = pattern.matcher(formattedTextField.getText()); 
     if(!matcher.matches()){ 
      formattedTextField.setText(oldValue); 
     } 
    } 
}