1 import java.awt.event.ActionEvent;
2 import java.awt.event.ActionListener;
3 import java.text.SimpleDateFormat;
4 import java.util.Calendar;
5 import javax.swing.ButtonGroup;
6 import javax.swing.JMenu;
7 import javax.swing.JRadioButtonMenuItem;
8 import javax.swing.Timer;
9
10 public class TimeMenu extends JMenu{
11 private static final long serialVersionUID = 1L;
12 private final static int ONE_SECOND=1000;
13 private String timeStyle="";
14
15 public TimeMenu(String text){
16 super(text);
17 timeStyle="yyyy-MM-dd HH:mm:ss";
18 timer.start();
19 addSubMenuItems();
20 }
21
22 Timer timer=new Timer(ONE_SECOND,new ActionListener(){
23 public void actionPerformed(ActionEvent evt){
24 setCurrTimeToText();
25 }
26 });
27
28 private void addSubMenuItems(){
29 String[] items=new String[]{"yyyy-MM-dd HH:mm:ss","HH:mm:ss","yyyy-MM-dd"};
30
31 ButtonGroup buttongroup = new ButtonGroup();
32
33 for (int i = 0; i < items.length; i++) {
34 JRadioButtonMenuItem timeMitem = new JRadioButtonMenuItem(
35 items[i], i == 0);
36
37 final String timeStyleTmp = items[i];
38 timeMitem.addActionListener(new ActionListener() {
39 public void actionPerformed(ActionEvent e) {
40 try {
41 timeStyle=timeStyleTmp;
42 } catch (Exception ex) {
43 System.out.println("Can't Change Time Style to "
44 + timeStyleTmp);
45 }
46 }
47 });
48 buttongroup.add(timeMitem);
49 this.add(timeMitem);
50 }
51 }
52
53 private void setCurrTimeToText(){
54 this.setText(getCurrTime(timeStyle));
55 }
56
57 private String getCurrTime(String timeStyle){
58 Calendar cal= Calendar.getInstance();
59 SimpleDateFormat fromatter=new SimpleDateFormat(timeStyle);
60 String strCurrTime=fromatter.format(cal.getTime());
61
62 return strCurrTime;
63 }
64 }
用法如下:
1 JMenuBar menubar = new JMenuBar();
2 mainFrame.setJMenuBar(menubar);
3
4
5
6 TimeMenu timeMenu = new TimeMenu("Time");
7 menubar.add(timeMenu);
8
9