2017-01-16 57 views
0

我使用的JFormattedTextField在下面的文本字段中顯示的百分比值:的JFormattedTextField值是不同的,那麼我所設置

NumberFormat percentDisplayFormat = NumberFormat.getPercentInstance(); 
NumberFormat editFormat = NumberFormat.getNumberInstance(); 

percentDisplayFormat.setMinimumFractionDigits(2); 

NumberFormatter percentEditFormatter = new NumberFormatter(editFormat); 

JFormattedTextField jftfPercentage = new JFormattedTextField(new DefaultFormatterFactory(new NumberFormatter(percentDisplayFormat), new NumberFormatter(percentDisplayFormat), percentEditFormatter)); 

jftfPercentage.setBounds(113, 95, 236, 21); 
jftfPercentage.setName("JftfPercentage"); 

和設置像下面的值:

jftfPercentage.setValue(<someDoubleValue>); 

現在,假設我已將該值設置爲80,那麼它將顯示值爲8000%。
但是,每當我點擊該字段時,它僅顯示爲80。

有人可以幫助我顯示我們設置的相同值。在此先感謝

+2

要得到80%的顯示值,不應該將值設置爲0.80? – trashgod

+0

@trashgod如果我將0.8設置爲一個值,那麼它會顯示爲80%,但是當我點擊該字段時,它僅顯示爲0.8 –

+0

也考慮一個'JSpinner','Slider'或['SpinSlider'] (http://stackoverflow.com/a/6067986/230513)。 – trashgod

回答

0

我在這裏得到了問題。在內部,默認數字格式化程序在顯示時將給定值乘以100。 (如果我們使用PercentInstance)

NumberFormat percentDisplayFormat = NumberFormat.getPercentInstance(); 
NumberFormat editFormat = NumberFormat.getNumberInstance(); 

percentDisplayFormat.setMinimumFractionDigits(2); 

NumberFormatter percentEditFormatter = new NumberFormatter(editFormat); 

// This was the new change that I have made 
NumberFormatter percentDisplayFormatter = new NumberFormatter(percentDisplayFormat) 
{ 
    @Override 
    public String valueToString(Object o) throws ParseException 
    { 
     Double number = null; 
     if (o != null) 
     { 
      number = Double.valueOf(o.toString()); 
      number /= 100; 
     } 
     // In super class, it multiplies the number by 100. So as we are dividing the number by 100 here. In super level it will become the same value that we have given   
     return super.valueToString(number); 
    } 
}; 

JFormattedTextField jftfPercentage = new JFormattedTextField(new DefaultFormatterFactory(percentDisplayFormatter, percentDisplayFormatter, percentEditFormatter)); 

jftfPercentage.setBounds(113, 95, 236, 21); 
jftfPercentage.setName("JftfPercentage"); 
相關問題