2014-01-16 33 views
0

什麼被認爲是格式化Wicket TextFields的最佳做法?例如,我希望貨幣字段有一個符號和一個逗號。我已經通過使用IConverter實現創建了一個解決方案,並且它有用。但是,我對焦點上的行爲不滿意。我想格式化在焦點上被刪除。我怎樣才能做到這一點?Wicket textfield貨幣格式化焦點

回答

0

你可以創建一個自定義行爲:

public class CurrencyFormattingBehavior extends Behavior{ 
private static final long serialVersionUID = -4754030237711643182L; 

private final String format; 

public CurrencyFormattingBehavior(final String format){ 
    this.format = format; 
} 

@Override 
public void renderHead(Component component, IHeaderResponse response) { 
    super.renderHead(component, response); 
    String script = "var currencyInputField = $('#"+component.getMarkupId()+"');" 
      + "currencyInputField.on('focus', function(){" 
      + "currencyInputField.val(currencyInputField.val().replace('"+format+"', ''));" 
      + "});" 
      + "currencyInputField.on('blur', function(){" 
      + "currencyInputField.val(currencyInputField.val() + '"+format+"')" 
      + "});"; 

    response.render(OnDomReadyHeaderItem.forScript(script)); 
    } 
} 

,然後將其用於任何文本字段:

public class HomePage extends WebPage { 

private final String testString = ""; 
    public HomePage(final PageParameters parameters) { 
    super(parameters); 
    TextField<String> textField = new TextField<String>("text", new PropertyModel<String>(this, "testString")); 
    add(textField); 
    textField.add(new CurrencyFormattingBehavior(" €")); 
    } 
} 

但是這僅僅是一個非常非常快速和簡單的例子。對於更高級的格式,我會建議使用正則表達式。