import java.util.Calendar;
import java.util.Date;
import java.awt.*;
import java.awt.event.*;
import java.text.NumberFormat;
public class H {
public static void main(String args[]) {
new Time("年龄计算器");
}
}
class Time extends Frame implements ActionListener {
Calendar calendar;
Button button;
TextField t1, t2, t3;
Label l, l1, l2, l3;
Time(String s) {
super(s);
setLayout(new FlowLayout());
button = new Button("确定");
button.addActionListener(this);
t1 = new TextField(2);
t2 = new TextField(2);
t3 = new TextField(2);
l = new Label(" 请输入您的生日 ");
l.setBackground(Color.cyan);
l1 = new Label("年");
l2 = new Label("月");
l3 = new Label("日");
add(l);
add(t1);
add(l1);
add(t2);
add(l2);
add(t3);
add(l3);
add(button);
setBounds(100, 100, 280, 100);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e) {
calendar = Calendar.getInstance();
calendar.setTime(new Date());
NumberFormat f = NumberFormat.getInstance();
long time = calendar.getTimeInMillis();
if (e.getSource() == button) {
try {
int n = Integer.parseInt(t1.getText());
int y = Integer.parseInt(t2.getText());
int r = Integer.parseInt(t3.getText());
calendar.set(n, y - 1, r);
double time1 = calendar.getTimeInMillis();
double c = (time - time1) / (1000 * 60 * 60 * 24);
double d = c/365;
f.setMaximumFractionDigits(2);
String s = f.format(d);
l.setText("您的年龄约为" + s + " 岁");
} catch (NumberFormatException ee) {
l.setText("请正确输入");
}
}
}
}
功底浅薄,如果有问题,还望指教。
温馨提示:答案为网友推荐,仅供参考