Search in sources :

Example 41 with Component

use of com.codename1.ui.Component in project CodenameOne by codenameone.

the class UIBuilderOverride method createInstance.

/**
 * Create a component instance from XML
 */
public Container createInstance(ComponentEntry root, EditableResources res) {
    ArrayList<Runnable> postCreateTasks = new ArrayList<Runnable>();
    Container c = (Container) createInstance(root, res, null, null, postCreateTasks);
    // execute tasks that must have the entire hierarchy constructed in order to work
    for (Runnable r : postCreateTasks) {
        r.run();
    }
    return c;
}
Also used : Container(com.codename1.ui.Container) ArrayList(java.util.ArrayList)

Example 42 with Component

use of com.codename1.ui.Component in project CodenameOne by codenameone.

the class UIBuilderOverride method createInstance.

/**
 * Create a component instance from XML
 */
private Component createInstance(final ComponentEntry root, final EditableResources res, Container rootCnt, final Container parentContainer, final ArrayList<Runnable> postCreateTasks) {
    try {
        final Component c = createComponentType(root.getType());
        if (rootCnt == null) {
            rootCnt = (Container) c;
        }
        final Container rootContainer = rootCnt;
        if (root.getBaseForm() != null) {
            c.putClientProperty("%base_form%", root.getBaseForm());
        }
        c.putClientProperty(TYPE_KEY, root.getType());
        c.setName(root.getName());
        String clientProps = root.getClientProperties();
        if (clientProps != null && clientProps.length() > 0) {
            String[] props = clientProps.split(",");
            StringBuilder b = new StringBuilder();
            for (String p : props) {
                String[] keyVal = p.split("=");
                c.putClientProperty(keyVal[0], keyVal[1]);
                if (b.length() > 0) {
                    b.append(",");
                }
                b.append(keyVal[0]);
            }
            c.putClientProperty("cn1$Properties", b.toString());
        }
        rootContainer.putClientProperty("%" + root.getName() + "%", c);
        // layout must be first since we might need to rely on it later on with things such as constraints
        if (root.getLayout() != null) {
            modifyingProperty(c, PROPERTY_LAYOUT);
            Layout l;
            if (root.getLayout().equals("BorderLayout")) {
                l = new BorderLayout();
                if (root.isBorderLayoutAbsoluteCenter() != null) {
                    ((BorderLayout) l).setAbsoluteCenter(root.isBorderLayoutAbsoluteCenter().booleanValue());
                }
                if (root.getBorderLayoutSwapCenter() != null) {
                    ((BorderLayout) l).defineLandscapeSwap(BorderLayout.CENTER, root.getBorderLayoutSwapCenter());
                }
                if (root.getBorderLayoutSwapNorth() != null) {
                    ((BorderLayout) l).defineLandscapeSwap(BorderLayout.NORTH, root.getBorderLayoutSwapNorth());
                }
                if (root.getBorderLayoutSwapSouth() != null) {
                    ((BorderLayout) l).defineLandscapeSwap(BorderLayout.SOUTH, root.getBorderLayoutSwapSouth());
                }
                if (root.getBorderLayoutSwapEast() != null) {
                    ((BorderLayout) l).defineLandscapeSwap(BorderLayout.EAST, root.getBorderLayoutSwapEast());
                }
                if (root.getBorderLayoutSwapWest() != null) {
                    ((BorderLayout) l).defineLandscapeSwap(BorderLayout.WEST, root.getBorderLayoutSwapWest());
                }
            } else {
                if (root.getLayout().equals("FlowLayout")) {
                    l = new FlowLayout();
                    ((FlowLayout) l).setFillRows(root.isFlowLayoutFillRows());
                    ((FlowLayout) l).setAlign(root.getFlowLayoutAlign());
                    ((FlowLayout) l).setValign(root.getFlowLayoutValign());
                } else {
                    if (root.getLayout().equals("GridLayout")) {
                        l = new GridLayout(root.getGridLayoutRows().intValue(), root.getGridLayoutColumns().intValue());
                    } else {
                        if (root.getLayout().equals("BoxLayout")) {
                            if (root.getBoxLayoutAxis().equals("X")) {
                                l = new BoxLayout(BoxLayout.X_AXIS);
                            } else {
                                l = new BoxLayout(BoxLayout.Y_AXIS);
                            }
                        } else {
                            if (root.getLayout().equals("TableLayout")) {
                                l = new TableLayout(root.getTableLayoutRows(), root.getTableLayoutColumns());
                            } else {
                                l = new LayeredLayout();
                            }
                        }
                    }
                }
            }
            ((Container) c).setLayout(l);
        }
        if (parentContainer != null && root.getLayoutConstraint() != null) {
            modifyingProperty(c, PROPERTY_LAYOUT_CONSTRAINT);
            if (parentContainer.getLayout() instanceof BorderLayout) {
                c.putClientProperty("layoutConstraint", root.getLayoutConstraint().getValue());
            } else {
                TableLayout tl = (TableLayout) parentContainer.getLayout();
                TableLayout.Constraint con = tl.createConstraint(root.getLayoutConstraint().getRow(), root.getLayoutConstraint().getColumn());
                con.setHeightPercentage(root.getLayoutConstraint().getHeight());
                con.setWidthPercentage(root.getLayoutConstraint().getWidth());
                con.setHorizontalAlign(root.getLayoutConstraint().getAlign());
                con.setHorizontalSpan(root.getLayoutConstraint().getSpanHorizontal());
                con.setVerticalAlign(root.getLayoutConstraint().getValign());
                con.setVerticalSpan(root.getLayoutConstraint().getSpanVertical());
                c.putClientProperty("layoutConstraint", con);
            }
        }
        if (root.getEmbed() != null && root.getEmbed().length() > 0) {
            modifyingProperty(c, PROPERTY_EMBED);
            rootContainer.putClientProperty(EMBEDDED_FORM_FLAG, "");
            ((EmbeddedContainer) c).setEmbed(root.getEmbed());
            Container embed = createContainer(res, root.getEmbed(), (EmbeddedContainer) c);
            if (embed != null) {
                if (embed instanceof Form) {
                    embed = formToContainer((Form) embed);
                }
                ((EmbeddedContainer) c).addComponent(BorderLayout.CENTER, embed);
                // this isn't exactly the "right thing" but its the best we can do to make all
                // use cases work
                beforeShowContainer(embed);
                postShowContainer(embed);
            }
        }
        if (root.isToggle() != null) {
            modifyingProperty(c, PROPERTY_TOGGLE_BUTTON);
            ((Button) c).setToggle(root.isToggle().booleanValue());
        }
        if (root.getGroup() != null) {
            modifyingProperty(c, PROPERTY_RADIO_GROUP);
            ((RadioButton) c).setGroup(root.getGroup());
        }
        if (root.isSelected() != null) {
            modifyingProperty(c, PROPERTY_SELECTED);
            if (c instanceof RadioButton) {
                ((RadioButton) c).setSelected(root.isSelected().booleanValue());
            } else {
                ((CheckBox) c).setSelected(root.isSelected().booleanValue());
            }
        }
        if (root.isScrollableX() != null) {
            modifyingProperty(c, PROPERTY_SCROLLABLE_X);
            ((Container) c).setScrollableX(root.isScrollableX().booleanValue());
        }
        if (root.isScrollableY() != null) {
            modifyingProperty(c, PROPERTY_SCROLLABLE_Y);
            ((Container) c).setScrollableY(root.isScrollableY().booleanValue());
        }
        if (root.isTensileDragEnabled() != null) {
            modifyingProperty(c, PROPERTY_TENSILE_DRAG_ENABLED);
            c.setTensileDragEnabled(root.isTensileDragEnabled().booleanValue());
        }
        if (root.isTactileTouch() != null) {
            modifyingProperty(c, PROPERTY_TACTILE_TOUCH);
            c.setTactileTouch(root.isTactileTouch().booleanValue());
        }
        if (root.isSnapToGrid() != null) {
            modifyingProperty(c, PROPERTY_SNAP_TO_GRID);
            c.setSnapToGrid(root.isSnapToGrid().booleanValue());
        }
        if (root.isFlatten() != null) {
            modifyingProperty(c, PROPERTY_FLATTEN);
            c.setFlatten(root.isFlatten().booleanValue());
        }
        if (root.getText() != null) {
            modifyingProperty(c, PROPERTY_TEXT);
            if (c instanceof Label) {
                ((Label) c).setText(root.getText());
            } else {
                ((TextArea) c).setText(root.getText());
            }
        }
        if (root.getMaxSize() != null) {
            modifyingProperty(c, PROPERTY_TEXT_MAX_LENGTH);
            ((TextArea) c).setMaxSize(root.getMaxSize().intValue());
        }
        if (root.getConstraint() != null) {
            modifyingProperty(c, PROPERTY_TEXT_CONSTRAINT);
            ((TextArea) c).setConstraint(root.getConstraint().intValue());
        }
        if (root.getAlignment() != null) {
            modifyingProperty(c, PROPERTY_ALIGNMENT);
            if (c instanceof Label) {
                ((Label) c).setAlignment(root.getAlignment().intValue());
            } else {
                ((TextArea) c).setAlignment(root.getAlignment().intValue());
            }
        }
        if (root.isGrowByContent() != null) {
            modifyingProperty(c, PROPERTY_TEXT_AREA_GROW);
            ((TextArea) c).setGrowByContent(root.isGrowByContent().booleanValue());
        }
        if (root.getTabPlacement() != null) {
            modifyingProperty(c, PROPERTY_TAB_PLACEMENT);
            ((Tabs) c).setTabPlacement(root.getTabPlacement().intValue());
        }
        if (root.getTabTextPosition() != null) {
            modifyingProperty(c, PROPERTY_TAB_TEXT_POSITION);
            ((Tabs) c).setTabTextPosition(root.getTabTextPosition().intValue());
        }
        if (root.getUiid() != null) {
            modifyingProperty(c, PROPERTY_UIID);
            c.setUIID(root.getUiid());
        }
        if (root.getDialogUIID() != null) {
            modifyingProperty(c, PROPERTY_DIALOG_UIID);
            ((Dialog) c).setDialogUIID(root.getDialogUIID());
        }
        if (root.isDisposeWhenPointerOutOfBounds() != null) {
            modifyingProperty(c, PROPERTY_DISPOSE_WHEN_POINTER_OUT);
            ((Dialog) c).setDisposeWhenPointerOutOfBounds(root.isDisposeWhenPointerOutOfBounds());
        }
        if (root.getCloudBoundProperty() != null) {
            modifyingProperty(c, PROPERTY_CLOUD_BOUND_PROPERTY);
            c.setCloudBoundProperty(root.getCloudBoundProperty());
        }
        if (root.getCloudDestinationProperty() != null) {
            modifyingProperty(c, PROPERTY_CLOUD_DESTINATION_PROPERTY);
            c.setCloudDestinationProperty(root.getCloudDestinationProperty());
        }
        if (root.getDialogPosition() != null && root.getDialogPosition().length() > 0) {
            modifyingProperty(c, PROPERTY_DIALOG_POSITION);
            ((Dialog) c).setDialogPosition(root.getDialogPosition());
        }
        if (root.isFocusable() != null) {
            modifyingProperty(c, PROPERTY_FOCUSABLE);
            c.setFocusable(root.isFocusable().booleanValue());
        }
        if (root.isEnabled() != null) {
            modifyingProperty(c, PROPERTY_ENABLED);
            c.setEnabled(root.isEnabled().booleanValue());
        }
        if (root.isScrollVisible() != null) {
            modifyingProperty(c, PROPERTY_SCROLL_VISIBLE);
            c.setScrollVisible(root.isScrollVisible().booleanValue());
        }
        if (root.getIcon() != null) {
            modifyingProperty(c, PROPERTY_ICON);
            ((Label) c).setIcon(res.getImage(root.getIcon()));
        }
        if (root.getRolloverIcon() != null) {
            modifyingProperty(c, PROPERTY_ROLLOVER_ICON);
            ((Button) c).setRolloverIcon(res.getImage(root.getRolloverIcon()));
        }
        if (root.getPressedIcon() != null) {
            modifyingProperty(c, PROPERTY_PRESSED_ICON);
            ((Button) c).setPressedIcon(res.getImage(root.getPressedIcon()));
        }
        if (root.getDisabledIcon() != null) {
            modifyingProperty(c, PROPERTY_DISABLED_ICON);
            ((Button) c).setDisabledIcon(res.getImage(root.getDisabledIcon()));
        }
        if (root.getGap() != null) {
            modifyingProperty(c, PROPERTY_GAP);
            ((Label) c).setGap(root.getGap().intValue());
        }
        if (root.getVerticalAlignment() != null) {
            modifyingProperty(c, PROPERTY_VERTICAL_ALIGNMENT);
            if (c instanceof Label) {
                ((Label) c).setVerticalAlignment(root.getVerticalAlignment().intValue());
            } else {
                ((TextArea) c).setVerticalAlignment(root.getVerticalAlignment().intValue());
            }
        }
        if (root.getTextPosition() != null) {
            modifyingProperty(c, PROPERTY_TEXT_POSITION);
            ((Label) c).setTextPosition(root.getTextPosition().intValue());
        }
        if (root.getTitle() != null) {
            modifyingProperty(c, PROPERTY_TITLE);
            ((Form) c).setTitle(root.getTitle());
        }
        // components should be added when we've set everything else up
        if (root.getComponent() != null) {
            modifyingProperty(c, PROPERTY_COMPONENTS);
            if (c instanceof Tabs) {
                for (ComponentEntry ent : root.getComponent()) {
                    Component newCmp = createInstance(ent, res, rootContainer, (Container) c, postCreateTasks);
                    ((Tabs) c).addTab(ent.getTabTitle(), newCmp);
                }
            } else {
                for (ComponentEntry ent : root.getComponent()) {
                    Component newCmp = createInstance(ent, res, rootContainer, (Container) c, postCreateTasks);
                    Object cons = newCmp.getClientProperty("layoutConstraint");
                    if (cons != null) {
                        modifyingProperty(c, PROPERTY_LAYOUT_CONSTRAINT);
                        ((Container) c).addComponent(cons, newCmp);
                    } else {
                        ((Container) c).addComponent(newCmp);
                    }
                }
            }
        }
        if (root.getColumns() != null) {
            modifyingProperty(c, PROPERTY_COLUMNS);
            ((TextArea) c).setColumns(root.getColumns().intValue());
        }
        if (root.getRows() != null) {
            modifyingProperty(c, PROPERTY_ROWS);
            ((TextArea) c).setRows(root.getRows().intValue());
        }
        if (root.getHint() != null) {
            modifyingProperty(c, PROPERTY_HINT);
            if (c instanceof List) {
                ((List) c).setHint(root.getHint());
            } else {
                ((TextArea) c).setHint(root.getHint());
            }
        }
        if (root.getHintIcon() != null) {
            modifyingProperty(c, PROPERTY_HINT_ICON);
            if (c instanceof List) {
                ((List) c).setHintIcon(res.getImage(root.getHint()));
            } else {
                ((TextArea) c).setHintIcon(res.getImage(root.getHint()));
            }
        }
        if (root.getItemGap() != null) {
            modifyingProperty(c, PROPERTY_ITEM_GAP);
            ((List) c).setItemGap(root.getItemGap().intValue());
        }
        if (root.getFixedSelection() != null) {
            modifyingProperty(c, PROPERTY_LIST_FIXED);
            ((List) c).setFixedSelection(root.getFixedSelection().intValue());
        }
        if (root.getOrientation() != null) {
            modifyingProperty(c, PROPERTY_LIST_ORIENTATION);
            ((List) c).setOrientation(root.getOrientation().intValue());
        }
        if (c instanceof com.codename1.ui.List && !(c instanceof com.codename1.components.RSSReader)) {
            modifyingProperty(c, PROPERTY_LIST_ITEMS);
            if (root.getStringItem() != null && root.getStringItem().length > 0) {
                String[] arr = new String[root.getStringItem().length];
                for (int iter = 0; iter < arr.length; iter++) {
                    arr[iter] = root.getStringItem()[iter].getValue();
                }
                ((List) c).setModel(new DefaultListModel<String>(arr));
            } else {
                if (root.getMapItems() != null && root.getMapItems().length > 0) {
                    Hashtable[] arr = new Hashtable[root.getMapItems().length];
                    for (int iter = 0; iter < arr.length; iter++) {
                        arr[iter] = new Hashtable();
                        if (root.getMapItems()[iter].getActionItem() != null) {
                            for (Val v : root.getMapItems()[iter].getActionItem()) {
                                Command cmd = createCommandImpl((String) v.getValue(), null, -1, v.getValue(), false, "");
                                cmd.putClientProperty(COMMAND_ACTION, (String) v.getValue());
                                arr[iter].put(v.getKey(), cmd);
                            }
                        }
                        if (root.getMapItems()[iter].getStringItem() != null) {
                            for (Val v : root.getMapItems()[iter].getActionItem()) {
                                arr[iter].put(v.getKey(), v.getValue());
                            }
                        }
                        if (root.getMapItems()[iter].getImageItem() != null) {
                            for (Val v : root.getMapItems()[iter].getActionItem()) {
                                arr[iter].put(v.getKey(), res.getImage(v.getValue()));
                            }
                        }
                    }
                    ((List) c).setModel(new DefaultListModel<java.util.Map>(arr));
                }
            }
        }
        if (root.getSelectedRenderer() != null) {
            modifyingProperty(c, PROPERTY_LIST_RENDERER);
            GenericListCellRenderer g;
            if (root.getSelectedRendererEven() == null) {
                Component selected = createContainer(res, root.getSelectedRenderer());
                Component unselected = createContainer(res, root.getUnselectedRenderer());
                g = new GenericListCellRenderer(selected, unselected);
                g.setFisheye(!root.getSelectedRenderer().equals(root.getUnselectedRenderer()));
            } else {
                Component selected = createContainer(res, root.getSelectedRenderer());
                Component unselected = createContainer(res, root.getUnselectedRenderer());
                Component even = createContainer(res, root.getSelectedRendererEven());
                Component evenU = createContainer(res, root.getUnselectedRendererEven());
                g = new GenericListCellRenderer(selected, unselected, even, evenU);
                g.setFisheye(!root.getSelectedRenderer().equals(root.getUnselectedRenderer()));
            }
            if (c instanceof ContainerList) {
                ((ContainerList) c).setRenderer(g);
            } else {
                ((List) c).setRenderer(g);
            }
        }
        if (root.getNextForm() != null && root.getNextForm().length() > 0) {
            modifyingProperty(c, PROPERTY_NEXT_FORM);
            setNextForm(c, root.getNextForm(), res, rootContainer);
        }
        if (root.getCommand() != null) {
            modifyingProperty(c, PROPERTY_COMMANDS);
            for (CommandEntry cmd : root.getCommand()) {
                Command currentCommand = createCommandImpl(cmd.getName(), res.getImage(cmd.getIcon()), cmd.getId(), cmd.getAction(), cmd.isBackCommand(), cmd.getArgument());
                if (cmd.getRolloverIcon() != null && cmd.getRolloverIcon().length() > 0) {
                    currentCommand.setRolloverIcon(res.getImage(cmd.getRolloverIcon()));
                }
                if (cmd.getPressedIcon() != null && cmd.getPressedIcon().length() > 0) {
                    currentCommand.setPressedIcon(res.getImage(cmd.getPressedIcon()));
                }
                if (cmd.getDisabledIcon() != null && cmd.getDisabledIcon().length() > 0) {
                    currentCommand.setDisabledIcon(res.getImage(cmd.getDisabledIcon()));
                }
                if (cmd.isBackCommand()) {
                    ((Form) c).setBackCommand(currentCommand);
                }
                ((Form) c).addCommand(currentCommand);
                currentCommand.putClientProperty(COMMAND_ARGUMENTS, cmd.getArgument());
                currentCommand.putClientProperty(COMMAND_ACTION, cmd.getAction());
            }
        }
        if (root.isCyclicFocus() != null) {
            modifyingProperty(c, PROPERTY_CYCLIC_FOCUS);
            ((Form) c).setCyclicFocus(root.isCyclicFocus().booleanValue());
        }
        if (root.isRtl() != null) {
            modifyingProperty(c, PROPERTY_RTL);
            c.setRTL(root.isRtl().booleanValue());
        }
        if (root.getThumbImage() != null) {
            modifyingProperty(c, PROPERTY_SLIDER_THUMB);
            ((Slider) c).setThumbImage(res.getImage(root.getThumbImage()));
        }
        if (root.isInfinite() != null) {
            modifyingProperty(c, PROPERTY_INFINITE);
            ((Slider) c).setInfinite(root.isInfinite().booleanValue());
        }
        if (root.getProgress() != null) {
            modifyingProperty(c, PROPERTY_PROGRESS);
            ((Slider) c).setProgress(root.getProgress().intValue());
        }
        if (root.isVertical() != null) {
            modifyingProperty(c, PROPERTY_VERTICAL);
            ((Slider) c).setVertical(root.isVertical().booleanValue());
        }
        if (root.isEditable() != null) {
            modifyingProperty(c, PROPERTY_EDITABLE);
            if (c instanceof TextArea) {
                ((TextArea) c).setEditable(root.isEditable().booleanValue());
            } else {
                ((Slider) c).setEditable(root.isEditable().booleanValue());
            }
        }
        if (root.getIncrements() != null) {
            modifyingProperty(c, PROPERTY_INCREMENTS);
            ((Slider) c).setIncrements(root.getIncrements().intValue());
        }
        if (root.isRenderPercentageOnTop() != null) {
            modifyingProperty(c, PROPERTY_RENDER_PERCENTAGE_ON_TOP);
            ((Slider) c).setRenderPercentageOnTop(root.isRenderPercentageOnTop().booleanValue());
        }
        if (root.getMaxValue() != null) {
            modifyingProperty(c, PROPERTY_MAX_VALUE);
            ((Slider) c).setMaxValue(root.getMaxValue().intValue());
        }
        if (root.getMinValue() != null) {
            modifyingProperty(c, PROPERTY_MIN_VALUE);
            ((Slider) c).setMinValue(root.getMinValue().intValue());
        }
        if (root.getCommandName() != null) {
            modifyingProperty(c, PROPERTY_COMMAND);
            postCreateTasks.add(new Runnable() {

                public void run() {
                    Command cmd = createCommandImpl(root.getCommandName(), res.getImage(root.getCommandIcon()), root.getCommandId().intValue(), root.getCommandAction(), root.isCommandBack().booleanValue(), root.getCommandArgument());
                    if (c instanceof Container) {
                        Button b = (Button) ((Container) c).getLeadComponent();
                        b.setCommand(cmd);
                        return;
                    }
                    ((Button) c).setCommand(cmd);
                }
            });
        }
        if (root.getLabelFor() != null) {
            modifyingProperty(c, PROPERTY_LABEL_FOR);
            postCreateTasks.add(new Runnable() {

                public void run() {
                    ((Label) c).setLabelForComponent((Label) findByName(root.getLabelFor(), rootContainer));
                }
            });
        }
        if (root.getLeadComponent() != null) {
            modifyingProperty(c, PROPERTY_LEAD_COMPONENT);
            postCreateTasks.add(new Runnable() {

                public void run() {
                    ((Container) c).setLeadComponent(findByName(root.getLeadComponent(), rootContainer));
                }
            });
        }
        if (root.getNextFocusUp() != null) {
            modifyingProperty(c, PROPERTY_NEXT_FOCUS_UP);
            postCreateTasks.add(new Runnable() {

                public void run() {
                    c.setNextFocusUp(findByName(root.getNextFocusUp(), rootContainer));
                }
            });
        }
        if (root.getNextFocusDown() != null) {
            modifyingProperty(c, PROPERTY_NEXT_FOCUS_DOWN);
            postCreateTasks.add(new Runnable() {

                public void run() {
                    c.setNextFocusDown(findByName(root.getNextFocusDown(), rootContainer));
                }
            });
        }
        if (root.getNextFocusLeft() != null) {
            modifyingProperty(c, PROPERTY_NEXT_FOCUS_LEFT);
            postCreateTasks.add(new Runnable() {

                public void run() {
                    c.setNextFocusLeft(findByName(root.getNextFocusLeft(), rootContainer));
                }
            });
        }
        if (root.getNextFocusRight() != null) {
            modifyingProperty(c, PROPERTY_NEXT_FOCUS_RIGHT);
            postCreateTasks.add(new Runnable() {

                public void run() {
                    c.setNextFocusRight(findByName(root.getNextFocusRight(), rootContainer));
                }
            });
        }
        // custom settings are always last after all other properties
        if (root.getCustom() != null && root.getCustom().length > 0) {
            modifyingProperty(c, PROPERTY_CUSTOM);
            for (Custom cust : root.getCustom()) {
                modifyingCustomProperty(c, cust.getName());
                Object value = null;
                Class customType = UserInterfaceEditor.getPropertyCustomType(c, cust.getName());
                if (customType.isArray()) {
                    if (customType == String[].class) {
                        if (cust.getStr() != null) {
                            String[] arr = new String[cust.getStr().length];
                            for (int iter = 0; iter < arr.length; iter++) {
                                arr[iter] = cust.getStr()[iter].getValue();
                            }
                            c.setPropertyValue(cust.getName(), arr);
                        } else {
                            c.setPropertyValue(cust.getName(), null);
                        }
                        continue;
                    }
                    if (customType == String[][].class) {
                        if (cust.getArr() != null) {
                            String[][] arr = new String[cust.getArr().length][];
                            for (int iter = 0; iter < arr.length; iter++) {
                                if (cust.getArr()[iter] != null && cust.getArr()[iter].getValue() != null) {
                                    arr[iter] = new String[cust.getArr()[iter].getValue().length];
                                    for (int inter = 0; inter < arr[iter].length; inter++) {
                                        arr[iter][inter] = cust.getArr()[iter].getValue()[inter].getValue();
                                    }
                                }
                            }
                            c.setPropertyValue(cust.getName(), arr);
                        } else {
                            c.setPropertyValue(cust.getName(), null);
                        }
                        continue;
                    }
                    if (customType == com.codename1.ui.Image[].class) {
                        if (cust.getStr() != null) {
                            com.codename1.ui.Image[] arr = new com.codename1.ui.Image[cust.getStr().length];
                            for (int iter = 0; iter < arr.length; iter++) {
                                arr[iter] = res.getImage(cust.getStr()[iter].getValue());
                            }
                            c.setPropertyValue(cust.getName(), arr);
                        } else {
                            c.setPropertyValue(cust.getName(), null);
                        }
                        continue;
                    }
                    if (customType == Object[].class) {
                        if (cust.getStringItem() != null) {
                            String[] arr = new String[cust.getStringItem().length];
                            for (int iter = 0; iter < arr.length; iter++) {
                                arr[iter] = cust.getStringItem()[iter].getValue();
                            }
                            c.setPropertyValue(cust.getName(), arr);
                            continue;
                        } else {
                            if (cust.getMapItems() != null) {
                                Hashtable[] arr = new Hashtable[cust.getMapItems().length];
                                for (int iter = 0; iter < arr.length; iter++) {
                                    arr[iter] = new Hashtable();
                                    if (cust.getMapItems()[iter].getActionItem() != null) {
                                        for (Val v : cust.getMapItems()[iter].getActionItem()) {
                                            Command cmd = createCommandImpl(v.getValue(), null, -1, v.getValue(), false, "");
                                            cmd.putClientProperty(COMMAND_ACTION, v.getValue());
                                            value = cmd;
                                            arr[iter].put(v.getKey(), cmd);
                                        }
                                    }
                                    if (cust.getMapItems()[iter].getStringItem() != null) {
                                        for (Val v : cust.getMapItems()[iter].getActionItem()) {
                                            arr[iter].put(v.getKey(), v.getValue());
                                        }
                                    }
                                    if (cust.getMapItems()[iter].getImageItem() != null) {
                                        for (Val v : cust.getMapItems()[iter].getActionItem()) {
                                            arr[iter].put(v.getKey(), res.getImage(v.getValue()));
                                        }
                                    }
                                }
                                c.setPropertyValue(cust.getName(), arr);
                                continue;
                            }
                        }
                        c.setPropertyValue(cust.getName(), null);
                        continue;
                    }
                }
                if (customType == String.class) {
                    c.setPropertyValue(cust.getName(), cust.getValue());
                    continue;
                }
                if (customType == Integer.class) {
                    if (cust.getValue() != null) {
                        c.setPropertyValue(cust.getName(), Integer.valueOf(cust.getValue()));
                    } else {
                        c.setPropertyValue(cust.getName(), null);
                    }
                    continue;
                }
                if (customType == Long.class) {
                    if (cust.getValue() != null) {
                        c.setPropertyValue(cust.getName(), Long.valueOf(cust.getValue()));
                    } else {
                        c.setPropertyValue(cust.getName(), null);
                    }
                    continue;
                }
                if (customType == Double.class) {
                    if (cust.getValue() != null) {
                        c.setPropertyValue(cust.getName(), Double.valueOf(cust.getValue()));
                    } else {
                        c.setPropertyValue(cust.getName(), null);
                    }
                    continue;
                }
                if (customType == Date.class) {
                    if (cust.getValue() != null) {
                        c.setPropertyValue(cust.getName(), new Date(Long.parseLong(cust.getValue())));
                    } else {
                        c.setPropertyValue(cust.getName(), null);
                    }
                    continue;
                }
                if (customType == Float.class) {
                    if (cust.getValue() != null) {
                        c.setPropertyValue(cust.getName(), Float.valueOf(cust.getValue()));
                    } else {
                        c.setPropertyValue(cust.getName(), null);
                    }
                    continue;
                }
                if (customType == Byte.class) {
                    if (cust.getValue() != null) {
                        c.setPropertyValue(cust.getName(), Byte.valueOf(cust.getValue()));
                    } else {
                        c.setPropertyValue(cust.getName(), null);
                    }
                    continue;
                }
                if (customType == Character.class) {
                    if (cust.getValue() != null && ((String) cust.getValue()).length() > 0) {
                        c.setPropertyValue(cust.getName(), new Character(((String) cust.getValue()).charAt(0)));
                    } else {
                        c.setPropertyValue(cust.getName(), null);
                    }
                    continue;
                }
                if (customType == Boolean.class) {
                    if (cust.getValue() != null) {
                        c.setPropertyValue(cust.getName(), Boolean.valueOf(cust.getValue()));
                    } else {
                        c.setPropertyValue(cust.getName(), null);
                    }
                    continue;
                }
                if (customType == com.codename1.ui.Image.class) {
                    if (cust.getValue() != null) {
                        c.setPropertyValue(cust.getName(), res.getImage(cust.getValue()));
                    } else {
                        c.setPropertyValue(cust.getName(), null);
                    }
                    continue;
                }
                if (customType == com.codename1.ui.Container.class) {
                    // resource might have been removed we need to fail gracefully
                    String[] uiNames = res.getUIResourceNames();
                    for (int iter = 0; iter < uiNames.length; iter++) {
                        if (uiNames[iter].equals(cust.getName())) {
                            c.setPropertyValue(cust.getName(), createContainer(res, cust.getName()));
                            continue;
                        }
                    }
                    c.setPropertyValue(cust.getName(), null);
                    continue;
                }
                if (customType == com.codename1.ui.list.CellRenderer.class) {
                    if (cust.getUnselectedRenderer() != null) {
                        GenericListCellRenderer g;
                        if (cust.getSelectedRendererEven() == null) {
                            Component selected = createContainer(res, cust.getSelectedRenderer());
                            Component unselected = createContainer(res, cust.getUnselectedRenderer());
                            g = new GenericListCellRenderer(selected, unselected);
                            g.setFisheye(!cust.getSelectedRenderer().equals(cust.getUnselectedRenderer()));
                        } else {
                            Component selected = createContainer(res, cust.getSelectedRenderer());
                            Component unselected = createContainer(res, cust.getUnselectedRenderer());
                            Component even = createContainer(res, cust.getSelectedRendererEven());
                            Component evenU = createContainer(res, cust.getUnselectedRendererEven());
                            g = new GenericListCellRenderer(selected, unselected, even, evenU);
                            g.setFisheye(!cust.getSelectedRenderer().equals(cust.getUnselectedRenderer()));
                        }
                        c.setPropertyValue(cust.getName(), g);
                        continue;
                    }
                    c.setPropertyValue(cust.getName(), null);
                    continue;
                }
            }
        }
        return c;
    } catch (Throwable t) {
        t.printStackTrace();
        JOptionPane.showMessageDialog(java.awt.Frame.getFrames()[0], "Error creating component: " + root.getName() + "\n" + t.toString() + "\ntrying to recover...", "Error", JOptionPane.ERROR_MESSAGE);
        return null;
    }
}
Also used : Val(com.codename1.ui.util.xml.Val) TextArea(com.codename1.ui.TextArea) Label(com.codename1.ui.Label) Container(com.codename1.ui.Container) BorderLayout(com.codename1.ui.layouts.BorderLayout) Button(com.codename1.ui.Button) RadioButton(com.codename1.ui.RadioButton) Dialog(com.codename1.ui.Dialog) ComponentEntry(com.codename1.ui.util.xml.comps.ComponentEntry) ArrayList(java.util.ArrayList) ContainerList(com.codename1.ui.list.ContainerList) List(com.codename1.ui.List) LayeredLayout(com.codename1.ui.layouts.LayeredLayout) List(com.codename1.ui.List) RadioButton(com.codename1.ui.RadioButton) CheckBox(com.codename1.ui.CheckBox) Tabs(com.codename1.ui.Tabs) FlowLayout(com.codename1.ui.layouts.FlowLayout) Slider(com.codename1.ui.Slider) Form(com.codename1.ui.Form) BoxLayout(com.codename1.ui.layouts.BoxLayout) ContainerList(com.codename1.ui.list.ContainerList) GridLayout(com.codename1.ui.layouts.GridLayout) Component(com.codename1.ui.Component) TableLayout(com.codename1.ui.table.TableLayout) GenericListCellRenderer(com.codename1.ui.list.GenericListCellRenderer) Hashtable(java.util.Hashtable) Custom(com.codename1.ui.util.xml.comps.Custom) Date(java.util.Date) CommandEntry(com.codename1.ui.util.xml.comps.CommandEntry) BoxLayout(com.codename1.ui.layouts.BoxLayout) LayeredLayout(com.codename1.ui.layouts.LayeredLayout) GridLayout(com.codename1.ui.layouts.GridLayout) Layout(com.codename1.ui.layouts.Layout) FlowLayout(com.codename1.ui.layouts.FlowLayout) BorderLayout(com.codename1.ui.layouts.BorderLayout) TableLayout(com.codename1.ui.table.TableLayout) ActionCommand(com.codename1.designer.ActionCommand) Command(com.codename1.ui.Command)

Example 43 with Component

use of com.codename1.ui.Component in project CodenameOne by codenameone.

the class WrappingLayout method layoutSize.

private Dimension layoutSize(Container parent, SizeGetter getter) {
    int ncomponents = parent.getComponentCount();
    int w = 0;
    int h = 0;
    int v = Preferences.userNodeForPackage(HorizontalList.class).getInt("previewIconWidth", 24);
    if (v > maxButtonWidth && maxButtonWidth > -1) {
        maxButtonWidth = v;
    }
    for (int i = 0; i < ncomponents; i++) {
        Component comp = parent.getComponent(i);
        Dimension d = getter.getSize(comp, maxButtonWidth);
        if (w < d.width) {
            w = d.width;
        }
        if (h < d.height) {
            h = d.height;
        }
    }
    if (ncomponents < 1) {
        return new Dimension(10, 10);
    }
    int parentWidth = Math.max(w, parent.getWidth());
    int columns = parentWidth / w;
    int rows = ncomponents / columns;
    if (ncomponents % columns != 0) {
        rows += 1;
    }
    return new Dimension(columns * w + (2) + columns, rows * h + (rows - 1) + rows);
}
Also used : HorizontalList(com.codename1.designer.HorizontalList) Dimension(java.awt.Dimension) Component(java.awt.Component)

Example 44 with Component

use of com.codename1.ui.Component in project CodenameOne by codenameone.

the class ResourceEditorView method generateStateMachineCodeImpl.

private static String generateStateMachineCodeImpl(String uiResourceName, File destFile, boolean promptUserForPackageName, EditableResources loadResources, java.awt.Component errorParent) {
    String packageString = "";
    File currentFile = destFile;
    while (currentFile.getParent() != null) {
        String shortName = currentFile.getParentFile().getName();
        if (shortName.equalsIgnoreCase("src")) {
            break;
        }
        if (shortName.indexOf(':') > -1 || shortName.length() == 0) {
            break;
        }
        if (shortName.equalsIgnoreCase("org") || shortName.equalsIgnoreCase("com") || shortName.equalsIgnoreCase("net") || shortName.equalsIgnoreCase("gov")) {
            if (packageString.length() > 0) {
                packageString = shortName + "." + packageString;
            } else {
                packageString = shortName;
            }
            break;
        }
        if (packageString.length() > 0) {
            packageString = shortName + "." + packageString;
        } else {
            packageString = shortName;
        }
        currentFile = currentFile.getParentFile();
    }
    final Map<String, String> nameToClassLookup = new HashMap<String, String>();
    final Map<String, Integer> commandMap = new HashMap<String, Integer>();
    final List<Integer> unhandledCommands = new ArrayList<Integer>();
    final List<String[]> actionComponents = new ArrayList<String[]>();
    final Map<String, String> allComponents = new HashMap<String, String>();
    initCommandMapAndNameToClassLookup(nameToClassLookup, commandMap, unhandledCommands, actionComponents, allComponents);
    // list all the .ovr files and add them to the nameToClassLookup
    if (loadedFile != null && loadedFile.getParentFile() != null) {
        File overrideDir = new File(loadedFile.getParentFile().getParentFile(), "override");
        if (overrideDir.exists()) {
            File[] ovrFiles = overrideDir.listFiles(new FilenameFilter() {

                @Override
                public boolean accept(File file, String string) {
                    return string.endsWith(".ovr");
                }
            });
            for (File ovr : ovrFiles) {
                try {
                    EditableResources er = EditableResources.open(new FileInputStream(ovr));
                    for (String currentResourceName : er.getUIResourceNames()) {
                        UIBuilder b = new UIBuilder() {

                            protected com.codename1.ui.Component createComponentInstance(String componentType, Class cls) {
                                if (cls.getName().startsWith("com.codename1.ui.")) {
                                    // subpackage of CodenameOne should be registered
                                    if (cls.getName().lastIndexOf(".") > 15) {
                                        nameToClassLookup.put(componentType, cls.getName());
                                    }
                                } else {
                                    nameToClassLookup.put(componentType, cls.getName());
                                }
                                return null;
                            }
                        };
                        b.createContainer(er, currentResourceName);
                    }
                } catch (IOException ioErr) {
                    ioErr.printStackTrace();
                }
            }
        }
    }
    if (promptUserForPackageName) {
        JTextField packageName = new JTextField(packageString);
        JOptionPane.showMessageDialog(errorParent, packageName, "Please Pick The Package Name", JOptionPane.PLAIN_MESSAGE);
        packageString = packageName.getText();
    }
    List<String> createdMethodNames = new ArrayList<String>();
    try {
        Writer w = new FileWriter(destFile);
        w.write("/**\n");
        w.write(" * This class contains generated code from the Codename One Designer, DO NOT MODIFY!\n");
        w.write(" * This class is designed for subclassing that way the code generator can overwrite it\n");
        w.write(" * anytime without erasing your changes which should exist in a subclass!\n");
        w.write(" * For details about this file and how it works please read this blog post:\n");
        w.write(" * http://codenameone.blogspot.com/2010/10/ui-builder-class-how-to-actually-use.html\n");
        w.write("*/\n");
        if (packageString.length() > 0) {
            w.write("package " + packageString + ";\n\n");
        }
        String className = destFile.getName().substring(0, destFile.getName().indexOf('.'));
        boolean hasIo = false;
        for (String currentName : nameToClassLookup.keySet()) {
            if (nameToClassLookup.get(currentName).indexOf("com.codename1.ui.io") > -1) {
                hasIo = true;
                break;
            }
        }
        w.write("import com.codename1.ui.*;\n");
        w.write("import com.codename1.ui.util.*;\n");
        w.write("import com.codename1.ui.plaf.*;\n");
        w.write("import java.util.Hashtable;\n");
        if (hasIo) {
            w.write("import com.codename1.ui.io.*;\n");
            w.write("import com.codename1.components*;\n");
        }
        w.write("import com.codename1.ui.events.*;\n\n");
        w.write("public abstract class " + className + " extends UIBuilder {\n");
        w.write("    private Container aboutToShowThisContainer;\n");
        w.write("    /**\n");
        w.write("     * this method should be used to initialize variables instead of\n");
        w.write("     * the constructor/class scope to avoid race conditions\n");
        w.write("     */\n");
        w.write("    /**\n    * @deprecated use the version that accepts a resource as an argument instead\n    \n**/\n");
        w.write("    protected void initVars() {}\n\n");
        w.write("    protected void initVars(Resources res) {}\n\n");
        w.write("    public " + className + "(Resources res, String resPath, boolean loadTheme) {\n");
        w.write("        startApp(res, resPath, loadTheme);\n");
        w.write("    }\n\n");
        w.write("    public Container startApp(Resources res, String resPath, boolean loadTheme) {\n");
        w.write("        initVars();\n");
        if (hasIo) {
            w.write("        NetworkManager.getInstance().start();\n");
        }
        for (String currentName : nameToClassLookup.keySet()) {
            w.write("        UIBuilder.registerCustomComponent(\"" + currentName + "\", " + nameToClassLookup.get(currentName) + ".class);\n");
        }
        w.write("        if(loadTheme) {\n");
        w.write("            if(res == null) {\n");
        w.write("                try {\n");
        w.write("                    if(resPath.endsWith(\".res\")) {\n");
        w.write("                        res = Resources.open(resPath);\n");
        w.write("                        System.out.println(\"Warning: you should construct the state machine without the .res extension to allow theme overlays\");\n");
        w.write("                    } else {\n");
        w.write("                        res = Resources.openLayered(resPath);\n");
        w.write("                    }\n");
        w.write("                } catch(java.io.IOException err) { err.printStackTrace(); }\n");
        w.write("            }\n");
        w.write("            initTheme(res);\n");
        w.write("        }\n");
        w.write("        if(res != null) {\n");
        w.write("            setResourceFilePath(resPath);\n");
        w.write("            setResourceFile(res);\n");
        w.write("            initVars(res);\n");
        w.write("            return showForm(getFirstFormName(), null);\n");
        w.write("        } else {\n");
        w.write("            Form f = (Form)createContainer(resPath, getFirstFormName());\n");
        w.write("            initVars(fetchResourceFile());\n");
        w.write("            beforeShow(f);\n");
        w.write("            f.show();\n");
        w.write("            postShow(f);\n");
        w.write("            return f;\n");
        w.write("        }\n");
        w.write("    }\n\n");
        w.write("    protected String getFirstFormName() {\n");
        w.write("        return \"" + uiResourceName + "\";\n");
        w.write("    }\n\n");
        w.write("    public Container createWidget(Resources res, String resPath, boolean loadTheme) {\n");
        w.write("        initVars();\n");
        if (hasIo) {
            w.write("        NetworkManager.getInstance().start();\n");
        }
        for (String currentName : nameToClassLookup.keySet()) {
            w.write("        UIBuilder.registerCustomComponent(\"" + currentName + "\", " + nameToClassLookup.get(currentName) + ".class);\n");
        }
        w.write("        if(loadTheme) {\n");
        w.write("            if(res == null) {\n");
        w.write("                try {\n");
        w.write("                    res = Resources.openLayered(resPath);\n");
        w.write("                } catch(java.io.IOException err) { err.printStackTrace(); }\n");
        w.write("            }\n");
        w.write("            initTheme(res);\n");
        w.write("        }\n");
        w.write("        return createContainer(resPath, \"" + uiResourceName + "\");\n");
        w.write("    }\n\n");
        w.write("    protected void initTheme(Resources res) {\n");
        w.write("            String[] themes = res.getThemeResourceNames();\n");
        w.write("            if(themes != null && themes.length > 0) {\n");
        w.write("                UIManager.getInstance().setThemeProps(res.getTheme(themes[0]));\n");
        w.write("            }\n");
        w.write("    }\n\n");
        w.write("    public " + className + "() {\n");
        w.write("    }\n\n");
        w.write("    public " + className + "(String resPath) {\n");
        w.write("        this(null, resPath, true);\n");
        w.write("    }\n\n");
        w.write("    public " + className + "(Resources res) {\n");
        w.write("        this(res, null, true);\n");
        w.write("    }\n\n");
        w.write("    public " + className + "(String resPath, boolean loadTheme) {\n");
        w.write("        this(null, resPath, loadTheme);\n");
        w.write("    }\n\n");
        w.write("    public " + className + "(Resources res, boolean loadTheme) {\n");
        w.write("        this(res, null, loadTheme);\n");
        w.write("    }\n\n");
        for (String componentName : allComponents.keySet()) {
            String componentType = allComponents.get(componentName);
            String methodName = " find" + normalizeFormName(componentName);
            // exists without a space might trigger this situation and thus code that won't compile
            if (!createdMethodNames.contains(methodName)) {
                if (componentType.equals("com.codename1.ui.Form") || componentType.equals("com.codename1.ui.Dialog")) {
                    continue;
                }
                createdMethodNames.add(methodName);
                w.write("    public " + componentType + methodName + "(Component root) {\n");
                w.write("        return (" + componentType + ")" + "findByName(\"" + componentName + "\", root);\n");
                w.write("    }\n\n");
                w.write("    public " + componentType + methodName + "() {\n");
                w.write("        " + componentType + " cmp = (" + componentType + ")" + "findByName(\"" + componentName + "\", Display.getInstance().getCurrent());\n");
                w.write("        if(cmp == null && aboutToShowThisContainer != null) {\n");
                w.write("            cmp = (" + componentType + ")" + "findByName(\"" + componentName + "\", aboutToShowThisContainer);\n");
                w.write("        }\n");
                w.write("        return cmp;\n");
                w.write("    }\n\n");
            }
        }
        if (commandMap.size() > 0) {
            for (String key : commandMap.keySet()) {
                w.write("    public static final int COMMAND_" + key + " = " + commandMap.get(key) + ";\n");
            }
            w.write("\n");
            StringBuilder methodSwitch = new StringBuilder("    protected void processCommand(ActionEvent ev, Command cmd) {\n        switch(cmd.getId()) {\n");
            for (String key : commandMap.keySet()) {
                String camelCase = "on" + key;
                boolean isAbstract = unhandledCommands.contains(commandMap.get(key));
                if (isAbstract) {
                    w.write("    protected abstract void ");
                    w.write(camelCase);
                    w.write("();\n\n");
                } else {
                    w.write("    protected boolean ");
                    w.write(camelCase);
                    w.write("() {\n        return false;\n    }\n\n");
                }
                methodSwitch.append("            case COMMAND_");
                methodSwitch.append(key);
                methodSwitch.append(":\n");
                methodSwitch.append("                ");
                if (isAbstract) {
                    methodSwitch.append(camelCase);
                    methodSwitch.append("();\n                break;\n\n");
                } else {
                    methodSwitch.append("if(");
                    methodSwitch.append(camelCase);
                    methodSwitch.append("()) {\n                    ev.consume();\n                    return;\n                }\n                break;\n\n");
                }
            }
            methodSwitch.append("        }\n        if(ev.getComponent() != null) {\n            handleComponentAction(ev.getComponent(), ev);\n        }\n    }\n\n");
            w.write(methodSwitch.toString());
        }
        writeFormCallbackCode(w, "    protected void exitForm(Form f) {\n", "f.getName()", "exit", "f", "Form f");
        writeFormCallbackCode(w, "    protected void beforeShow(Form f) {\n    aboutToShowThisContainer = f;\n", "f.getName()", "before", "f", "Form f");
        writeFormCallbackCode(w, "    protected void beforeShowContainer(Container c) {\n        aboutToShowThisContainer = c;\n", "c.getName()", "beforeContainer", "c", "Container c");
        writeFormCallbackCode(w, "    protected void postShow(Form f) {\n", "f.getName()", "post", "f", "Form f");
        writeFormCallbackCode(w, "    protected void postShowContainer(Container c) {\n", "c.getName()", "postContainer", "c", "Container c");
        writeFormCallbackCode(w, "    protected void onCreateRoot(String rootName) {\n", "rootName", "onCreate", "", "");
        writeFormCallbackCode(w, "    protected Hashtable getFormState(Form f) {\n        Hashtable h = super.getFormState(f);\n", "f.getName()", "getState", "f, h", "Form f, Hashtable h", "return h;");
        writeFormCallbackCode(w, "    protected void setFormState(Form f, Hashtable state) {\n        super.setFormState(f, state);\n", "f.getName()", "setState", "f, state", "Form f, Hashtable state");
        List<String> listComponents = new ArrayList<String>();
        for (String currentName : allComponents.keySet()) {
            String value = allComponents.get(currentName);
            if (value.equals("com.codename1.ui.List") || value.equals("com.codename1.ui.ComboBox") || value.equals("com.codename1.ui.list.MultiList") || value.equals("com.codename1.ui.Calendar")) {
                listComponents.add(currentName);
            }
        }
        List<String> containerListComponents = new ArrayList<String>();
        for (String currentName : allComponents.keySet()) {
            String value = allComponents.get(currentName);
            if (value.equals("com.codename1.ui.list.ContainerList")) {
                containerListComponents.add(currentName);
            }
        }
        if (listComponents.size() > 0) {
            w.write("    protected boolean setListModel(List cmp) {\n");
            w.write("        String listName = cmp.getName();\n");
            for (String listName : listComponents) {
                w.write("        if(\"");
                w.write(listName);
                w.write("\".equals(listName)) {\n");
                w.write("            return initListModel");
                w.write(normalizeFormName(listName));
                w.write("(cmp);\n        }\n");
            }
            w.write("        return super.setListModel(cmp);\n    }\n\n");
            for (String listName : listComponents) {
                w.write("    protected boolean initListModel");
                w.write(normalizeFormName(listName));
                w.write("(List cmp) {\n");
                w.write("        return false;\n    }\n\n");
            }
        }
        if (containerListComponents.size() > 0) {
            w.write("    protected boolean setListModel(com.codename1.ui.list.ContainerList cmp) {\n");
            w.write("        String listName = cmp.getName();\n");
            for (String listName : containerListComponents) {
                w.write("        if(\"");
                w.write(listName);
                w.write("\".equals(listName)) {\n");
                w.write("            return initListModel");
                w.write(normalizeFormName(listName));
                w.write("(cmp);\n        }\n");
            }
            w.write("        return super.setListModel(cmp);\n    }\n\n");
            for (String listName : containerListComponents) {
                w.write("    protected boolean initListModel");
                w.write(normalizeFormName(listName));
                w.write("(com.codename1.ui.list.ContainerList cmp) {\n");
                w.write("        return false;\n    }\n\n");
            }
        }
        if (actionComponents.size() > 0) {
            Object lastFormName = null;
            StringBuilder methods = new StringBuilder();
            w.write("    protected void handleComponentAction(Component c, ActionEvent event) {\n");
            w.write("        Container rootContainerAncestor = getRootAncestor(c);\n");
            w.write("        if(rootContainerAncestor == null) return;\n");
            w.write("        String rootContainerName = rootContainerAncestor.getName();\n");
            w.write("        Container leadParentContainer = c.getParent().getLeadParent();\n");
            w.write("        if(leadParentContainer != null && leadParentContainer.getClass() != Container.class) {\n");
            w.write("            c = c.getParent().getLeadParent();\n");
            w.write("        }\n");
            w.write("        if(rootContainerName == null) return;\n");
            for (String[] currentCmp : actionComponents) {
                if (lastFormName != currentCmp[1]) {
                    if (lastFormName != null) {
                        w.write("        }\n");
                    }
                    w.write("        if(rootContainerName.equals(\"");
                    w.write(currentCmp[1]);
                    w.write("\")) {\n");
                    lastFormName = currentCmp[1];
                }
                w.write("            if(\"");
                w.write(currentCmp[0]);
                w.write("\".equals(c.getName())) {\n");
                String methodName = "on" + normalizeFormName(currentCmp[1]) + "_" + normalizeFormName(currentCmp[0]) + "Action";
                w.write("                ");
                w.write(methodName);
                w.write("(c, event);\n");
                w.write("                return;\n");
                w.write("            }\n");
                methods.append("      protected void ");
                methods.append(methodName);
                methods.append("(Component c, ActionEvent event) {\n      }\n\n");
            }
            w.write("        }\n    }\n\n");
            w.write(methods.toString());
        }
        w.write("}\n");
        w.close();
    } catch (IOException ioErr) {
        ioErr.printStackTrace();
        JOptionPane.showMessageDialog(errorParent, "IO Error: " + ioErr, "IO Error", JOptionPane.ERROR_MESSAGE);
    }
    return packageString;
}
Also used : HashMap(java.util.HashMap) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) UIBuilder(com.codename1.ui.util.UIBuilder) JTextField(javax.swing.JTextField) FilenameFilter(java.io.FilenameFilter) UIBuilderOverride(com.codename1.ui.util.UIBuilderOverride) EditableResources(com.codename1.ui.util.EditableResources) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) AnimationObject(com.codename1.ui.animations.AnimationObject) File(java.io.File) BufferedWriter(java.io.BufferedWriter) Writer(java.io.Writer) FileWriter(java.io.FileWriter)

Example 45 with Component

use of com.codename1.ui.Component in project CodenameOne by codenameone.

the class ResourceEditorView method initImagesComboBox.

/**
 * Creates a sorted image combo box that includes image previews. The combo box
 * can be searched by typing a letter even when images are used for the values...
 */
public static void initImagesComboBox(JComboBox cb, final EditableResources res, boolean asString, final boolean includeNull, boolean blockTimelines) {
    String[] imgs = res.getImageResourceNames();
    if (blockTimelines) {
        List<String> nonT = new ArrayList<String>();
        for (String c : imgs) {
            if (!(res.getImage(c) instanceof Timeline)) {
                nonT.add(c);
            }
        }
        imgs = new String[nonT.size()];
        nonT.toArray(imgs);
    }
    final String[] images = imgs;
    Arrays.sort(images, String.CASE_INSENSITIVE_ORDER);
    if (asString) {
        if (includeNull) {
            String[] n = new String[images.length + 1];
            System.arraycopy(images, 0, n, 1, images.length);
            cb.setModel(new DefaultComboBoxModel(n));
        } else {
            cb.setModel(new DefaultComboBoxModel(images));
        }
        cb.setRenderer(new DefaultListCellRenderer() {

            @Override
            public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                boolean n = false;
                if (value == null) {
                    value = "[null]";
                    n = true;
                }
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if (!n) {
                    setIcon(new CodenameOneImageIcon(res.getImage((String) value), 24, 24));
                } else {
                    setIcon(null);
                }
                return this;
            }
        });
    } else {
        int offset = 0;
        com.codename1.ui.Image[] arr;
        if (includeNull) {
            arr = new com.codename1.ui.Image[images.length + 1];
            offset++;
        } else {
            arr = new com.codename1.ui.Image[images.length];
        }
        for (String c : images) {
            arr[offset] = res.getImage(c);
            offset++;
        }
        cb.setModel(new DefaultComboBoxModel(arr));
        cb.setKeySelectionManager(new JComboBox.KeySelectionManager() {

            private String current;

            private long lastPress;

            public int selectionForKey(char aKey, ComboBoxModel aModel) {
                long t = System.currentTimeMillis();
                aKey = Character.toLowerCase(aKey);
                if (t - lastPress < 800) {
                    current += aKey;
                } else {
                    current = "" + aKey;
                }
                lastPress = t;
                for (int iter = 0; iter < images.length; iter++) {
                    if (images[iter].toLowerCase().startsWith(current)) {
                        if (includeNull) {
                            return iter + 1;
                        }
                        return iter;
                    }
                }
                return -1;
            }
        });
        cb.setRenderer(new DefaultListCellRenderer() {

            @Override
            public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                com.codename1.ui.Image i = (com.codename1.ui.Image) value;
                if (value == null) {
                    value = "[null]";
                } else {
                    value = res.findId(value);
                }
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if (i != null) {
                    setIcon(new CodenameOneImageIcon(i, 24, 24));
                } else {
                    setIcon(null);
                }
                return this;
            }
        });
    }
}
Also used : JComboBox(javax.swing.JComboBox) ArrayList(java.util.ArrayList) DefaultComboBoxModel(javax.swing.DefaultComboBoxModel) EncodedImage(com.codename1.ui.EncodedImage) BufferedImage(java.awt.image.BufferedImage) Timeline(com.codename1.ui.animations.Timeline) DefaultListCellRenderer(javax.swing.DefaultListCellRenderer) AnimationObject(com.codename1.ui.animations.AnimationObject) Component(java.awt.Component) UIBuilderOverride(com.codename1.ui.util.UIBuilderOverride) JList(javax.swing.JList) ComboBoxModel(javax.swing.ComboBoxModel) DefaultComboBoxModel(javax.swing.DefaultComboBoxModel)

Aggregations

Component (com.codename1.ui.Component)152 Style (com.codename1.ui.plaf.Style)61 Container (com.codename1.ui.Container)55 Form (com.codename1.ui.Form)41 BorderLayout (com.codename1.ui.layouts.BorderLayout)40 TextArea (com.codename1.ui.TextArea)31 ActionEvent (com.codename1.ui.events.ActionEvent)28 Dimension (com.codename1.ui.geom.Dimension)28 Label (com.codename1.ui.Label)25 Point (com.codename1.ui.geom.Point)22 ArrayList (java.util.ArrayList)22 Rectangle (com.codename1.ui.geom.Rectangle)21 Vector (java.util.Vector)18 Button (com.codename1.ui.Button)16 Dialog (com.codename1.ui.Dialog)16 Hashtable (java.util.Hashtable)16 Image (com.codename1.ui.Image)15 TextField (com.codename1.ui.TextField)15 ActionListener (com.codename1.ui.events.ActionListener)13 BoxLayout (com.codename1.ui.layouts.BoxLayout)13