How can I set a customized currency symbol to be applied to a number?
Created May 7, 2012
Of course, a large amount of work has been done with these classes, including locales, to
avoid customization, but the following code shows how I would do it when necessary:
// JCusCF.java - Custom CurrencyFormat
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.util.*;
public class JCusCF extends JFrame
implements ActionListener,
WindowListener
{
boolean bPre = true;
int ndx = 0;
JButton jb = new JButton( "Go" );
JLabel jlI = new JLabel("Input Currency Value:"),
jlD = new JLabel("Display:"),
jlP = new JLabel("Parsed:");
JPanel jp = new JPanel();
JTextField jtI = new JTextField( 10 ),
jtD = new JTextField( 10 ),
jtP = new JTextField( 10 );
NumberFormat cfLocal = NumberFormat.
getCurrencyInstance();
NumberFormat cf2 = NumberFormat.
getCurrencyInstance();
String sCurSymbol = "";
public JCusCF()
{
super( "JCusCF" );
DecimalFormatSymbols dfs = null;
addWindowListener( this );
jb.addActionListener( this );
jp.add(jlI);
jp.add(jtI);
jp.add(jb);
jp.add(jlD);
jp.add(jtD);
jp.add(jlP);
jp.add(jtP);
getContentPane().add( jp, BorderLayout.CENTER );
pack();
show();
if( cfLocal instanceof DecimalFormat )
{ // determine if symbol is prefix or suffix
dfs =
((DecimalFormat)cfLocal).
getDecimalFormatSymbols();
sCurSymbol = dfs.getCurrencySymbol();
String sLP = ((DecimalFormat)cfLocal).
toLocalizedPattern();
ndx = sLP.indexOf( 'u00A4' ); // currency sign
if( ndx > 0 ) { bPre = false; }
else { bPre = true; }
}
// code to modify getDecimalFormatSymbols
if( cf2 instanceof DecimalFormat )
{ // determine if symbol is prefix or suffix
dfs =
((DecimalFormat)cf2).getDecimalFormatSymbols();
dfs.setCurrencySymbol("Rs");
dfs.setGroupingSeparator('&');
dfs.setMonetaryDecimalSeparator('$');
((DecimalFormat)cf2).setDecimalFormatSymbols(dfs);
System.out.println(cf2.format(3333.454));
}
} // end constructor
// ActionListener Implementation
public void actionPerformed(ActionEvent e)
{
Number n = null;
String sText = jtI.getText();
jtD.setText( "" );
jtP.setText( "" );
ndx = sText.indexOf( sCurSymbol );
if( ndx == -1 )
{
if( bPre ) { sText = sCurSymbol + sText; }
else { sText = sText + " " + sCurSymbol; }
}
try
{
n = cfLocal.parse( sText );
jtI.setText( cfLocal.format( n ) );
jtD.setText( cf2.format( n ) );
n = cf2.parse( jtD.getText() );
jtP.setText( n.toString() );
}
catch( ParseException pe ) { jtI.setText( "" ); }
} // End actionPerformed
// Window Listener Implementation
public void windowOpened(WindowEvent e) {}
public void windowClosing(WindowEvent e)
{
dispose();
System.exit(0);
}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
// End Window Listener Implementation
public static void main(String[] args)
{
new JCusCF();
}
} // end class JCusCF