| Home >> All >> com >> obs >> gui >> swing >> [ interfaces Javadoc ] |
Source code: com/obs/gui/swing/interfaces/MoneyTextField.java
1 2 package com.obs.gui.swing.interfaces; 3 import org.apache.log4j.Logger; 4 5 import javax.swing.*; 6 import javax.swing.text.MaskFormatter; 7 import java.math.BigDecimal; 8 import java.text.ParseException; 9 10 /** 11 * Created by IntelliJ IDEA. 12 * User: Owner 13 * Date: 12-Jun-2003 14 * Time: 11:45:49 PM 15 * To change this template use Options | File Templates. 16 */ 17 18 /** 19 * JTextField that will ensure data is formatted as currency 20 */ 21 public class MoneyTextField 22 extends JFormattedTextField { 23 24 // logger 25 protected Logger log = Logger.getLogger(MoneyTextField.class); 26 27 public MoneyTextField() { 28 super(); 29 30 31 setColumns(8); 32 setScrollOffset(0); 33 34 MaskFormatter mask = new MaskFormatter(); 35 36 try { 37 mask.setMask("$***.**"); 38 } catch (ParseException e) { 39 log.warn(e); 40 } 41 mask.setValidCharacters(" 0123456789"); 42 43 //mask.setAllowsInvalid(false); 44 mask.install(this); 45 } 46 47 public float getAmount() { 48 49 StringBuffer text = new StringBuffer(getText()); 50 text.delete(0, 1); 51 52 float amount = 0; 53 try { 54 amount = Float.parseFloat(text.toString()); 55 } catch (NumberFormatException e) { 56 //log.error("Invalid Number: " + text); 57 return 0; 58 } 59 60 return amount; 61 } 62 63 public void setAmount(float amount) { 64 65 BigDecimal b = new BigDecimal(amount); 66 StringBuffer stringAmount = new StringBuffer(b.setScale(2, BigDecimal.ROUND_HALF_UP).toString()); 67 68 if (amount < 100) { 69 stringAmount.insert(0, ' '); 70 } 71 72 if (amount < 10) { 73 stringAmount.insert(0, ' '); 74 } 75 76 setText(stringAmount.toString()); 77 } 78 }