Search code examples
codenameone

What are the diffenences between addPointerPressed and addActionListener?


I have sample codes below:

    hi = new Form("Click Test Application", BoxLayout.y());
    Label l = new Label("Click by Program");
    hi.add(l);
    b1 = new Button("Click Button 2","DescButton");
    b1.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ev){      
            hi.pointerPressed(b2.getAbsoluteX(), b2.getAbsoluteY());
        }
    });
    hi.add(b1);
    b2 = new Button("Button_2","DescButton");
    b2.addPointerPressedListener(new ActionListener(){
        public void actionPerformed(ActionEvent ev){      
            b2.setText("Button 2 Pressed");
        }
    });    
    b2.addPointerReleasedListener(new ActionListener(){
        public void actionPerformed(ActionEvent ev){      
            b2.setText("Button 2 Released");
        }
    }); 
    hi.add(b2);                
    hi.show();

The b2 button shows 'Button 2 Pressed' after I click b1. The b2 button shows 'Button 2 Released' after I click b2.

What are the differences between addActionListener and addPointerPressedListener? How do I send the click event(addActionListener, not addPointerPressedListener) to b2 by clicking b1 button?

Or I should call pointerPressed and pointerReleased in b1 to simulate the click event?


Solution

  • On Button you have:

    b2.press();
    b2.release();
    

    Which is the right way to trigger this sort of event.

    If you use components other than button then always fire both pressed and released.

    Notice that UI events are almost always implemented on release and rarely on press. The only exception is continuous events like scrolling that keep happening as long as the button remains pressed.

    We use released for two reasons:

    • An event might trigger navigation and the release might be sent to the next form.
    • A user might change his mind and drag his finger out of a button at which point the release might not trigger an action. It's possible that this was just a drag event to begin with...