com.codename1.ui.events.ActionListener Java Examples

The following examples show how to use com.codename1.ui.events.ActionListener. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PushDemo.java    From codenameone-demos with GNU General Public License v2.0 6 votes vote down vote up
public void start() {
    if(current != null){
        current.show();
        return;
    }
    s = new StateMachine("/theme");        
    
    Display.getInstance().addEdtErrorHandler(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            evt.consume();
            Log.p("Exception in AppName version " + Display.getInstance().getProperty("AppVersion", "Unknown"));
            Log.p("OS " + Display.getInstance().getPlatformName());
            Log.p("Error " + evt.getSource());
            Log.p("Current Form " + Display.getInstance().getCurrent().getName());
            Log.e((Throwable)evt.getSource());
            Log.sendLog();
        }
    });
}
 
Example #2
Source File: Ads.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void initComponent() {
    if(service != null) {
        service.initialize(this);
        service.addResponseListener(new ActionListener() {

            public void actionPerformed(ActionEvent evt) {
                String a = (String) evt.getSource();
                setAd(a);
            }
        });
        
        if (refreshAd) {
            getComponentForm().registerAnimated(this);
        }else{
            requestAd();            
        }
    }
}
 
Example #3
Source File: SideMenuBar.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Folds the current side menu if it is open, when the menu is closed it
 * will invoke the runnable callback method
 *
 * @param callback will be invoked when the menu is actually closed
 */
public static void closeCurrentMenu(final Runnable callback) {
    if(Toolbar.isOnTopSideMenu() && (Toolbar.isGlobalToolbar() || Display.getInstance().getCommandBehavior() != Display.COMMAND_BEHAVIOR_SIDE_NAVIGATION)) {
        Display.getInstance().getCurrent().getToolbar().closeSideMenu();
        callback.run();
        return;
    }
    Form f = Display.getInstance().getCurrent();
    final SideMenuBar b = (SideMenuBar) f.getClientProperty("cn1$sideMenuParent");
    if (b != null && !b.transitionRunning) {
        b.parent.addShowListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                b.parent.removeShowListener(this);
                callback.run();
            }
        });
        b.closeMenu();
    } else {
        callback.run();
    }
}
 
Example #4
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get a list of FaceBook objects for a given id
 * 
 * @param faceBookId the id to preform the query upon
 * @param itemsConnection the type of the query
 * @param feed
 * @param params
 * @param callback the callback that should be updated when the data arrives
 */
public void getFaceBookObjectItems(String faceBookId, String itemsConnection,
        final DefaultListModel feed, Hashtable params, final ActionListener callback) throws IOException {
    checkAuthentication();

    final FacebookRESTService con = new FacebookRESTService(token, faceBookId, itemsConnection, false);
    con.setResponseDestination(feed);
    con.addResponseListener(new Listener(con, callback));
    if (params != null) {
        Enumeration keys = params.keys();
        while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();
            con.addArgument(key, (String) params.get(key));
        }
    }
    if (slider != null) {
        SliderBridge.bindProgress(con, slider);
    }
    for (int i = 0; i < responseCodeListeners.size(); i++) {
        con.addResponseCodeListener((ActionListener) responseCodeListeners.elementAt(i));
    }
    current = con;
    NetworkManager.getInstance().addToQueue(con);
}
 
Example #5
Source File: FBDemo.java    From codenameone-demos with GNU General Public License v2.0 6 votes vote down vote up
private Component showShare() {
    final Container c = new Container(new BorderLayout());
    final ShareButton share = new ShareButton();
    final TextArea t = new TextArea("Sharing on Facebook with CodenameOne is a breeze.\n"
            + "http://www.codenameone.com\n"
            + "(Sent from the facebook demo app)");
    t.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            share.setTextToShare(t.getText());
        }
    });
    c.addComponent(BorderLayout.CENTER, t);
    share.setTextToShare(t.getText());
    Container cnt = new Container(new BorderLayout());
    cnt.addComponent(BorderLayout.SOUTH, share);
    c.addComponent(BorderLayout.EAST, cnt);
    return c;
}
 
Example #6
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gest an album from an albumId
 *
 * @param albumId the albumId
 * @param album an Object to fill with the data
 * @param callback the callback that should be updated when the data arrives
 */
public void getAlbum(String albumId, final Album album, final ActionListener callback) throws IOException {
    getFaceBookObject(albumId, new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            Vector v = (Vector) ((NetworkEvent) evt).getMetaData();
            Hashtable t = (Hashtable) v.elementAt(0);
            if (album != null) {
                album.copy(t);
            }
            if (callback != null) {
                callback.actionPerformed(evt);
            }
        }
    });
}
 
Example #7
Source File: Form.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
private void addKeyListener(int keyCode, ActionListener listener, HashMap<Integer, ArrayList<ActionListener>> keyListeners) {
    if (keyListeners == null) {
        keyListeners = new HashMap<Integer, ArrayList<ActionListener>>();
    }
    Integer code = new Integer(keyCode);
    ArrayList<ActionListener> vec = keyListeners.get(code);
    if (vec == null) {
        vec = new ArrayList<ActionListener>();
        vec.add(listener);
        keyListeners.put(code, vec);
        return;
    }
    if (!vec.contains(listener)) {
        vec.add(listener);
    }
}
 
Example #8
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the picture of the given facebook object id
 *
 * @param id the object id to query
 * @param callback the callback that should be updated when the data arrives
 * @param toScale picture dimension or null
 * @param tempStorage if true place the image in a temp storage
 */
public void getPicture(String id, final ActionListener callback, Dimension toScale, boolean tempStorage) throws IOException {
    checkAuthentication();

    FacebookRESTService fb = new FacebookRESTService(token, id, FacebookRESTService.PICTURE, false);
    if(toScale != null){
        fb.addArgument("width", "" + toScale.getWidth());
        fb.addArgument("height", "" + toScale.getHeight());
    }else{
        fb.addArgument("type", "small");
    }
    String cacheKey = id;
    //check if this image is a temporarey resource and it is not saved
    //already has a permanent image
    if (tempStorage && !Storage.getInstance().exists(id)) {
        cacheKey = TEMP_STORAGE + id;
    }
    ImageDownloadService.createImageToStorage(fb.requestURL(), callback, cacheKey);
}
 
Example #9
Source File: CachedDataService.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Checks that the cached data is up to date and if a newer version exits it updates the data in place
 * 
 * @param d the data to check
 * @param callback optional callback to be invoked on request completion
 */
public static void updateData(CachedData d, ActionListener callback) {
    if(d.isFetching()) {
        return;
    }
    d.setFetching(true);
    CachedDataService c = new CachedDataService();
    c.setUrl(d.getUrl());
    c.setPost(false);
    if(callback != null) {
        c.addResponseListener(callback);
    }
    if(d.getModified() != null && d.getModified().length() > 0) {
        c.addRequestHeader("If-Modified-Since", d.getModified());
        if(d.getEtag() != null) {
            c.addRequestHeader("If-None-Match", d.getEtag());
        }
    }
    NetworkManager.getInstance().addToQueue(c);        
}
 
Example #10
Source File: Sheet.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
private void initUI() {
    setLayout(new BorderLayout());
    contentPane.setSafeArea(true);
    titleBar.setSafeArea(true);
    add(BorderLayout.NORTH, titleBar);
    if (parentSheet != null) {
        FontImage.setMaterialIcon(backButton, FontImage.MATERIAL_ARROW_BACK);
    }
    add(BorderLayout.CENTER, contentPane);
    backButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            back(DEFAULT_TRANSITION_DURATION);
        }
    });
    
}
 
Example #11
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Post a message on the users wall
 *
 * @param userId the userId
 * @param message the message to post
 */
public void postOnWall(String userId, String message, ActionListener callback) throws IOException {
    checkAuthentication();

    FacebookRESTService con = new FacebookRESTService(token, userId, FacebookRESTService.FEED, true);
    con.addArgument("message", "" + message);
    con.addResponseListener(new Listener(con, callback));
    if (slider != null) {
        SliderBridge.bindProgress(con, slider);
    }
    for (int i = 0; i < responseCodeListeners.size(); i++) {
        con.addResponseCodeListener((ActionListener) responseCodeListeners.elementAt(i));
    }
    current = con;
    NetworkManager.getInstance().addToQueueAndWait(con);
}
 
Example #12
Source File: RequestBuilder.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Executes the request asynchronously and writes the response to the provided
 * Callback. This fetches JSON data and parses it into a properties business object
 * @param callback writes the response to this callback
 * @param type the class of the business object returned
 * @return returns the Connection Request object so it can be killed if necessary
 */ 
public ConnectionRequest fetchAsProperties(final OnComplete<Response<PropertyBusinessObject>> callback, final Class type) {
    final Connection request = createRequest(true);
    request.addResponseListener(new ActionListener<NetworkEvent>() {
        @Override
        public void actionPerformed(NetworkEvent evt) {
            if(request.errorCode) {
                return;
            }
            Response res = null;
            Map response = (Map)evt.getMetaData();
            try {
                PropertyBusinessObject pb = (PropertyBusinessObject)type.newInstance();
                pb.getPropertyIndex().populateFromMap(response);
                res = new Response(evt.getResponseCode(), pb, evt.getMessage());
                callback.completed(res);
            } catch(Exception err) {
                Log.e(err);
                throw new RuntimeException(err.toString());
            }
        }
    });
    fetched = true;
    CN.addToQueue(request);       
    return request;
}
 
Example #13
Source File: FaceBookAccess.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This method creates a component which can authenticate. You will receive either the
 * authentication key or an Exception object within the ActionListener callback method.
 * 
 * @param al a listener that will receive at its source either a token for the service or an exception in case of a failure
 * @return a component that should be displayed to the user in order to perform the authentication
 */
public Component createAuthComponent(final ActionListener al) {
    return createOAuth().createAuthComponent(new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            if(evt.getSource() instanceof String){
                token = (String) evt.getSource();
            }
            al.actionPerformed(evt);
        }
    });
}
 
Example #14
Source File: Tree.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Since a node may be any component type developers should override this method to
 * add support for binding the click listener to the given component.
 * @param l listener interface
 * @param node node component returned by createNode
 */
protected void bindNodeListener(ActionListener l, Component node) {
    if(node instanceof Button) {
        ((Button)node).addActionListener(l);
        return;
    }
    ((SpanButton)node).addActionListener(l);
}
 
Example #15
Source File: NetworkManager.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Identical to add to queue but returns an AsyncResource object that will resolve to
 * the ConnectionRequest.
 * 
 * @param request the request object to add.
 * @return AsyncResource resolving to the connection request on complete.
 * @since 7.0
 */
public AsyncResource<ConnectionRequest> addToQueueAsync(final ConnectionRequest request) {
    final AsyncResource<ConnectionRequest> out = new AsyncResource<ConnectionRequest>();
    class WaitingClass implements ActionListener<NetworkEvent> {
        

        public void actionPerformed(NetworkEvent e) {
            if(e.getError() != null) {
                
                removeProgressListener(this);
                removeErrorListener(this);
                if (!out.isDone()) {
                    out.error(e.getError());
                }
                return;
            }
            if(e.getConnectionRequest() == request) {
                if(e.getProgressType() == NetworkEvent.PROGRESS_TYPE_COMPLETED) {
                    if(request.retrying) {
                        request.retrying = false;
                        return;
                    }
                    
                    removeProgressListener(this);
                    removeErrorListener(this);
                    if (!out.isDone()) {
                        out.complete(request);
                    }
                    return;
                }
            }
        }
    }
    WaitingClass w = new WaitingClass();
    addProgressListener(w);
    addErrorListener(w);
    addToQueue(request);
    return out;
}
 
Example #16
Source File: Form.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This listener is invoked when device orientation changes on devices that support orientation change
 *
 * @param l the listener
 */
public void removeOrientationListener(ActionListener l) {
    if (orientationListener == null) {
        return;
    }
    orientationListener.removeListener(l);
}
 
Example #17
Source File: Web.java    From codenameone-demos with GNU General Public License v2.0 5 votes vote down vote up
public Container createDemo() {
    Container cnt = new Container(new BorderLayout());
    final WebBrowser wb = new WebBrowser();
    if(wb.getInternal() instanceof BrowserComponent) {
        Button btn = new Button("Add");
        final TextArea content = new TextArea();
        Container north = new Container(new BorderLayout());
        north.addComponent(BorderLayout.CENTER, content);
        north.addComponent(BorderLayout.EAST, btn);
        cnt.addComponent(BorderLayout.NORTH, north);
        content.setHint("Add to web document");
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                ((BrowserComponent)wb.getInternal()).execute("fnc('" + content.getText() + "');");
            }
        });
        ((BrowserComponent)wb.getInternal()).setBrowserNavigationCallback(new BrowserNavigationCallback() {
            public boolean shouldNavigate(String url) {
                if(url.startsWith("http://sayhello")) {
                    // warning!!! This is not on the EDT and this method MUST return immediately!
                    Display.getInstance().callSerially(new Runnable() {
                        public void run() {
                            ((BrowserComponent)wb.getInternal()).execute("fnc('this was written by Java code!')");
                        }
                    });
                    return false;
                }
                return true;
            }
        });
    }
    
    cnt.addComponent(BorderLayout.CENTER, wb);
    wb.setURL("jar:///Page.html");
    return cnt;
}
 
Example #18
Source File: TextArea.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes an action listener
 * 
 * @param a actionListener
 */
public void removeActionListener(ActionListener a) {
    if(actionListeners == null) {
        return;
    }
    actionListeners.removeListener(a);
    if(!actionListeners.hasListeners()) {
        actionListeners = null;
    }
}
 
Example #19
Source File: ConnectionRequest.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes the given listener
 *
 * @param a listener
 */
public void removeResponseCodeListener(ActionListener<NetworkEvent> a) {
    if(responseCodeListeners == null) {
        return;
    }
    responseCodeListeners.removeListener(a);
    if(responseCodeListeners.getListenerCollection()== null || responseCodeListeners.getListenerCollection().size() == 0) {
        responseCodeListeners = null;
    }
}
 
Example #20
Source File: BrowserWindow.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adds listeners to be notified when a page is loaded in the browser window.  ActionEvents
 * will have the URL of the page as a string as its "source" property.
 * @param l Listener to add.
 */
public void addLoadListener(ActionListener l) {
    if (nativeWindow != null) {
        Display.impl.addNativeBrowserWindowOnLoadListener(nativeWindow, l);
    } else {
        webview.addWebEventListener("onLoad", l);
    }
}
 
Example #21
Source File: BrowserComponent.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Registers a callback to be run when the BrowserComponent is "ready".  The browser component
 * is considered to be ready once the onLoad event has been fired on the first page.
 * If this method is called after the browser component is already "ready", then the callback
 * will be executed immediately.  Otherwise it will be called in the first onLoad event.
 * @param onReady Callback to be executed when the browser component is ready.
 * @return Self for chaining.
 * @since 7.0
 * @see #waitForReady() 
 */
public BrowserComponent ready(final SuccessCallback<BrowserComponent> onReady) {
    if (ready) {
        onReady.onSucess(this);
    } else {
        ActionListener l = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                removeWebEventListener(onStart, this);
                onReady.onSucess(BrowserComponent.this);
            }
        };
        addWebEventListener(onStart, l);
    }
    return this;
}
 
Example #22
Source File: Accordion.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
public AccordionContent(Component header, final Component body) {
    setUIID(uiidBackGroundItem);
    setLayout(new BorderLayout());
    this.body = body;
    this.header = header;
    header.setSelectedStyle(header.getUnselectedStyle());
    header.setPressedStyle(header.getUnselectedStyle());
    String t = (String)body.getClientProperty("cn1$setHeaderUIID");
    if(t != null) {
        topUiid = t;
    }

    top = new Container(new BorderLayout(), topUiid);
    top.add(BorderLayout.CENTER, header);
    arrow.setUIID(uiidOpenCloseIcon);
    arrow.setIcon(closeIcon);
    arrow.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent evt) {
            
            //toggle the current
            openClose(!isClosed());
            if(autoClose){
                for (int i = 0; i < Accordion.this.getComponentCount(); i++) {
                    AccordionContent c = (AccordionContent)Accordion.this.getComponentAt(i);
                    if(c != AccordionContent.this && !c.isClosed()){
                        c.openClose(true);
                    }
                }
            }
            Accordion.this.animateLayout(250);
            fireEvent(evt);
        }
    });
    top.add(BorderLayout.EAST, arrow);
    top.setLeadComponent(arrow);
    add(BorderLayout.NORTH, top);
    body.setHidden(true);
    add(BorderLayout.CENTER, body);
}
 
Example #23
Source File: UIBuilder.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes a command listener
 *
 * @param l the listener to remove
 */
public void removeCommandListener(ActionListener l) {
    if(globalCommandListeners == null) {
        return;
    }
    globalCommandListeners.removeListener(l);
}
 
Example #24
Source File: NetworkManager.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adds a listener to be notified when progress updates
 *
 * @param al action listener
 */
public void addProgressListener(ActionListener<NetworkEvent> al) {
    if(progressListeners == null) {
        progressListeners = new EventDispatcher();
        progressListeners.setBlocking(false);
    }
    progressListeners.addListener(al);
}
 
Example #25
Source File: SideMenuBar.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
public void run() {
    if(Display.getInstance().isEdt()) {
        ActionEvent e = new ActionEvent(cmd, ActionEvent.Type.Command);
        if (cmd instanceof NavigationCommand) {
            parent.getContentPane().setVisible(true);
            final Form nextForm = ((NavigationCommand) cmd).getNextForm();
            if (nextForm != null) {
                final Transition out = parent.getTransitionOutAnimator();
                final Transition in = nextForm.getTransitionInAnimator();
                parent.setTransitionOutAnimator(CommonTransitions.createEmpty());
                nextForm.setTransitionInAnimator(CommonTransitions.createEmpty());
                nextForm.addShowListener(new ActionListener() {

                    public void actionPerformed(ActionEvent evt) {
                        parent.setTransitionOutAnimator(out);
                        nextForm.setTransitionInAnimator(in);
                        nextForm.removeShowListener(this);
                    }
                });
            }
        }
        parent.dispatchCommand(cmd, e);

        return;
    }

    synchronized (LOCK) {
        while (Display.getInstance().getCurrent() != parent) {
            try {
                LOCK.wait(40);
            } catch (Exception ex) {
            }
        }
    }
    Display.getInstance().callSerially(this);
}
 
Example #26
Source File: ComponentSelector.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adds a drop listener to all components in found set.  Wraps {@link Component#addDropListener(com.codename1.ui.events.ActionListener) } 
 * @param l
 * @return 
 */
public ComponentSelector addDropListener(ActionListener l) {
    for (Component c : this) {
        c.addDropListener(l);
    }
    return this;
}
 
Example #27
Source File: Image.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
@Override
public synchronized void addActionListener(ActionListener l) {
    if (listeners == null) {
        listeners = new EventDispatcher();
    }
    listeners.addListener(l);
}
 
Example #28
Source File: UIManager.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes a Theme refresh listener.
 * 
 * @param l an ActionListener to be removed
 */
public void removeThemeRefreshListener(ActionListener l) {

    if (themelisteners == null) {
        return;
    }
    themelisteners.removeListener(l);
}
 
Example #29
Source File: Display.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * An error handler will receive an action event with the source exception from the EDT
 * once an error handler is installed the default Codename One error dialog will no longer appear
 *
 * @param e listener receiving the errors
 */
public void addEdtErrorHandler(ActionListener e) {
    if(errorHandler == null) {
        errorHandler = new EventDispatcher();
    }
    errorHandler.addListener(e);
}
 
Example #30
Source File: NetworkManager.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Removes the given error listener
 *
 * @param e callback to remove
 */
public void removeErrorListener(ActionListener<NetworkEvent> e) {
    if(errorListeners == null) {
        return;
    }

    errorListeners.removeListener(e);
}