Search code examples
javatoolbarcodenameoneinfinite

Infinite Rotation Command (or button) in toolbar in Codename One


I'd like to 'infinite' rotate on of my Commands (the refresh Command) in the Codename One Toolbar (until loading is done, then I want to stop rotation, but the image still has to be visible). Can I change the icon so it will start rotation? How can I achieve this result?

The rotating icon should not be clickable when rotating, but that should not be that hard to implement.


Solution

  • You can use Toolbar API and a little bit of hack. I created the methods below to do that:

    private void showTitleProgress(Toolbar t) {
        int pos = t.getComponentCount() - 1; //If you have a command on the left like back command
        //int pos = t.getComponentCount(); //If you don't have a command on the left like back command
        InfiniteProgress ip = new InfiniteProgress();
        ip.setAnimation(YourProgressImage);
        ip.setUIID("icon");
        Container contIp = FlowLayout.encloseCenterMiddle(ip);
    
        Component.setSameWidth(t.getComponentAt(pos), contIp);
        Component.setSameHeight(t.getComponentAt(pos), contIp);
        t.replaceAndWait(t.getComponentAt(pos), contIp, null);
        t.revalidate();
    }
    
    private void hideTitleProgress(Toolbar t, Command cmd) {
        int pos = t.getComponentCount() - 1; //If you have a command on the left like back command
        //int pos = t.getComponentCount(); //If you don't have a command on the left like back command
        Button cmdButton = new Button(cmd.getIcon());
        cmdButton.setUIID("TitleCommand");
        cmdButton.setCommand(cmd);
        t.replaceAndWait(t.getComponentAt(pos), cmdButton, null);
        t.getComponentForm().revalidate();
    }
    

    Use it with Toolbar API and your form like this:

    private Command myCommand = new Command("");
    Form f = new Form("Test form");
    Toolbar t = new Toolbar();
    f.setToolbar(t);
    
    Command back = new Command("Back") {
    
        @Override
        public void actionPerformed(ActionEvent evt) {
           //Do stuff
        }
    };
    back.putClientProperty("uiid", "BackCommand");
    f.setBackCommand(back);
    t.addCommandToLeftBar(back);
    
    myCommand = new Command(YourProgressImage) {
    
        @Override
        public void actionPerformed(ActionEvent evt) {
            //To show the progress when some actions are being performed 
            showTitleProgress(t);
            //When you're done, discard the progress and restore your command
            hideTitleProgress(t, myCommand);
        }
    }
    myCommand.putClientProperty("TitleCommand", true);
    t.addCommandToRightBar(myCommand);
    f.show();