[我有一个问题,我正在用一本书学习Java,并且在其中复制了一些代码(并进行了一些更改)并进行了一些调查,发现有些奇怪……这是代码) >
public static void main(String[] args) { Timer timer = new Timer(1000, (event) -> { System.out.println("At the Tone, the time is" + Instant.ofEpochMilli(event.getWhen())); Toolkit.getDefaultToolkit().beep(); }); timer.start(); JOptionPane.showMessageDialog(null, "Quit?"); System.exit(0); }
这只是一秒钟会通知您的代码。 (此代码可以编译并顺利运行)
如您所见,Timer Constructor需要2个par(int,ActionListener)
public Timer(int delay, ActionListener listener)
并且ActionListener接口具有一种可以执行actionPerform并且需要ActionEvent参数的方法
public void actionPerformed(ActionEvent e);
现在是我的问题,在上面的那个lambda表达式中调用这个actionPerformed方法时编译器如何知道在不向其提供任何有关线索的情况下调用哪个构造函数来实例化ActionEvent,ActionEvent没有“ No arguments Constructor”,并且方法getWhen()不是静态的(必须实例化obj)
这里是ActionEvent的所有构造方法:
public ActionEvent(Object source, int id, String command) public ActionEvent(Object source, int id, String command, int modifiers) public ActionEvent(Object source, int id, String command, long when, int modifiers)
我真的希望我能说清楚!,谢谢
[我有一个问题,我正在用一本书学习Java,并且在其中复制了一些代码(并进行了一些更改)并进行了一些调查,我发现有些奇怪……这里是公开的代码...
编译器不知道! ;-)Timer
实例将在运行时每隔ActionEvent
创建一个delay
实例,并且Timer
实例将使用其创建的actionPerformed
调用ActionListener方法ActionEvent
。
/**
* Fire the action event, named "Timer" and having the numeric
* identifier, equal to the numer of events that have been
* already fired before.
*/
void fireActionPerformed()
{
fireActionPerformed(new ActionEvent(this, ticks++, "Timer"));
}
[如果我们查看javax.swing.Timer
的源代码,我们会注意到Timer
的所有ActionListener都存储在称为javax.swing.event.EventListenerList
的listenerList
上。它们在此行中被调用:
Timer
构造函数仅接收一个侦听器并将其注册在其侦听器列表中。当计时器计时(应在其中调用侦听器)计时时,Timer
实例创建一个新的ActionEvent(请参见Timer.java:245
)并将其传递给已注册的侦听器。