import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;

import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;

public class MoneyJFrame extends JFrame implements CaretListener{
private JTextField tfdMoney,tfdText;
private MessageDialog dlg=null; //内部类对象

public MoneyJFrame(String str) {
super(str);
setBounds(300, 240, 470, 120);
setDefaultCloseOperation(EXIT_ON_CLOSE); //关闭则结束程序
Container c = getContentPane(); //返回一个getContenPane()对象
c.setLayout(new FlowLayout(FlowLayout.RIGHT)); //设置为流布局

JLabel lb1=new JLabel("金额"); //设置标签
c.add(lb1); //标签加入到面板中
tfdMoney = new JTextField("12345.67",30);//new一个文本条看,不能换行
c.add(tfdMoney);
JLabel lb2=new JLabel("中文大写形式");
c.add(lb2);
tfdText = new JTextField(30);
tfdText.setEditable(false); //设置文本不能编辑
c.add(tfdText);

//设置字体
Font font = new Font("黑体",Font.BOLD,18); //设置字体大小
lb1.setFont(font);
lb2.setFont(font);
tfdMoney.setFont(font);
tfdText.setFont(font);

//监听
tfdMoney.addCaretListener(this);

//程序初始显示时,手动触发一次事件,让中文金额能够直接显示
caretUpdate(null); //Update()它是由JVM执行的,在这里起一个刷新作用

dlg=new MessageDialog(this);

setVisible(true);
}

@Override
public void caretUpdate(CaretEvent e) {
String str = tfdMoney.getText();
try {
double x = Double.parseDouble( str);
tfdText.setText( rmb2string(x) );
} catch (NumberFormatException e1) {
dlg.show(str );
}
}

private static String rmb2string(double x) {
String unit = "百拾亿千百拾万千百拾元角分";
String digit="零壹贰叁肆伍陆柒捌玖";
String res="";

int y =(int) (x*100+0.5);//乘以100,四舍五入
int i=unit.length()-1;
while(y>0 && i>0){
res =""+ digit.charAt(y%10)+unit.charAt(i) +res; //这里需要注意字符串的拼接
i--;
y=y/10;
}

return res;
}

public static void main(String[] args) {
new MoneyJFrame("金额的中文大写形式");
}

}

class MessageDialog extends JDialog{
private JFrame frame;
private JLabel warnLb;
private JLabel lbMsg;
public MessageDialog(JFrame frame) {
super(frame,"警告!");
this.frame=frame;
setSize(400, 300);
setDefaultCloseOperation(HIDE_ON_CLOSE);
getContentPane().setLayout(new FlowLayout());

warnLb = new JLabel(new ImageIcon("imgs/warn.jpg")); //设置标签,并且用图片的方式显示
lbMsg=new JLabel();
lbMsg.setFont(new Font("黑体",Font.BOLD,20));
getContentPane().add(warnLb);
getContentPane().add(lbMsg);
}
public void show(String strMsg){
setLocation(frame.getX()+50, frame.getY()+50); //这里是获Frame取框架做左上角坐标,这样设计提示信息框可以跟着框架“跑”
lbMsg.setText(strMsg);
setVisible(true);
}
}