java它 ------ 图形界面(两)

<img src="http://img.blog.csdn.net/20150604093446275?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMTQ3OTg3NQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
import java.awt.FlowLayout;
import java.awt.GridLayout;

import javax.swing.JButton;
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 textMoney,textStr;
	private MessageJDialog jdialog;
	
	public MoneyJFrame(){
		super("金额的中文大写形式");
		this.setSize(360, 90);
		this.setLocationRelativeTo(null);//设置窗体居中
		this.setResizable(false);//设置窗体大小不能改变
		this.setBackground(java.awt.Color.lightGray);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);//单击关闭button时。结束程序执行
		this.getContentPane().setLayout(new FlowLayout(FlowLayout.RIGHT));
		this.getContentPane().add(new JLabel("金额"));
		textMoney=new JTextField("12345678.90",22);
		this.getContentPane().add(textMoney);
		textMoney.addCaretListener(this);//注冊文本编辑事件。即文本编辑器中要有变化就响应
		this.getContentPane().add(new JLabel("中文大写形式"));
		textStr=new JTextField(22);
		textStr.setHorizontalAlignment(JTextField.RIGHT);
		textStr.setEditable(false);
		this.getContentPane().add(textStr);
		caretUpdate(null);//执行文本编辑事件,相当于初始化
		this.setVisible(true);
		jdialog=new MessageJDialog();//创建对话框对象
	}
	
	private class MessageJDialog extends JDialog{//消息对话框,私有实例内部类,对象嵌套
		private JLabel jlabel;
		public MessageJDialog(){//内部类的构造方法
			super(MoneyJFrame.this,"提示",true);//MoneyJFrame.this引用外部类的当前对象(即对话框所依附的框架窗体)true表示吗。模式窗体(即仅仅有对话窗体关闭或操作完才干对依附框架窗体进行操作)
			this.setSize(300, 80);
			//this.setLayout(new GridLayout(2,1));
			jlabel=new JLabel("",JLabel.CENTER);
			this.getContentPane().add(jlabel);
			this.setDefaultCloseOperation(HIDE_ON_CLOSE);
			//this.add(new JButton("确定"));
		}
		
		private void show(String message){//对话框的显示
			jlabel.setText(message);
			this.setLocation(MoneyJFrame.this.getX()+100, MoneyJFrame.this.getY()+100);//对话框位置在框架下方
			this.setVisible(true);
		}
	}
	
	public void caretUpdate(CaretEvent e) {//文本编辑事件处理方法
		try {
			double x=Double.parseDouble(textMoney.getText());
			textStr.setText(RMBtoString(x));
		} catch (NumberFormatException e1) {
			jdialog.show("""+textMoney.getText()+"" 不能转换成浮点数,请又一次输入!");
		}
	}
	
	private String RMBtoString(double x) {//将x表示的金额转换成中文大写形式
		String yuan="亿千百拾万千百拾元角分";
		String digit="零壹贰叁肆伍陆柒捌玖";
		String result="";
		int y=(int) (x*100);//浮点数扩充100倍后取整(保留两位有效数字)
		for(int i=yuan.length()-1;y>0&&i>0;i--,y/=10){
			result=""+digit.charAt(y%10)+yuan.charAt(i)+result;
		}
		return result;
	}

	public static void main(String[] args) {
		new MoneyJFrame();
	}


}




版权声明:本文博客原创文章。博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/yxwkf/p/4741819.html