ウィジェット---金額変換
7527 ワード
これは教科書の中の1つの例題で、私は最適化を行ってこの比較的に満足するプログラムを書いて、悪いところがあって多く指導することを望みます.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
public class MoneyJFrame extends JFrame implements CaretListener {
private JTextField tfdNum,tfdChinese;
private MesDialog mdg ;
public MoneyJFrame() {
super(" ");
setBounds(200, 100, 450, 130);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container c = getContentPane();//
c.setLayout(new FlowLayout(FlowLayout.RIGHT));
c.add(new JLabel(" :"));
tfdNum = new JTextField("123.45",30);
c.add(tfdNum);
c.add(new JLabel(" :"));
tfdChinese = new JTextField("",30);
tfdChinese.setEditable(false);
c.add(tfdChinese);
//
tfdNum.addCaretListener(this);
// ,
mdg = new MesDialog(this);
// ,
caretUpdate(null);
setVisible(true);
}
public static void main(String[] args) {
new MoneyJFrame();
}
@Override
public void caretUpdate(CaretEvent e) {
String str = tfdNum.getText();
str.trim();
if (str == null|| str.length()==0) {
tfdChinese.setText("");
return ;
}
try {
double num = Double.parseDouble(str);
if (Math.log10(num)>12) {
String mes = str+" ";
mdg.show(mes);
return;
}
String Chinese = toChinese(num);
tfdChinese.setText(Chinese);
} catch (NumberFormatException e1) {
String mes = " :"+str;
mdg.show(mes);
}
}
private String toChinese(double num) {
String unit = " ";
String money = " ";
String res = "";
long x = (long)((num+0.005)*100);
int index = unit.length()-1;
while (x>0 && index>-1) {
res = ""+money.charAt((int)(x%10))+unit.charAt(index--)+res;
x /= 10;
}
return res;
}
}
//
class MesDialog extends JDialog{
private JFrame jFrame;
private JLabel lb;
public MesDialog(JFrame jFrame) {
this.jFrame = jFrame;
setTitle(" ");
setSize(300, 120);
Container c = getContentPane();
c.setBackground(Color.WHITE);
lb = new JLabel();
c.add(lb);
JButton btnOk = new JButton(" ");
btnOk.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
JPanel p = new JPanel();
p.setBackground(Color.WHITE);
p.add(btnOk);
c.add(p,BorderLayout.SOUTH);
}
public void show(String mes) {
lb.setText(mes);
setLocation(jFrame.getX()+90, jFrame.getY()+70);
setVisible(true);
}
}