为什么在 LWUIT 中 Button 可以有自己的 ActionListener(通过 button.addActionListener)而 Command 没有?
为特定命令设置监听器的唯一方法是向表单添加 ActionListener 并检查事件来自哪个命令的监听器,如下所示?
public void startApp() {
Display.init(this);
f = new Form("Mixed Record");
exit = new Command("Exit");
start = new Command("Start");
Button button = new Button("Button");
f.addCommand(exit);
f.addCommand(start);
f.addCommand(delete);
f.addComponent(button);
f.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (ae.getCommand().equals(exit)) {
//Do Exit command code
} else if (ae.getCommand().equals(start)) {
//Do Start command code
}
}
});
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
//Do button code
}
});
f.show();
}
最佳答案
好吧,我无法确切地告诉您为什么编写 LWUIT 的人会做出这个决定,但有几个原因可以说明它是有道理的。
当一个表单包含多个命令时,它们被分组在一个菜单中。每次用户展开然后折叠菜单时,最多执行一个命令。因此,命令在概念上比按钮更相互关联,特别是因为将按钮子类从一个表单重用到另一个表单并不少见。
对于使 LWUIT 窗体的 API 看起来很像 MIDP 规范中的 LCDUI 窗体,可能还有人担心。
我也喜欢您的代码显示了该决定的一个积极结果:
您的代码中已经有 2 个未命名的内部类(ActionListener 子类)。如果每个 Command 都有自己的 ActionListener,您可能会编写 3 个未命名的内部类。开发人员倾向于这样做很多,即使当您花更多时间查看包含多个未命名内部类的代码的堆栈跟踪时,您会意识到在每个命名类中拥有多个是不好的做法。
关于java - 为什么在 LWUIT 中按钮有 Action 监听器而命令没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11654374/