import java设置时间
import java.text.DecimalFormat; public class Time {
private int hour;
private int minute;
private int second;
private static DecimalFormat twoDigits=new DecimalFormat("00");
public Time(){
this(0,0,0);
}
public Time(int h){
this(h,0,0);
}
public Time(int h,int m){
this(h,m,0);
}
public Time(int h,int m,int s){
setTime(h,m,s);
}
public Time(Time time){
this(time.getHour(),time.getMinute(),time.getSecond());
}
public void setTime(int h,int m,int s){
setHour(h);
setMinute(m);
setSecond(s);
}
public void setHour(int h){
hour =((h>=0&&h<24)?h:0);
}
public void setMinute(int m){
minute=((m>=0&&m<60)?m:0); }
public void setSecond(int s){
minute=((s>=0&&s<60)?s:0); }
public int getHour(){
return hour;
}
public int getMinute(){
return minute;
}
public int getSecond(){
return second;
}
public String toUniversalString(){
return twoDigits.format(getHour())+":"+
twoDigits.format(getMinute())+":"+
twoDigits.format(getSecond());
}
public String toString(){
return ((getHour()==12||getHour()==0)?
12:getHour()%12)+":"+twoDigits.format(getMinute())
+":"+twoDigits.format(getSecond())+
(getHour()<12?"AM":"PM");
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TimeTestWindow extends JFrame
{
private Time time;
private JLabel hourLabel,minuteLabel,secondLabel;
private JTextField hourField,minuteField,secondField,displayField;
public TimeTestWindow()
{
super ("嵌套内部类使用例子");
time=new Time();
creatGUI();
registerEventHandlers();
}
private void creatGUI()
{Container container=getContentPane();
container.setLayout(new FlowLayout());
hourLabel=new JLabel("设置时");
hourField=new JTextField(10);
container.add(hourLabel);
container.add(hourField);
minuteLabel=new JLabel("设置分");
minuteField=new JTextField(10);
container.add(minuteLabel);
container.add(minuteField);
secondLabel=new JLabel("设置秒");
secondField=new JTextField(10);
container.add(secondLabel);
container.add(secondField);
displayField=new JTextField(30);
displayField.setEditable(false);
container.add(displayField);
}
private void registerEventHandlers()
{
ActionEventHandler handler=new ActionEventHandler();
hourField.addActionListener(handler);
minuteField.addActionListener(handler);
secondField.addActionListener(handler);
}
private class ActionEventHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==hourField)
{
time.setHour(Integer.parseInt(event.getActionCommand()));
}
else if(event.getSource()==minuteField)
{
time.setMinute(Integer.parseInt(event.getActionCommand()));
}
else if(event.getSource()==secondField)
{
time.setSecond(Integer.parseInt(event.getActionCommand()));
}
displayTime();
}
}
private void displayTime()
{
displayField.setText("时间:"+time);
}
public static void main(String args[])
{TimeTestWindow window=new TimeTestWindow();
window.addWindowListener(new WindowAdapter()
{public void windowClosing(WindowEvent event)
{System.exit(0);}
}
);
window.setSize(550,150);
window.setVisible(true);
}
}