简体   繁体   English

为什么Button在LWUIT中没有动作侦听器而命令没有?

[英]Why do Buttons have action listeners and commands don't in LWUIT?

Is there any reason why in LWUIT a Button can have its own ActionListener (via button.addActionListener) while a Command does not? 有什么原因为什么按钮在LWUIT中可以有自己的ActionListener(通过button.addActionListener),而Command没有?

Is the only way to have a listener for a specific command is to add an ActionListener to a form and check the listener for which Command the event came from like below? 拥有特定命令的侦听器的唯一方法是将ActionListener添加到表单并检查事件来自哪个Command的侦听器,如下所示?

    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();
}

Well, I can't tell you exactly why the people who wrote LWUIT made that decision but there are several reasons why it makes sense. 好吧,我无法确切地告诉你为什么写LWUIT的人为什么做出这个决定,但是有几个原因使它有意义。

When a Form contains several Commands, they are grouped in a menu. 当一个窗体包含多个命令时,它们被分组在菜单中。 Every time the user expands then collapses the menu, a maximum of one Command is executed. 每次用户展开然后折叠菜单时,最多执行一个命令。 As such, the Commands are conceptually more linked to one another than Buttons are, especially since it is not uncommon to reuse Button subclasses from one Form to another. 这样,命令在概念上比按钮在彼此之间的链接更多,尤其是因为将按钮子类从一种形式重用到另一种形式并不少见。

There might also have been a concern about making the API of the LWUIT Form look a lot like the LCDUI Form in the MIDP specification. 使LWUIT Form的API看起来很像MIDP规范中的LCDUI Form可能也引起了人们的关注。

I also like that your code shows one positive consequence of the decision: 我也喜欢您的代码显示了该决定的一个积极结果:

You already have 2 unnamed inner classes (the ActionListener subclasses) in your code. 您的代码中已经有2个未命名的内部类(ActionListener子类)。 If each Command had its own ActionListener, you would probably have written 3 unnamed inner classes. 如果每个Command都有自己的ActionListener,则您可能会编写3个未命名的内部类。 Developers tend to do that a lot even though, when you have spent a bit more time looking at stack traces of code that contains multiple unnamed inner classes, you will realize that it is bad practice to have more than one in each named class. 即使您花了更多时间查看包含多个未命名内部类的代码的堆栈跟踪时,开发人员仍会做很多事情,您将意识到在每个命名类中都包含多个内部类是一种不好的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM