如何在Button或者输入框中添加系统时间

解决方案 »

  1.   

    什么意思?让Button 上显示的文字是 系统时间 ?
      

  2.   

    需要引进 java.util.Calendar 和 java.text.SimpleDateFormat 这两个类:Calendar rightNow = Calendar.getInstance();
    SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddhhmmss");
    String sysDatetime = fmt.format(rightNow.getTime());  JButton button=new JButton(); 
    button.add(sysDatetime); 
      

  3.   

    JButton 有继承 add方法吗?
    又不是Container。
      

  4.   


    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Date;
    import javax.swing.JButton;
    import javax.swing.JFrame;/**
     * @author bzwm
     *
     */
    public class TimeButton extends JButton implements ActionListener{

    java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    public static void main(String args[]){
    JFrame jf = new JFrame();

    TimeButton b = new TimeButton();
    javax.swing.Timer t = new javax.swing.Timer(1000, b);
    t.start(); jf.add(b);

    jf.setVisible(true);
    jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jf.setSize(300, 300);
    }

    protected void paintComponent(Graphics g){

    this.setText(df.format(new Date()));

    super.paintComponent(g);
    } public void actionPerformed(ActionEvent e) {
    this.repaint();
    }
    }
    以JButton 为例子。