com.codename1.ui.Command Java Examples

The following examples show how to use com.codename1.ui.Command. 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: AddComponentToRightBarSample.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
public void start() {
    if(current != null){
        current.show();
        return;
    }
    Form hi = new Form("Hi World", BoxLayout.y());
    Toolbar toolbar = hi.getToolbar();
    Command cmd = toolbar.addCommandToRightBar("Test", null, evt->{
        System.out.println("Hello");
    });
    
    Component cmp = toolbar.findCommandComponent(cmd);
    cmp.getParent().replace(cmp, new Button("Replaced cmp"), null);
    System.out.println("Command component: "+cmp);
    
    
    hi.add(new Label("Hi World"));
    hi.show();
}
 
Example #2
Source File: UIBuilder.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
private void initBackForm(Form f) {
    Vector formNavigationStack = baseFormNavigationStack;
    if(formNavigationStack != null && formNavigationStack.size() > 0) {
        setFormState(f, (Hashtable)formNavigationStack.elementAt(formNavigationStack.size() - 1));
        formNavigationStack.removeElementAt(formNavigationStack.size() - 1);
        if(formNavigationStack.size() > 0) {
            Hashtable previous = (Hashtable)formNavigationStack.elementAt(formNavigationStack.size() - 1);
            String commandAction = (String)previous.get(FORM_STATE_KEY_NAME);
            Command backCommand = createCommandImpl(getBackCommandText((String)previous.get(FORM_STATE_KEY_TITLE)), null,
                    BACK_COMMAND_ID, commandAction, true, "");
            setBackCommand(f, backCommand);
            
            // trigger listener creation if this is the only command in the form
            getFormListenerInstance(f, null);

            backCommand.putClientProperty(COMMAND_ARGUMENTS, "");
            backCommand.putClientProperty(COMMAND_ACTION, commandAction);
        }
    }
}
 
Example #3
Source File: UIBuilder.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
private void processCommandImpl(ActionEvent ev, Command cmd) {
    processCommand(ev, cmd);
    if(ev.isConsumed()) {
        return;
    }
    if(globalCommandListeners != null) {
        globalCommandListeners.fireActionEvent(ev);
        if(ev.isConsumed()) {
            return;
        }
    }

    if(localCommandListeners != null) {
        Form f = Display.getInstance().getCurrent();
        EventDispatcher e = (EventDispatcher)localCommandListeners.get(f.getName());
        if(e != null) {
            e.fireActionEvent(ev);
        }
    }
}
 
Example #4
Source File: Log.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Places a form with the log as a TextArea on the screen, this method can
 * be attached to appear at a given time or using a fixed global key. Using
 * this method might cause a problem with further log output
 * @deprecated this method is an outdated method that's no longer supported
 */
public static void showLog() {
    try {
        String text = getLogContent();
        TextArea area = new TextArea(text, 5, 20);
        Form f = new Form("Log");
        f.setScrollable(false);
        final Form current = Display.getInstance().getCurrent();
        Command back = new Command("Back") {
            public void actionPerformed(ActionEvent ev) {
                current.show();
            }
        };
        f.addCommand(back);
        f.setBackCommand(back);
        f.setLayout(new BorderLayout());
        f.addComponent(BorderLayout.CENTER, area);
        f.show();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
 
Example #5
Source File: Progress.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Binds the progress UI to the completion of this request
 *
 * @param title the title of the progress dialog
 * @param request the network request pending
 * @param showPercentage shows percentage on the progress bar
 */
public Progress(String title, ConnectionRequest request, boolean showPercentage) {
    super(title);
    this.request = request;
    SliderBridge b = new SliderBridge(request);
    b.setRenderPercentageOnTop(showPercentage);
    b.setRenderValueOnTop(true);
    setLayout(new BoxLayout(BoxLayout.Y_AXIS));
    addComponent(b);
    Command cancel = new Command(UIManager.getInstance().localize("cancel", "Cancel"));
    if(Display.getInstance().isTouchScreenDevice() || getSoftButtonCount() < 2) {
        // if this is a touch screen device or a blackberry use a centered button
        Button btn = new Button(cancel);
        Container cnt = new Container(new FlowLayout(CENTER));
        cnt.addComponent(btn);
        addComponent(cnt);
    } else {
        // otherwise use a command
        addCommand(cancel);
    }
    setDisposeWhenPointerOutOfBounds(false);
    setAutoDispose(false);
    NetworkManager.getInstance().addProgressListener(this);
}
 
Example #6
Source File: Progress.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
protected void actionCommand(Command cmd) {
    if(Display.getInstance().isTouchScreenDevice() || getSoftButtonCount() < 2) {
        for(int iter = 0 ; iter < getComponentCount() ; iter++) {
            Component c = getComponentAt(iter);
            if(c instanceof Button) {
                c.setEnabled(false);
            }
        }
    } else {
        removeAllCommands();
    }
    // cancel was pressed
    request.kill();
    dispose();
}
 
Example #7
Source File: WebSocketsSample.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
void showLogin() {
    Form f = new Form("Login");
    f.addComponent(new Label("Name: "));
    final TextField nameField = new TextField();
    f.addComponent(nameField);
    f.addComponent(new Button(new Command("Login"){ 

        @Override
        public void actionPerformed(ActionEvent evt) {
            System.out.println("Hello");
            if (sock.getReadyState() == WebSocketState.OPEN) {
                System.out.println("Open");
                sock.send(nameField.getText());
                showChat();
            } else {
                System.out.println("Closed");
                Dialog.show("Dialog", "The socket is not open: "+sock.getReadyState(), "OK", null);
                sock.reconnect();
            }
        }
           
    }));
    f.show();
}
 
Example #8
Source File: ToolbarRTLTest.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
public void start() {
    if(current != null){
        current.show();
        return;
    }
    Form hi = new Form("Hi World", BoxLayout.y());
    Toolbar tb = new Toolbar();
    hi.setToolbar(tb);
    tb.addCommandToLeftSideMenu(new Command("Test") {;
        public void actionPerformed(ActionEvent e) {
            System.out.println("Action clicked");
        }
    });
    hi.add(new Label("Hi World"));
    hi.show();
}
 
Example #9
Source File: JailbreakDetectionSample.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
public void start() {
    if(current != null){
        current.show();
        return;
    }
    Form hi = new Form("Jailbreak Detection", BoxLayout.y());
    Button detect = new Button("Detect Jailbreak");
    detect.addActionListener(evt->{
        if (JailbreakDetect.isJailbreakDetectionSupported()) {
            if (JailbreakDetect.isJailbroken()) {
                Dialog.show("Jailbroken","This device is jailbroken", new Command("OK") );
            } else {
                Dialog.show("Not Jailbroken", "Probably not jailbroken.  But can't be 100% sure.", new Command("OK"));
            }
        } else {
            Dialog.show("No Idea", "No support for jailbreak detection on this device.", new Command("OK"));
        }
    });
    hi.add(detect);
    hi.show();
}
 
Example #10
Source File: BlackBerryCanvas.java    From CodenameOne with GNU General Public License v2.0 6 votes vote down vote up
public Menu getMenu(int val) {
    if (Display.getInstance().getCommandBehavior() == Display.COMMAND_BEHAVIOR_NATIVE) {
        m = new Menu();
        if(commands != null){
            for (int iter = 0; iter < commands.size(); iter++) {
                final Command cmd = (Command) commands.elementAt(iter);
                String txt = UIManager.getInstance().localize(cmd.getCommandName(), cmd.getCommandName());
                MenuItem i = new MenuItem(txt, iter, iter) {
                    public void run() {
                        Display.getInstance().callSerially(new Runnable() {
                            public void run() {
                                impl.getCurrentForm().dispatchCommand(cmd, new ActionEvent(cmd));
                            }
                        });
                    }
                };
                m.add(i);
            }
        }
        return m;
    }
    return super.getMenu(val);
}
 
Example #11
Source File: GoogleLoginSample.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
public void showContactsForm(UserData data) {
    Form f = new Form("Contact Info");
    f.setToolbar(new Toolbar());
    f.getToolbar().setTitle("Contact Info");
    Form prev = CN.getCurrentForm();
    if (prev != null) {
        f.getToolbar().setBackCommand(new Command("Back") {
            public void actionPerformed(ActionEvent evt) {
                prev.show();
            }
            
        });
    }
    f.add(new Label("You are logged in as "+fullName));
    
    Button logout = new Button("Log out");
    logout.addActionListener(e->{
        GoogleConnect.getInstance().doLogout();
        Preferences.set(tokenPrefix + "tokenExpires", -1);
        Preferences.set(tokenPrefix + "token", (String)null);
        showLoginForm();
    });
    f.add(logout);
    f.show();
    
    
}
 
Example #12
Source File: UserForm.java    From codenameone-demos with GNU General Public License v2.0 5 votes vote down vote up
public UserForm(String name, EncodedImage placeHolder, String imageURL) {
    this.name = name;
    this.imageURL = imageURL;
    setTitle("Welcome!");
    setLayout(new BorderLayout());
    
    Label icon = new Label(placeHolder);
    icon.setUIID("Picture");
    if(imageURL != null){
        icon.setIcon(URLImage.createToStorage(placeHolder, name, imageURL, null));
    }
    addComponent(BorderLayout.CENTER, icon);
    Label nameLbl = new Label(name);
    nameLbl.setUIID("Name");
    addComponent(BorderLayout.SOUTH, nameLbl);
    final Form current = Display.getInstance().getCurrent();
    Command back = new Command("Back"){

        @Override
        public void actionPerformed(ActionEvent evt) {
            current.showBack();;
        }

    };
    addCommand(back);
    setBackCommand(back);
    
}
 
Example #13
Source File: ActionEvent.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * If this event was sent as a result of a command action this method returns
 * that command
 * @return the command action that triggered the action event
 */
public Command getCommand() {
    if(source instanceof Command) {
        return (Command)source;
    }
    return null;
}
 
Example #14
Source File: UIBuilder.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Useful tool to refresh the current state of a form shown using show form
 * without pushing another instance to the back stack
 */
public void reloadForm() {
    Form currentForm = Display.getInstance().getCurrent();
    Command backCommand = currentForm.getBackCommand(); 
    Form newForm = (Form)createContainer(fetchResourceFile(), currentForm.getName());
    newForm.setSourceCommand(currentForm.getSourceCommand());
    if (backCommand != null) {
        setBackCommand(newForm, backCommand);

        // trigger listener creation if this is the only command in the form
        getFormListenerInstance(newForm, null);
        
        for(int iter = 0 ; iter < currentForm.getCommandCount() ; iter++) {
            if(backCommand == currentForm.getCommand(iter)) {
                newForm.addCommand(backCommand, newForm.getCommandCount());
                break;
            }
        }
    }
    
    beforeShow(newForm);
    Transition tin = newForm.getTransitionInAnimator();
    Transition tout = newForm.getTransitionOutAnimator();
    currentForm.setTransitionInAnimator(CommonTransitions.createEmpty());
    currentForm.setTransitionOutAnimator(CommonTransitions.createEmpty());
    newForm.setTransitionInAnimator(CommonTransitions.createEmpty());
    newForm.setTransitionOutAnimator(CommonTransitions.createEmpty());
    newForm.layoutContainer();
    newForm.show();
    postShowImpl(newForm);
    newForm.setTransitionInAnimator(tin);
    newForm.setTransitionOutAnimator(tout);
}
 
Example #15
Source File: ActionEvent.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a new instance of ActionEvent for a command
 *
 * @param source element command
 * @param type the {@link Type } of the event
 * @param sourceComponent the triggering component
 * @param x the x position of the pointer event
 * @param y the y position of the pointer event
 */
public ActionEvent(Command source, Type type, Component sourceComponent, int x, int y) {
    this.source = source;
    this.sourceComponent = sourceComponent;
    this.keyEvent = x;
    this.y = y;
    this.trigger = type;
    if (type == Type.LongPointerPress) {
        longEvent = true;
    }
}
 
Example #16
Source File: HTMLForm.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a reset command associated with this form
 * 
 * @param value The reset button display name, if null or empty DEFAULT_RESET_TEXT will be assigned to it
 * @return The reset command
 */
Command createResetCommand(String value) {
    if ((value==null) || (value.equals(""))) {
        value=htmlC.getUIManager().localize("html.reset", HTMLForm.DEFAULT_RESET_TEXT);
    }
    return new NamedCommand(null,value, this, false);
}
 
Example #17
Source File: HTMLForm.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a submit command associated with this form
 *
 * @param name The submit command name (i.e. it's NAME attribute, or null if none specified)
 * @param value The submit button display name, if null or empty DEFAULT_SUBMIT_TEXT will be assigned to it
 * @return The reset command
 */
Command createSubmitCommand(String name, String value) {
    hasSubmitButton = true;
    if ((value==null) || (value.equals(""))) {
        value= htmlC.getUIManager().localize("html.submit", DEFAULT_SUBMIT_TEXT);
    }
    return new NamedCommand(name,value, this, true);
}
 
Example #18
Source File: TestUtils.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Executes the back command for the current form, similarly to pressing the back button
 */
public static void goBack() {
    if(verbose) {
        log("goBack()");
    }
    Form f = Display.getInstance().getCurrent();
    Command c = f.getBackCommand();
    assertBool(c != null, "The current form doesn't have a back command at this moment! for form name " + f.getName());
    f.dispatchCommand(c, new ActionEvent(c,ActionEvent.Type.Command));
    waitFor(20);
}
 
Example #19
Source File: PhotoShare.java    From codenameone-demos with GNU General Public License v2.0 5 votes vote down vote up
private Command createPictureCommand(final Container grid) {
    return new Command("Take Picture") {
        public void actionPerformed(ActionEvent ev) {
            String picture = Capture.capturePhoto(1024, -1);
            if(picture == null) {
                return;
            }
            MultipartRequest mp = new MultipartRequest() {
                private long key;
                @Override
                protected void readResponse(InputStream input) throws IOException {
                    DataInputStream di = new DataInputStream(input);
                    key = di.readLong();
                }

                @Override
                protected void postResponse() {
                    final Button btn = createImageButton(key, grid, imageList.getSize());
                    imageList.addImageId(key);
                    grid.addComponent(0, btn);
                    if(!animating) {
                        animating = true;
                        grid.animateLayoutAndWait(400);
                        animating = false;
                    }
                }
            };
            mp.setUrl(UPLOAD_URL);
            try {
                mp.addData("i", picture, "image/jpeg");
                mp.addArgument("p", "Data;More data");
                NetworkManager.getInstance().addToQueue(mp);
            } catch(IOException err) {
                err.printStackTrace();
            }
        }
    };
}
 
Example #20
Source File: TestUtils.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Executes a menu command with the given name
 * @param name the name of the command
 */
public static void clickMenuItem(String name) {
    if(verbose) {
        log("clickMenuItem(" + name + ")");
    }
    Form f = Display.getInstance().getCurrent();
    for(int iter = 0 ; iter < f.getCommandCount() ; iter++) {
        Command c = f.getCommand(iter);
        if(name.equals(c.getCommandName())) {
            f.dispatchCommand(c, new ActionEvent(c,ActionEvent.Type.Command));
            return;
        }
    }
    throw new RuntimeException("Command not found: " + name);
}
 
Example #21
Source File: TestUtils.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns all the command objects from the toolbar in the order of left, right, overflow &amp; sidemenu
 * @return the set of commands
 */
public static Command[] getToolbarCommands() {
    Form f = Display.getInstance().getCurrent();
    Toolbar tb = f.getToolbar();
    ArrayList<Command> result = new ArrayList<Command>();
    addAllCommands(tb.getLeftBarCommands(), result);
    addAllCommands(tb.getRightBarCommands(), result);
    addAllCommands(tb.getOverflowCommands(), result);
    addAllCommands(tb.getSideMenuCommands(), result);
    Command[] carr = new Command[result.size()];
    result.toArray(carr);
    return carr;
}
 
Example #22
Source File: TestUtils.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
private static void addAllCommands(Iterable<Command> cs, ArrayList<Command> result) {
    if(cs != null) {
        for(Command c : cs) {
            result.add(c);
        }
    }
}
 
Example #23
Source File: TestUtils.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Executes a command from the offset returned by {@link #getToolbarCommands()}
 * 
 * @param offset the offset of the command we want to execute
 */
public static void executeToolbarCommandAtOffset(final int offset) {
    Form f = Display.getInstance().getCurrent();
    if(!Display.getInstance().isEdt()) {
        Display.getInstance().callSerially(new Runnable() {
            public void run() {
                executeToolbarCommandAtOffset(offset);
            }
        });
        return;
    }
    Command cmd = getToolbarCommands()[offset];
    f.dispatchCommand(cmd, new ActionEvent(cmd));
}
 
Example #24
Source File: DefaultCrashReporter.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void exception(Throwable t) {
    Preferences.set("$CN1_pendingCrash", true);
    if(promptUser) {
        Dialog error = new Dialog("Error");
        error.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
        TextArea txt = new TextArea(errorText);
        txt.setEditable(false);
        txt.setUIID("DialogBody");
        error.addComponent(txt);
        CheckBox cb = new CheckBox(checkboxText);
        cb.setUIID("DialogBody");
        error.addComponent(cb);
        Container grid = new Container(new GridLayout(1, 2));
        error.addComponent(grid);
        Command ok = new Command(sendButtonText);
        Command dont = new Command(dontSendButtonText);
        Button send = new Button(ok);
        Button dontSend = new Button(dont);
        grid.addComponent(send);
        grid.addComponent(dontSend);
        Command result = error.showPacked(BorderLayout.CENTER, true);
        if(result == dont) {
            if(cb.isSelected()) {
                Preferences.set("$CN1_crashBlocked", true);
            }
            Preferences.set("$CN1_pendingCrash", false);
            return;
        } else {
            if(cb.isSelected()) {
                Preferences.set("$CN1_prompt", false);
            }
        }
    }
    Log.sendLog();
    Preferences.set("$CN1_pendingCrash", false);
}
 
Example #25
Source File: WebSocketsSample.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
void showChat() {
    Form f= new Form("Chat");
    f.setLayout(new BorderLayout());
    
    Container south = new Container();
    final TextField tf = new TextField();
    Button send = new Button(new Command("Send") {

        @Override
        public void actionPerformed(ActionEvent evt) {
            if (sock.getReadyState() == WebSocketState.OPEN) {
                sock.send(tf.getText());
                tf.setText("");
            } else {
                Dialog.show("", "The socket is not open", "OK", null);
                showLogin();
            }
            
        }
         
    });
    
    chatContainer = new Container();
    chatContainer.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
    
    south.addComponent(tf);
    south.addComponent(send);
    f.addComponent(BorderLayout.SOUTH, south);
    f.addComponent(BorderLayout.CENTER, chatContainer);
    f.setFormBottomPaddingEditingMode(true);
    f.show();
    
}
 
Example #26
Source File: SpanMultiButton.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets the command for the component, it doesn't affe
 * 
 * @param c the command
 */
public void setCommand(Command c) {
    Image img = emblem.getIcon();
    emblem.setCommand(c);
    emblem.setIcon(img);
    emblem.setText("");
}
 
Example #27
Source File: MultiButton.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Sets the command for the component, it doesn't affe
 * 
 * @param c the command
 */
public void setCommand(Command c) {
    Image img = emblem.getIcon();
    emblem.setCommand(c);
    emblem.setIcon(img);
    emblem.setText("");
}
 
Example #28
Source File: UserForm.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
public UserForm(String name, EncodedImage placeHolder, String imageURL) {
    this.name = name;
    this.imageURL = imageURL;
    setTitle("Welcome!");
    setLayout(new BorderLayout());
    
    Label icon = new Label(placeHolder);
    icon.setUIID("Picture");
    if(imageURL != null){
        icon.setIcon(URLImage.createToStorage(placeHolder, name, imageURL, null));
    }
    addComponent(BorderLayout.CENTER, icon);
    Label nameLbl = new Label(name);
    nameLbl.setUIID("Name");
    addComponent(BorderLayout.SOUTH, nameLbl);
    final Form current = Display.getInstance().getCurrent();
    Command back = new Command("Back"){

        @Override
        public void actionPerformed(ActionEvent evt) {
            current.showBack();;
        }

    };
    addCommand(back);
    setBackCommand(back);
    
}
 
Example #29
Source File: TestComponent.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
private void testNestedScrollingLabels() {
    int w = Display.getInstance().getDisplayWidth();
    int h = Display.getInstance().getDisplayHeight();
    Form f = new Form("Scrolling Labels");
    Toolbar tb = new Toolbar();
    f.setToolbar(tb);
    final Form backForm = Display.getInstance().getCurrent();
    tb.addCommandToSideMenu(new Command("Back") {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (backForm != null) {
                backForm.showBack();
            }
        }
    });
    f.setTitle("Scrolling Labels");
    Container cnt = new Container(BoxLayout.y());
    cnt.setScrollableY(true);
    for (String l : new String[]{"Red", "Green", "Blue", "Orange", "Indigo"}) {
        for (int i=0; i<20; i++) {
            cnt.add(l+i);
        }
    }

    f.setLayout(new BorderLayout());
    f.add(BorderLayout.CENTER, LayeredLayout.encloseIn(new Button("Press me"), BorderLayout.center(BorderLayout.center(cnt))));
    f.show();

    TestUtils.waitForFormTitle("Scrolling Labels", 2000);
    Component res = f.getComponentAt(w/2, h/2);
    assertTrue(res == cnt || res.getParent() == cnt, "getComponentAt(x,y) should return scrollable container on top of button when in layered pane.");

}
 
Example #30
Source File: TestComponent.java    From CodenameOne with GNU General Public License v2.0 5 votes vote down vote up
private void findCommandComponent() {
    log("Testing findCommandComponent()");
    Form f = new Form();
    Toolbar tb = new Toolbar();
    f.setToolbar(tb);
    Command cmd = tb.addMaterialCommandToLeftBar(null, FontImage.MATERIAL_3D_ROTATION, 4.5f, e-> {

    });

    Component res = tb.findCommandComponent(cmd);

    TestUtils.assertTrue(res != null, "Could not find command component added to left bar.");

}