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()中的static,想要运行成功就要把MyFrame.showtime()改为MyFrame.this.showtime求解释
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
3条回答 默认 最新
threenewbee 2020-04-12 23:50关注showtime如果不是一个静态函数,就不能在静态函数中直接调用,道理很简单,非静态成员函数的调用依赖对象的实例,静态函数中没有。
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报