在下面的工作代码,匿名内部类 - javac如何与lambda表达式一起工作?
package com.ca.naive;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.List;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TodoGUI {
public static void main(String[] args) {
List list = new List();
TextField itemField = new TextField();
Button addButton = new Button("Add");
Button removeButton = new Button("Remove");
addButton.addActionListener(e -> list.add(itemField.getText()));
removeButton.addActionListener(e -> list.remove(list.getSelectedIndex()));
Panel buttons = new Panel(new GridLayout(1,0,3,3));
buttons.add(addButton);
buttons.add(removeButton);
Panel bottomPanel = new Panel(new FlowLayout(FlowLayout.RIGHT));
bottomPanel.add(buttons);
Panel centerPanel = new Panel(new BorderLayout());
centerPanel.add(BorderLayout.NORTH, itemField);
centerPanel.add(BorderLayout.SOUTH, buttons);
Frame frame = new Frame();
frame.setLayout(new BorderLayout());
frame.add(BorderLayout.WEST, list);
frame.add(BorderLayout.CENTER, centerPanel);
frame.pack();
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.setVisible(true);
}
}
是否javac的替代addButton.addActionListener(e -> list.add(itemField.getText()));
语法与
addButton.addActionListener(new java.awt.Event.ActionListener() {
public void actionPerformed(java.awt.Event.ActionEvent e) {
list.add(itemField.getText());
}
});
?
_ [an'import'语句] ...允许您使用单个标识符(例如'List','min')来引用类型或静态成员,而不是完全限定的名称(例如'java .util.List','Math.min')_你没有使用类型名称,所以你不需要'import'语句。 –
@SotiriosDelimanolis你的意思是,'javac'通过检测传递给'addButton.addActionListener()'的对象的类型在内部解析类型名称'ActionListener'?在提出此查询之前,您的评论的第一部分是已知的 – overexchange
是的,它知道您尝试调用的方法需要一个'ActionListener'。据推测,这是唯一适用的方法。但是对于_resolve name_,则不需要解析名称,因为您没有使用名称。 'import'语句只是简化了源代码。他们什么都不做。 –