package my;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MyFrame extends JFrame
{
static JLabel timeLabel = new JLabel("00:00:00");
JButton button = new JButton("显示时间");
public MyFrame(String title)
{
super(title);
// 内容面板 (ContentPane)
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// 向内容面板里添加控件
contentPane.add(button);
contentPane.add(timeLabel);
// 创建监听器对象
MyButtonListener listener = new MyButtonListener();
// 把监听器注册给按钮
button.addActionListener( listener );
}
public static void showtime()
{
SimpleDateFormat ppp=new SimpleDateFormat("HH:MM:SS");
String timeppp = ppp.format(new Date());
timeLabel.setText(timeppp);
}
// ActionListener 是一个 interface
public class MyButtonListener implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
// 当按钮被点击时,Swing框架会调用监听器的 actionPerformed()方法
System.out.println("按钮被点击...");
MyFrame.showtime();
}
}
}
showtime如果不是一个静态函数,就不能在静态函数中直接调用,道理很简单,非静态成员函数的调用依赖对象的实例,静态函数中没有。
public static void showtime() 是类方法,可以用类名直接调用;
public void showtime() 是实例方法;
MyButtonListener是内部类;
如果需要访问外部类的方法或者成员域的时候,如果使用 this.成员域(与 内部类.this.成员域 没有分别) 调用的显然是内部类的域 , 如果我们想要访问外部类的域的时候,就要必须使用 外部类.this.成员域
【成员域:成员方法或成员变量】
在程序允许过程中,静态方法不需要类被实例化就会被加载的,非静态方法是在类被实例化的时候加载,必须依托于对象进行调用,否则虚拟机根本不知道你调用的是什么方法。