Search in sources :

Example 66 with BorderLayout

use of com.codename1.ui.layouts.BorderLayout in project CodenameOne by codenameone.

the class LazyValueC method createComponent.

private Component createComponent(DataInputStream in, Container parent, Container root, Resources res, Hashtable componentListeners, EmbeddedContainer embedded) throws Exception {
    String name = in.readUTF();
    int property = in.readInt();
    // special case for the base form
    if (property == PROPERTY_BASE_FORM) {
        String baseFormName = name;
        initBaseForm(baseFormName);
        if (!ignorBaseForm) {
            Form base = (Form) createContainer(res, baseFormName);
            Container destination = (Container) findByName("destination", base);
            // try finding an appropriate empty container if no "fixed" destination is defined
            if (destination == null) {
                destination = findEmptyContainer(base.getContentPane());
                if (destination == null) {
                    System.out.println("Couldn't find appropriate 'destination' container in base form: " + baseFormName);
                    return null;
                }
            }
            root = base;
            Component cmp = createComponent(in, destination, root, res, componentListeners, embedded);
            if (destination.getLayout() instanceof BorderLayout) {
                destination.addComponent(BorderLayout.CENTER, cmp);
            } else {
                destination.addComponent(cmp);
            }
            return root;
        } else {
            name = in.readUTF();
            property = in.readInt();
        }
    }
    Component cmp = createComponentType(name);
    if (componentListeners != null) {
        Object listeners = componentListeners.get(name);
        if (listeners != null) {
            if (listeners instanceof Vector) {
                Vector v = (Vector) listeners;
                for (int iter = 0; iter < v.size(); iter++) {
                    bindListenerToComponent(cmp, v.elementAt(iter));
                }
            } else {
                bindListenerToComponent(cmp, listeners);
            }
        }
    }
    Component actualLead = cmp;
    if (actualLead instanceof Container) {
        Container cnt = (Container) actualLead;
        actualLead = cnt.getLeadComponent();
        if (actualLead == null) {
            actualLead = cmp;
        }
    }
    if (actualLead instanceof Button) {
        ActionListener l = getFormListenerInstance(root, embedded);
        if (l != null) {
            ((Button) actualLead).addActionListener(l);
        }
    } else {
        if (actualLead instanceof TextArea) {
            ActionListener l = getFormListenerInstance(root, embedded);
            if (l != null) {
                ((TextArea) actualLead).addActionListener(l);
            }
        } else {
            if (actualLead instanceof List) {
                ActionListener l = getFormListenerInstance(root, embedded);
                if (l != null) {
                    ((List) actualLead).addActionListener(l);
                }
            } else {
                if (actualLead instanceof ContainerList) {
                    ActionListener l = getFormListenerInstance(root, embedded);
                    if (l != null) {
                        ((ContainerList) actualLead).addActionListener(l);
                    }
                } else {
                    if (actualLead instanceof com.codename1.ui.Calendar) {
                        ActionListener l = getFormListenerInstance(root, embedded);
                        if (l != null) {
                            ((com.codename1.ui.Calendar) actualLead).addActionListener(l);
                        }
                    }
                }
            }
        }
    }
    cmp.putClientProperty(TYPE_KEY, name);
    if (root == null) {
        root = (Container) cmp;
    }
    while (property != -1) {
        modifyingProperty(cmp, property);
        switch(property) {
            case PROPERTY_CUSTOM:
                String customPropertyName = in.readUTF();
                modifyingCustomProperty(cmp, customPropertyName);
                boolean isNull = in.readBoolean();
                if (isNull) {
                    cmp.setPropertyValue(customPropertyName, null);
                    break;
                }
                boolean cl = cmp instanceof ContainerList;
                String[] propertyNames = cmp.getPropertyNames();
                for (int iter = 0; iter < propertyNames.length; iter++) {
                    if (propertyNames[iter].equals(customPropertyName)) {
                        Class type = cmp.getPropertyTypes()[iter];
                        String[] typeNames = cmp.getPropertyTypeNames();
                        String typeName = null;
                        if (typeNames != null && typeNames.length > iter) {
                            typeName = typeNames[iter];
                        }
                        Object value = readCustomPropertyValue(in, type, typeName, res, propertyNames[iter]);
                        if (cl && customPropertyName.equals("ListItems") && setListModel((ContainerList) cmp)) {
                            break;
                        }
                        cmp.setPropertyValue(customPropertyName, value);
                        break;
                    }
                }
                break;
            case PROPERTY_EMBED:
                root.putClientProperty(EMBEDDED_FORM_FLAG, "");
                ((EmbeddedContainer) cmp).setEmbed(in.readUTF());
                Container embed = createContainer(res, ((EmbeddedContainer) cmp).getEmbed(), (EmbeddedContainer) cmp);
                if (embed != null) {
                    if (embed instanceof Form) {
                        embed = formToContainer((Form) embed);
                    }
                    ((EmbeddedContainer) cmp).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);
                }
                break;
            case PROPERTY_TOGGLE_BUTTON:
                ((Button) cmp).setToggle(in.readBoolean());
                break;
            case PROPERTY_RADIO_GROUP:
                ((RadioButton) cmp).setGroup(in.readUTF());
                break;
            case PROPERTY_SELECTED:
                boolean isSelected = in.readBoolean();
                if (cmp instanceof RadioButton) {
                    ((RadioButton) cmp).setSelected(isSelected);
                } else {
                    ((CheckBox) cmp).setSelected(isSelected);
                }
                break;
            case PROPERTY_SCROLLABLE_X:
                ((Container) cmp).setScrollableX(in.readBoolean());
                break;
            case PROPERTY_SCROLLABLE_Y:
                ((Container) cmp).setScrollableY(in.readBoolean());
                break;
            case PROPERTY_TENSILE_DRAG_ENABLED:
                cmp.setTensileDragEnabled(in.readBoolean());
                break;
            case PROPERTY_TACTILE_TOUCH:
                cmp.setTactileTouch(in.readBoolean());
                break;
            case PROPERTY_SNAP_TO_GRID:
                cmp.setSnapToGrid(in.readBoolean());
                break;
            case PROPERTY_FLATTEN:
                cmp.setFlatten(in.readBoolean());
                break;
            case PROPERTY_TEXT:
                if (cmp instanceof Label) {
                    ((Label) cmp).setText(in.readUTF());
                } else {
                    ((TextArea) cmp).setText(in.readUTF());
                }
                break;
            case PROPERTY_TEXT_MAX_LENGTH:
                ((TextArea) cmp).setMaxSize(in.readInt());
                break;
            case PROPERTY_TEXT_CONSTRAINT:
                ((TextArea) cmp).setConstraint(in.readInt());
                if (cmp instanceof TextField) {
                    int cons = ((TextArea) cmp).getConstraint();
                    if ((cons & TextArea.NUMERIC) == TextArea.NUMERIC) {
                        ((TextField) cmp).setInputModeOrder(new String[] { "123" });
                    }
                }
                break;
            case PROPERTY_ALIGNMENT:
                if (cmp instanceof Label) {
                    ((Label) cmp).setAlignment(in.readInt());
                } else {
                    ((TextArea) cmp).setAlignment(in.readInt());
                }
                break;
            case PROPERTY_TEXT_AREA_GROW:
                ((TextArea) cmp).setGrowByContent(in.readBoolean());
                break;
            case PROPERTY_LAYOUT:
                Layout layout = null;
                switch(in.readShort()) {
                    case LAYOUT_BORDER_LEGACY:
                        layout = new BorderLayout();
                        break;
                    case LAYOUT_BORDER_ANOTHER_LEGACY:
                        {
                            BorderLayout b = new BorderLayout();
                            if (in.readBoolean()) {
                                b.defineLandscapeSwap(BorderLayout.NORTH, in.readUTF());
                            }
                            if (in.readBoolean()) {
                                b.defineLandscapeSwap(BorderLayout.EAST, in.readUTF());
                            }
                            if (in.readBoolean()) {
                                b.defineLandscapeSwap(BorderLayout.WEST, in.readUTF());
                            }
                            if (in.readBoolean()) {
                                b.defineLandscapeSwap(BorderLayout.SOUTH, in.readUTF());
                            }
                            if (in.readBoolean()) {
                                b.defineLandscapeSwap(BorderLayout.CENTER, in.readUTF());
                            }
                            layout = b;
                            break;
                        }
                    case LAYOUT_BORDER:
                        {
                            BorderLayout b = new BorderLayout();
                            if (in.readBoolean()) {
                                b.defineLandscapeSwap(BorderLayout.NORTH, in.readUTF());
                            }
                            if (in.readBoolean()) {
                                b.defineLandscapeSwap(BorderLayout.EAST, in.readUTF());
                            }
                            if (in.readBoolean()) {
                                b.defineLandscapeSwap(BorderLayout.WEST, in.readUTF());
                            }
                            if (in.readBoolean()) {
                                b.defineLandscapeSwap(BorderLayout.SOUTH, in.readUTF());
                            }
                            if (in.readBoolean()) {
                                b.defineLandscapeSwap(BorderLayout.CENTER, in.readUTF());
                            }
                            b.setAbsoluteCenter(in.readBoolean());
                            layout = b;
                            break;
                        }
                    case LAYOUT_BOX_X:
                        layout = new BoxLayout(BoxLayout.X_AXIS);
                        break;
                    case LAYOUT_BOX_Y:
                        layout = new BoxLayout(BoxLayout.Y_AXIS);
                        break;
                    case LAYOUT_FLOW_LEGACY:
                        layout = new FlowLayout();
                        break;
                    case LAYOUT_FLOW:
                        FlowLayout f = new FlowLayout();
                        f.setFillRows(in.readBoolean());
                        f.setAlign(in.readInt());
                        f.setValign(in.readInt());
                        layout = f;
                        break;
                    case LAYOUT_LAYERED:
                        layout = new LayeredLayout();
                        break;
                    case LAYOUT_GRID:
                        layout = new GridLayout(in.readInt(), in.readInt());
                        break;
                    case LAYOUT_TABLE:
                        layout = new TableLayout(in.readInt(), in.readInt());
                        break;
                }
                ((Container) cmp).setLayout(layout);
                break;
            case PROPERTY_TAB_PLACEMENT:
                ((Tabs) cmp).setTabPlacement(in.readInt());
                break;
            case PROPERTY_TAB_TEXT_POSITION:
                ((Tabs) cmp).setTabTextPosition(in.readInt());
                break;
            case PROPERTY_PREFERRED_WIDTH:
                cmp.setPreferredW(in.readInt());
                break;
            case PROPERTY_PREFERRED_HEIGHT:
                cmp.setPreferredH(in.readInt());
                break;
            case PROPERTY_UIID:
                cmp.setUIID(in.readUTF());
                break;
            case PROPERTY_DIALOG_UIID:
                ((Dialog) cmp).setDialogUIID(in.readUTF());
                break;
            case PROPERTY_DISPOSE_WHEN_POINTER_OUT:
                ((Dialog) cmp).setDisposeWhenPointerOutOfBounds(in.readBoolean());
                break;
            case PROPERTY_CLOUD_BOUND_PROPERTY:
                cmp.setCloudBoundProperty(in.readUTF());
                break;
            case PROPERTY_CLOUD_DESTINATION_PROPERTY:
                cmp.setCloudDestinationProperty(in.readUTF());
                break;
            case PROPERTY_DIALOG_POSITION:
                String pos = in.readUTF();
                if (pos.length() > 0) {
                    ((Dialog) cmp).setDialogPosition(pos);
                }
                break;
            case PROPERTY_FOCUSABLE:
                cmp.setFocusable(in.readBoolean());
                break;
            case PROPERTY_ENABLED:
                cmp.setEnabled(in.readBoolean());
                break;
            case PROPERTY_SCROLL_VISIBLE:
                cmp.setScrollVisible(in.readBoolean());
                break;
            case PROPERTY_ICON:
                ((Label) cmp).setIcon(res.getImage(in.readUTF()));
                break;
            case PROPERTY_ROLLOVER_ICON:
                ((Button) cmp).setRolloverIcon(res.getImage(in.readUTF()));
                break;
            case PROPERTY_PRESSED_ICON:
                ((Button) cmp).setPressedIcon(res.getImage(in.readUTF()));
                break;
            case PROPERTY_DISABLED_ICON:
                ((Button) cmp).setDisabledIcon(res.getImage(in.readUTF()));
                break;
            case PROPERTY_GAP:
                ((Label) cmp).setGap(in.readInt());
                break;
            case PROPERTY_VERTICAL_ALIGNMENT:
                if (cmp instanceof TextArea) {
                    ((TextArea) cmp).setVerticalAlignment(in.readInt());
                } else {
                    ((Label) cmp).setVerticalAlignment(in.readInt());
                }
                break;
            case PROPERTY_TEXT_POSITION:
                ((Label) cmp).setTextPosition(in.readInt());
                break;
            case PROPERTY_CLIENT_PROPERTIES:
                int count = in.readInt();
                StringBuilder sb = new StringBuilder();
                for (int iter = 0; iter < count; iter++) {
                    String k = in.readUTF();
                    String v = in.readUTF();
                    cmp.putClientProperty(k, v);
                    sb.append(k);
                    if (iter < count - 1) {
                        sb.append(",");
                    }
                }
                cmp.putClientProperty("cn1$Properties", sb.toString());
                break;
            case PROPERTY_NAME:
                String componentName = in.readUTF();
                cmp.setName(componentName);
                root.putClientProperty("%" + componentName + "%", cmp);
                break;
            case PROPERTY_LAYOUT_CONSTRAINT:
                if (parent.getLayout() instanceof BorderLayout) {
                    cmp.putClientProperty("layoutConstraint", in.readUTF());
                } else {
                    TableLayout tl = (TableLayout) parent.getLayout();
                    TableLayout.Constraint con = tl.createConstraint(in.readInt(), in.readInt());
                    con.setHeightPercentage(in.readInt());
                    con.setWidthPercentage(in.readInt());
                    con.setHorizontalAlign(in.readInt());
                    con.setHorizontalSpan(in.readInt());
                    con.setVerticalAlign(in.readInt());
                    con.setVerticalSpan(in.readInt());
                    cmp.putClientProperty("layoutConstraint", con);
                }
                break;
            case PROPERTY_TITLE:
                ((Form) cmp).setTitle(in.readUTF());
                break;
            case PROPERTY_COMPONENTS:
                int componentCount = in.readInt();
                if (cmp instanceof Tabs) {
                    for (int iter = 0; iter < componentCount; iter++) {
                        String tab = in.readUTF();
                        Component child = createComponent(in, (Container) cmp, root, res, componentListeners, embedded);
                        ((Tabs) cmp).addTab(tab, child);
                    }
                } else {
                    for (int iter = 0; iter < componentCount; iter++) {
                        Component child = createComponent(in, (Container) cmp, root, res, componentListeners, embedded);
                        Object con = child.getClientProperty("layoutConstraint");
                        if (con != null) {
                            ((Container) cmp).addComponent(con, child);
                        } else {
                            ((Container) cmp).addComponent(child);
                        }
                    }
                }
                break;
            case PROPERTY_COLUMNS:
                ((TextArea) cmp).setColumns(in.readInt());
                break;
            case PROPERTY_ROWS:
                ((TextArea) cmp).setRows(in.readInt());
                break;
            case PROPERTY_HINT:
                if (cmp instanceof List) {
                    ((List) cmp).setHint(in.readUTF());
                } else {
                    ((TextArea) cmp).setHint(in.readUTF());
                }
                break;
            case PROPERTY_HINT_ICON:
                if (cmp instanceof List) {
                    ((List) cmp).setHintIcon(res.getImage(in.readUTF()));
                } else {
                    ((TextArea) cmp).setHintIcon(res.getImage(in.readUTF()));
                }
                break;
            case PROPERTY_ITEM_GAP:
                ((List) cmp).setItemGap(in.readInt());
                break;
            case PROPERTY_LIST_FIXED:
                ((List) cmp).setFixedSelection(in.readInt());
                break;
            case PROPERTY_LIST_ORIENTATION:
                ((List) cmp).setOrientation(in.readInt());
                break;
            case PROPERTY_LIST_ITEMS_LEGACY:
                String[] items = new String[in.readInt()];
                for (int iter = 0; iter < items.length; iter++) {
                    items[iter] = in.readUTF();
                }
                if (!setListModel(((List) cmp))) {
                    ((List) cmp).setModel(new DefaultListModel((Object[]) items));
                }
                break;
            case PROPERTY_LIST_ITEMS:
                Object[] elements = readObjectArrayForListModel(in, res);
                if (!setListModel(((List) cmp))) {
                    ((List) cmp).setModel(new DefaultListModel(elements));
                }
                break;
            case PROPERTY_LIST_RENDERER:
                if (cmp instanceof ContainerList) {
                    ((ContainerList) cmp).setRenderer(readRendererer(res, in));
                } else {
                    ((List) cmp).setRenderer(readRendererer(res, in));
                }
                break;
            case PROPERTY_NEXT_FORM:
                String nextForm = in.readUTF();
                setNextForm(cmp, nextForm, res, root);
                break;
            case PROPERTY_COMMANDS:
                readCommands(in, cmp, res, false);
                break;
            case PROPERTY_COMMANDS_LEGACY:
                readCommands(in, cmp, res, true);
                break;
            case PROPERTY_CYCLIC_FOCUS:
                ((Form) cmp).setCyclicFocus(in.readBoolean());
                break;
            case PROPERTY_RTL:
                cmp.setRTL(in.readBoolean());
                break;
            case PROPERTY_SLIDER_THUMB:
                ((Slider) cmp).setThumbImage(res.getImage(in.readUTF()));
                break;
            case PROPERTY_INFINITE:
                ((Slider) cmp).setInfinite(in.readBoolean());
                break;
            case PROPERTY_PROGRESS:
                ((Slider) cmp).setProgress(in.readInt());
                break;
            case PROPERTY_VERTICAL:
                ((Slider) cmp).setVertical(in.readBoolean());
                break;
            case PROPERTY_EDITABLE:
                if (cmp instanceof TextArea) {
                    ((TextArea) cmp).setEditable(in.readBoolean());
                } else {
                    ((Slider) cmp).setEditable(in.readBoolean());
                }
                break;
            case PROPERTY_INCREMENTS:
                ((Slider) cmp).setIncrements(in.readInt());
                break;
            case PROPERTY_RENDER_PERCENTAGE_ON_TOP:
                ((Slider) cmp).setRenderPercentageOnTop(in.readBoolean());
                break;
            case PROPERTY_MAX_VALUE:
                ((Slider) cmp).setMaxValue(in.readInt());
                break;
            case PROPERTY_MIN_VALUE:
                ((Slider) cmp).setMinValue(in.readInt());
                break;
        }
        property = in.readInt();
    }
    postCreateComponent(cmp);
    return cmp;
}
Also used : FlowLayout(com.codename1.ui.layouts.FlowLayout) Slider(com.codename1.ui.Slider) Form(com.codename1.ui.Form) TextArea(com.codename1.ui.TextArea) ContainerList(com.codename1.ui.list.ContainerList) BoxLayout(com.codename1.ui.layouts.BoxLayout) Label(com.codename1.ui.Label) DefaultListModel(com.codename1.ui.list.DefaultListModel) Container(com.codename1.ui.Container) GridLayout(com.codename1.ui.layouts.GridLayout) BorderLayout(com.codename1.ui.layouts.BorderLayout) Button(com.codename1.ui.Button) RadioButton(com.codename1.ui.RadioButton) Dialog(com.codename1.ui.Dialog) TextField(com.codename1.ui.TextField) List(com.codename1.ui.List) ContainerList(com.codename1.ui.list.ContainerList) Component(com.codename1.ui.Component) LayeredLayout(com.codename1.ui.layouts.LayeredLayout) Vector(java.util.Vector) TableLayout(com.codename1.ui.table.TableLayout) RadioButton(com.codename1.ui.RadioButton) ActionListener(com.codename1.ui.events.ActionListener) BoxLayout(com.codename1.ui.layouts.BoxLayout) LayeredLayout(com.codename1.ui.layouts.LayeredLayout) GridLayout(com.codename1.ui.layouts.GridLayout) FlowLayout(com.codename1.ui.layouts.FlowLayout) BorderLayout(com.codename1.ui.layouts.BorderLayout) Layout(com.codename1.ui.layouts.Layout) TableLayout(com.codename1.ui.table.TableLayout) CheckBox(com.codename1.ui.CheckBox) Tabs(com.codename1.ui.Tabs)

Example 67 with BorderLayout

use of com.codename1.ui.layouts.BorderLayout in project CodenameOne by codenameone.

the class GameCanvasImplementation method captureVideo.

public void captureVideo(ActionListener response) {
    captureResponse = response;
    try {
        final Form current = Display.getInstance().getCurrent();
        final MMAPIPlayer player = MMAPIPlayer.createPlayer("capture://video", null);
        RecordControl record = (RecordControl) player.nativePlayer.getControl("RecordControl");
        if (record == null) {
            player.cleanup();
            throw new RuntimeException("Capture Video is not supported on this device");
        }
        final Form cam = new Form();
        cam.setTransitionInAnimator(CommonTransitions.createEmpty());
        cam.setTransitionOutAnimator(CommonTransitions.createEmpty());
        cam.setLayout(new BorderLayout());
        cam.show();
        MIDPVideoComponent video = new MIDPVideoComponent(player, canvas);
        video.play();
        video.setVisible(true);
        cam.addComponent(BorderLayout.CENTER, video);
        final Label time = new Label("0:00");
        cam.addComponent(BorderLayout.SOUTH, time);
        cam.revalidate();
        ActionListener l = new ActionListener() {

            boolean recording = false;

            OutputStream out = null;

            String videoPath = null;

            RecordControl record;

            public void actionPerformed(ActionEvent evt) {
                if (!recording) {
                    record = (RecordControl) player.nativePlayer.getControl("RecordControl");
                    recording = true;
                    String type = record.getContentType();
                    String prefix = "";
                    if (type.endsWith("mpeg")) {
                        prefix = ".mpeg";
                    } else if (type.endsWith("4")) {
                        prefix = ".mp4";
                    } else if (type.endsWith("3gpp")) {
                        prefix = ".3gp";
                    } else if (type.endsWith("avi")) {
                        prefix = ".avi";
                    }
                    videoPath = getOutputMediaFile() + prefix;
                    try {
                        out = FileSystemStorage.getInstance().openOutputStream(videoPath);
                        record.setRecordStream(out);
                        record.startRecord();
                        cam.registerAnimated(new Animation() {

                            long current = System.currentTimeMillis();

                            long zero = current;

                            int sec = 0;

                            public boolean animate() {
                                long now = System.currentTimeMillis();
                                if (now - current > 1000) {
                                    current = now;
                                    sec++;
                                    return true;
                                }
                                return false;
                            }

                            public void paint(Graphics g) {
                                String txt = sec / 60 + ":" + sec % 60;
                                time.setText(txt);
                            }
                        });
                    } catch (IOException ex) {
                        ex.printStackTrace();
                        System.out.println("failed to store video to " + videoPath);
                    } finally {
                    }
                } else {
                    if (out != null) {
                        try {
                            record.stopRecord();
                            record.commit();
                            out.close();
                            player.cleanup();
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                    captureResponse.actionPerformed(new ActionEvent(videoPath));
                    current.showBack();
                }
            }
        };
        cam.addGameKeyListener(Display.GAME_FIRE, l);
        cam.addPointerReleasedListener(l);
    } catch (IOException ex) {
        ex.printStackTrace();
        throw new RuntimeException("failed to start camera");
    }
}
Also used : Form(com.codename1.ui.Form) ActionEvent(com.codename1.ui.events.ActionEvent) DataOutputStream(java.io.DataOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedOutputStream(com.codename1.io.BufferedOutputStream) OutputStream(java.io.OutputStream) IOException(java.io.IOException) RecordStoreException(javax.microedition.rms.RecordStoreException) MediaException(javax.microedition.media.MediaException) IOException(java.io.IOException) ConnectionNotFoundException(javax.microedition.io.ConnectionNotFoundException) Graphics(com.codename1.ui.Graphics) BorderLayout(com.codename1.ui.layouts.BorderLayout) ActionListener(com.codename1.ui.events.ActionListener) Animation(com.codename1.ui.animations.Animation) RecordControl(javax.microedition.media.control.RecordControl)

Example 68 with BorderLayout

use of com.codename1.ui.layouts.BorderLayout in project CodenameOne by codenameone.

the class JavascriptTests method runTest.

@Override
public boolean runTest() throws Exception {
    Form f = new Form("Test Browser");
    f.setLayout(new BorderLayout());
    BrowserComponent bc = new BrowserComponent();
    bc.setPage("<!doctype html><html><head><title>Foo</title><body>Body</body></head></html>", "http://www.codenameone.com");
    final Res res = new Res();
    bc.addWebEventListener(BrowserComponent.onLoad, e -> {
        try {
            int timeout = 5000;
            bc.execute("window.person={name:'Steve', somefunc: function(a){this.someval = a}}");
            JSRef tmp = bc.executeAndWait(timeout, "callback.onSuccess(person.name)");
            TestUtils.assertEqual(JSType.STRING, tmp.getJSType(), "Wrong JSType for person.name");
            TestUtils.assertEqual("Steve", tmp.toString());
            bc.execute("person.age=${0}", new Object[] { 24 });
            tmp = bc.executeAndWait(timeout, "callback.onSuccess(person.age)");
            TestUtils.assertEqual(JSType.NUMBER, tmp.getJSType(), "Wrong JSType for age");
            TestUtils.assertEqual(24, tmp.getInt(), "Age should be 24");
            bc.execute("person.enabled=${0}", new Object[] { true });
            tmp = bc.executeAndWait(timeout, "callback.onSuccess(person.enabled)");
            TestUtils.assertEqual(JSType.BOOLEAN, tmp.getJSType(), "Wrong JSType for enabled");
            TestUtils.assertEqual(true, tmp.getBoolean(), "Wrong value for enabled");
            tmp = bc.executeAndWait(timeout, "callback.onSuccess(person)");
            TestUtils.assertEqual(JSType.OBJECT, tmp.getJSType(), "Wrong type for person");
            tmp = bc.executeAndWait(timeout, "callback.onSuccess(person.somefunc)");
            TestUtils.assertEqual(JSType.FUNCTION, tmp.getJSType(), "Wrong type for somefunc");
            tmp = bc.executeAndWait(timeout, "callback.onSuccess(person.firstName)");
            TestUtils.assertEqual(JSType.UNDEFINED, tmp.getJSType(), "firstName should be undefined");
            bc.execute("window.person2={name:'Marlene'}");
            tmp = bc.executeAndWait(timeout, "callback.onSuccess(48)");
            bc.execute("window.person2.age=${0}", new Object[] { tmp });
            tmp = bc.executeAndWait(timeout, "callback.onSuccess(window.person2.age)");
            TestUtils.assertEqual(JSType.NUMBER, tmp.getJSType(), "Wrong type for age after setting with JSRef");
            TestUtils.assertEqual(48, tmp.getInt(), "Wrong value for age after setting with JSRef");
            tmp = bc.executeAndWait(timeout, "callback.onSuccess(${0} + ${1} + ${2} + ${3})", new Object[] { 1, 2, 3, 4 });
            TestUtils.assertEqual(JSType.NUMBER, tmp.getJSType(), "Wrong type for 1+2+3+4");
            TestUtils.assertEqual(10, tmp.getInt(), "Wrong value for 1+2+3+4");
            JSRef name1 = bc.executeAndWait(timeout, "callback.onSuccess(person.name)");
            JSRef name2 = bc.executeAndWait(timeout, "callback.onSuccess(person2.name)");
            JSRef name1name2 = bc.executeAndWait(timeout, "callback.onSuccess(${0} +' '+${1})", new Object[] { name1, name2 });
            TestUtils.assertEqual(JSType.STRING, name1name2.getJSType(), "Wrong type for name1name2");
            TestUtils.assertEqual("Steve Marlene", name1name2.toString(), "Wrong value for name1name2");
            // Steve
            JSProxy proxy = bc.createJSProxy("person.name");
            tmp = proxy.callAndWait(timeout, "indexOf", new Object[] { "e" });
            TestUtils.assertEqual(2, tmp.getInt(), "Wrong position for 'e'");
            tmp = proxy.getAndWait(timeout, "length");
            TestUtils.assertEqual(5, tmp.getInt(), "Wrong string length in proxy");
            synchronized (res) {
                res.complete = true;
                res.notifyAll();
            }
            res.complete = true;
        } catch (Throwable t) {
            synchronized (res) {
                res.complete = true;
                res.error = t;
                res.notifyAll();
            }
        }
    });
    f.add(BorderLayout.CENTER, bc);
    f.show();
    while (!res.complete) {
        Display.getInstance().invokeAndBlock(() -> {
            synchronized (res) {
                Util.wait(res, 1000);
            }
        });
    }
    if (res.error != null) {
        Log.e(res.error);
        throw new Exception(res.error.getMessage());
    }
    return true;
}
Also used : JSRef(com.codename1.ui.BrowserComponent.JSRef) BorderLayout(com.codename1.ui.layouts.BorderLayout) JSProxy(com.codename1.ui.BrowserComponent.JSProxy)

Example 69 with BorderLayout

use of com.codename1.ui.layouts.BorderLayout in project CodenameOne by codenameone.

the class TestComponent method testBrowserComponent2267.

// Test for https://github.com/codenameone/CodenameOne/issues/2267
private void testBrowserComponent2267() {
    Form hi = new Form();
    String formName = "testBrowserComponent2267";
    hi.setName(formName);
    hi.setLayout(new BorderLayout());
    BrowserComponent browserComponent = new BrowserComponent();
    hi.add(BorderLayout.CENTER, browserComponent);
    final Throwable[] ex = new Throwable[1];
    final boolean[] complete = new boolean[1];
    Button loadButton = new Button("setUrl");
    String buttonName = "setUrl";
    loadButton.setName(buttonName);
    loadButton.addActionListener((ev) -> {
        ActionListener errorHandler = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                e.consume();
                ex[0] = (Throwable) e.getSource();
                complete[0] = true;
                Display.getInstance().removeEdtErrorHandler(this);
            }
        };
        try {
            Display.getInstance().addEdtErrorHandler(errorHandler);
            browserComponent.addWebEventListener("onLoad", e -> {
                Display.getInstance().removeEdtErrorHandler(errorHandler);
                complete[0] = true;
            });
            browserComponent.setURL("https://www.google.es");
        } catch (Throwable t) {
            ex[0] = t;
            complete[0] = true;
            Display.getInstance().removeEdtErrorHandler(errorHandler);
        } finally {
        // complete[0] = true;
        }
    });
    hi.add(BorderLayout.SOUTH, loadButton);
    hi.show();
    TestUtils.waitForFormName(formName, 2000);
    TestUtils.clickButtonByName(buttonName);
    while (!complete[0]) {
        Display.getInstance().invokeAndBlock(() -> {
            Util.sleep(50);
        });
    }
    String message = null;
    if (ex[0] != null) {
        message = ex[0].getMessage();
    }
    TestUtils.assertBool(ex[0] == null, "We received an exception setting the browserComponent URL: " + message);
}
Also used : BorderLayout(com.codename1.ui.layouts.BorderLayout) ActionListener(com.codename1.ui.events.ActionListener) ActionEvent(com.codename1.ui.events.ActionEvent)

Example 70 with BorderLayout

use of com.codename1.ui.layouts.BorderLayout in project codenameone-google-maps by codenameone.

the class GoogleMapsTestApp method start.

public void start() {
    if (current != null) {
        current.show();
        return;
    }
    Form hi = new Form("Native Maps Test");
    hi.setLayout(new BorderLayout());
    final MapContainer cnt = new MapContainer(HTML_API_KEY);
    // final MapContainer cnt = new MapContainer();
    // this breaks the code //because the Google map is not loaded yet
    cnt.setCameraPosition(new Coord(-26.1486233, 28.67401229999996));
    cnt.addMapListener(new MapListener() {

        @Override
        public void mapPositionUpdated(Component source, int zoom, Coord center) {
            System.out.println("Map position updated: zoom=" + zoom + ", Center=" + center);
        }
    });
    cnt.addLongPressListener(e -> {
        System.out.println("Long press");
        ToastBar.showMessage("Received longPress at " + e.getX() + ", " + e.getY(), FontImage.MATERIAL_3D_ROTATION);
    });
    cnt.addTapListener(e -> {
        ToastBar.showMessage("Received tap at " + e.getX() + ", " + e.getY(), FontImage.MATERIAL_3D_ROTATION);
    });
    int maxZoom = cnt.getMaxZoom();
    System.out.println("Max zoom is " + maxZoom);
    Button btnMoveCamera = new Button("Move Camera");
    btnMoveCamera.addActionListener(e -> {
        cnt.setCameraPosition(new Coord(-33.867, 151.206));
    });
    Style s = new Style();
    s.setFgColor(0xff0000);
    s.setBgTransparency(0);
    FontImage markerImg = FontImage.createMaterial(FontImage.MATERIAL_PLACE, s, 3);
    Button btnAddMarker = new Button("Add Marker");
    btnAddMarker.addActionListener(e -> {
        cnt.setCameraPosition(new Coord(41.889, -87.622));
        cnt.addMarker(EncodedImage.createFromImage(markerImg, false), cnt.getCameraPosition(), "Hi marker", "Optional long description", new ActionListener() {

            public void actionPerformed(ActionEvent evt) {
                System.out.println("Bounding box is " + cnt.getBoundingBox());
                ToastBar.showMessage("You clicked the marker", FontImage.MATERIAL_PLACE);
            }
        });
    });
    Button btnAddPath = new Button("Add Path");
    btnAddPath.addActionListener(e -> {
        cnt.addPath(cnt.getCameraPosition(), // Sydney
        new Coord(-33.866, 151.195), // Fiji
        new Coord(-18.142, 178.431), // Hawaii
        new Coord(21.291, -157.821), // Mountain View
        new Coord(37.423, -122.091));
    });
    Button panTo = new Button("Pan To");
    panTo.addActionListener(e -> {
        // bounds.extend(new google.maps.LatLng('66.057878', '-22.579047')); // Iceland
        // bounds.extend(new google.maps.LatLng('37.961952', '43.878878')); // Turkey
        Coord c1 = new Coord(49.0986192, -122.6764454);
        Coord c2 = new Coord(49.2577142, -123.1941149);
        // Coord center = new Coord(c1.getLatitude()/2 +  c2.getLatitude() / 2, c1.getLongitude()/2 + c2.getLongitude()/2 );
        Coord center = new Coord(49.1110928, -122.9414646);
        float zoom = cnt.getZoom();
        boolean[] finished = new boolean[1];
        cnt.addMapListener(new MapListener() {

            @Override
            public void mapPositionUpdated(Component source, int zoom, Coord c) {
                if (Math.abs(c.getLatitude() - center.getLatitude()) > .001 || Math.abs(c.getLongitude() - center.getLongitude()) > .001) {
                    return;
                }
                finished[0] = true;
                synchronized (finished) {
                    final MapListener fthis = this;
                    Display.getInstance().callSerially(() -> {
                        cnt.removeMapListener(fthis);
                    });
                    finished.notify();
                }
            }
        });
        cnt.zoom(center, (int) zoom);
        while (!finished[0]) {
            Display.getInstance().invokeAndBlock(() -> {
                while (!finished[0]) {
                    Util.wait(finished, 100);
                }
            });
        }
        BoundingBox box = cnt.getBoundingBox();
        if (!box.contains(c1) || !box.contains(c2)) {
            while (!box.contains(c1) || !box.contains(c2)) {
                if (!box.contains(c1)) {
                    System.out.println("Box " + box + " doesn't contain " + c1);
                }
                if (!box.contains(c1)) {
                    System.out.println("Box " + box + " doesn't contain " + c2);
                }
                zoom -= 1;
                final boolean[] done = new boolean[1];
                final int fzoom = (int) zoom;
                cnt.addMapListener(new MapListener() {

                    @Override
                    public void mapPositionUpdated(Component source, int zm, Coord center) {
                        if (zm == fzoom) {
                            final MapListener fthis = this;
                            Display.getInstance().callSerially(() -> {
                                cnt.removeMapListener(fthis);
                            });
                            done[0] = true;
                            synchronized (done) {
                                done.notify();
                            }
                        }
                    }
                });
                cnt.zoom(center, (int) zoom);
                while (!done[0]) {
                    Display.getInstance().invokeAndBlock(() -> {
                        while (!done[0]) {
                            Util.wait(done, 100);
                        }
                    });
                }
                box = cnt.getBoundingBox();
                System.out.println("Zoom now " + zoom);
            }
        } else if (box.contains(c1) && box.contains(c2)) {
            while (box.contains(c1) && box.contains(c2)) {
                zoom += 1;
                final boolean[] done = new boolean[1];
                final int fzoom = (int) zoom;
                cnt.addMapListener(new MapListener() {

                    public void mapPositionUpdated(Component source, int zm, Coord center) {
                        if (zm == fzoom) {
                            final MapListener fthis = this;
                            Display.getInstance().callSerially(() -> {
                                cnt.removeMapListener(fthis);
                            });
                            done[0] = true;
                            synchronized (done) {
                                done.notify();
                            }
                        }
                    }
                });
                cnt.zoom(center, (int) zoom);
                while (!done[0]) {
                    Display.getInstance().invokeAndBlock(() -> {
                        while (!done[0]) {
                            Util.wait(done, 100);
                        }
                    });
                }
                box = cnt.getBoundingBox();
            }
            zoom -= 1;
            cnt.zoom(center, (int) zoom);
            cnt.addTapListener(null);
        }
    });
    Button testCoordPositions = $(new Button("Test Coords")).addActionListener(e -> {
        Coord topLeft = cnt.getCoordAtPosition(0, 0);
        System.out.println("Top Left is " + topLeft + " -> " + cnt.getScreenCoordinate(topLeft) + " Should be (0,0)");
        Coord bottomRight = cnt.getCoordAtPosition(cnt.getWidth(), cnt.getHeight());
        System.out.println("Bottom right is " + bottomRight + " -> " + cnt.getScreenCoordinate(bottomRight) + " Should be " + cnt.getWidth() + ", " + cnt.getHeight());
        Coord bottomLeft = cnt.getCoordAtPosition(0, cnt.getHeight());
        System.out.println("Bottom Left is " + bottomLeft + " -> " + cnt.getScreenCoordinate(bottomLeft) + " Should be 0, " + cnt.getHeight());
        Coord topRight = cnt.getCoordAtPosition(cnt.getWidth(), 0);
        System.out.println("Top right is " + topRight + " -> " + cnt.getScreenCoordinate(topRight) + " Should be " + cnt.getWidth() + ", 0");
        Coord center = cnt.getCoordAtPosition(cnt.getWidth() / 2, cnt.getHeight() / 2);
        System.out.println("Center is " + center + " -> " + cnt.getScreenCoordinate(center) + ", should be " + (cnt.getWidth() / 2) + ", " + (cnt.getHeight() / 2));
        EncodedImage encImg = EncodedImage.createFromImage(markerImg, false);
        cnt.addMarker(encImg, topLeft, "Top Left", "Top Left", null);
        cnt.addMarker(encImg, topRight, "Top Right", "Top Right", null);
        cnt.addMarker(encImg, bottomRight, "Bottom Right", "Bottom Right", null);
        cnt.addMarker(encImg, bottomLeft, "Bottom Left", "Bottom Left", null);
        cnt.addMarker(encImg, center, "Center", "Center", null);
    }).asComponent(Button.class);
    Button toggleTopMargin = $(new Button("Toggle Margin")).addActionListener(e -> {
        int marginTop = $(cnt).getStyle().getMarginTop();
        if (marginTop < Display.getInstance().getDisplayHeight() / 3) {
            $(cnt).selectAllStyles().setMargin(Display.getInstance().getDisplayHeight() / 3, 0, 0, 0);
        } else {
            $(cnt).selectAllStyles().setMargin(0, 0, 0, 0);
        }
        $(cnt).getComponentForm().revalidate();
    }).asComponent(Button.class);
    Button btnClearAll = new Button("Clear All");
    btnClearAll.addActionListener(e -> {
        cnt.clearMapLayers();
    });
    MapObject mo = cnt.addMarker(EncodedImage.createFromImage(markerImg, false), new Coord(-33.866, 151.195), "test", "test", e -> {
        System.out.println("Marker clicked");
        cnt.removeMapObject(sydney);
    });
    sydney = mo;
    System.out.println("MO is " + mo);
    mo = cnt.addMarker(EncodedImage.createFromImage(markerImg, false), new Coord(-18.142, 178.431), "test", "test", e -> {
        System.out.println("Marker clicked");
    });
    System.out.println("MO is " + mo);
    cnt.addTapListener(e -> {
        if (tapDisabled) {
            return;
        }
        tapDisabled = true;
        TextField enterName = new TextField();
        Container wrapper = BoxLayout.encloseY(new Label("Name:"), enterName);
        InteractionDialog dlg = new InteractionDialog("Add Marker");
        dlg.getContentPane().add(wrapper);
        enterName.setDoneListener(e2 -> {
            String txt = enterName.getText();
            cnt.addMarker(EncodedImage.createFromImage(markerImg, false), cnt.getCoordAtPosition(e.getX(), e.getY()), enterName.getText(), "", e3 -> {
                ToastBar.showMessage("You clicked " + txt, FontImage.MATERIAL_PLACE);
            });
            dlg.dispose();
            tapDisabled = false;
        });
        dlg.showPopupDialog(new Rectangle(e.getX(), e.getY(), 10, 10));
        enterName.startEditingAsync();
    });
    Button showNextForm = $(new Button("Next Form")).addActionListener(e -> {
        Form form = new Form("Hello World");
        Button b1 = $(new Button("B1")).addActionListener(e2 -> {
            ToastBar.showMessage("B1 was pressed", FontImage.MATERIAL_3D_ROTATION);
        }).asComponent(Button.class);
        Button back = $(new Button("Back")).addActionListener(e2 -> {
            hi.showBack();
        }).asComponent(Button.class);
        form.add(b1);
    }).asComponent(Button.class);
    FloatingActionButton nextForm = FloatingActionButton.createFAB(FontImage.MATERIAL_ACCESS_ALARM);
    nextForm.addActionListener(e -> {
        Form form = new Form("Hello World");
        Button b1 = $(new Button("B1")).addActionListener(e2 -> {
            ToastBar.showMessage("B1 was pressed", FontImage.MATERIAL_3D_ROTATION);
        }).asComponent(Button.class);
        Button back = $(new Button("Back")).addActionListener(e2 -> {
            hi.showBack();
        }).asComponent(Button.class);
        form.add(b1).add(back);
        form.show();
    });
    Container root = LayeredLayout.encloseIn(BorderLayout.center(nextForm.bindFabToContainer(cnt)), BorderLayout.south(FlowLayout.encloseBottom(panTo, testCoordPositions, toggleTopMargin, btnMoveCamera, btnAddMarker, btnAddPath, btnClearAll)));
    hi.add(BorderLayout.CENTER, root);
    hi.show();
}
Also used : Util(com.codename1.io.Util) BoxLayout(com.codename1.ui.layouts.BoxLayout) ActionEvent(com.codename1.ui.events.ActionEvent) LayeredLayout(com.codename1.ui.layouts.LayeredLayout) MapObject(com.codename1.googlemaps.MapContainer.MapObject) MapListener(com.codename1.maps.MapListener) Form(com.codename1.ui.Form) Container(com.codename1.ui.Container) BoundingBox(com.codename1.maps.BoundingBox) ComponentSelector.$(com.codename1.ui.ComponentSelector.$) TextField(com.codename1.ui.TextField) Display(com.codename1.ui.Display) FontImage(com.codename1.ui.FontImage) Button(com.codename1.ui.Button) Label(com.codename1.ui.Label) Component(com.codename1.ui.Component) Rectangle(com.codename1.ui.geom.Rectangle) EncodedImage(com.codename1.ui.EncodedImage) MapContainer(com.codename1.googlemaps.MapContainer) FlowLayout(com.codename1.ui.layouts.FlowLayout) Resources(com.codename1.ui.util.Resources) IOException(java.io.IOException) ActionListener(com.codename1.ui.events.ActionListener) BorderLayout(com.codename1.ui.layouts.BorderLayout) Style(com.codename1.ui.plaf.Style) Coord(com.codename1.maps.Coord) UIManager(com.codename1.ui.plaf.UIManager) ToastBar(com.codename1.components.ToastBar) FloatingActionButton(com.codename1.components.FloatingActionButton) SideMenuBar(com.codename1.ui.SideMenuBar) InteractionDialog(com.codename1.components.InteractionDialog) Form(com.codename1.ui.Form) ActionEvent(com.codename1.ui.events.ActionEvent) Label(com.codename1.ui.Label) Rectangle(com.codename1.ui.geom.Rectangle) MapContainer(com.codename1.googlemaps.MapContainer) InteractionDialog(com.codename1.components.InteractionDialog) Container(com.codename1.ui.Container) MapContainer(com.codename1.googlemaps.MapContainer) BorderLayout(com.codename1.ui.layouts.BorderLayout) Button(com.codename1.ui.Button) FloatingActionButton(com.codename1.components.FloatingActionButton) BoundingBox(com.codename1.maps.BoundingBox) Style(com.codename1.ui.plaf.Style) TextField(com.codename1.ui.TextField) FloatingActionButton(com.codename1.components.FloatingActionButton) Component(com.codename1.ui.Component) FontImage(com.codename1.ui.FontImage) MapObject(com.codename1.googlemaps.MapContainer.MapObject) EncodedImage(com.codename1.ui.EncodedImage) Coord(com.codename1.maps.Coord) ActionListener(com.codename1.ui.events.ActionListener) MapListener(com.codename1.maps.MapListener)

Aggregations

BorderLayout (com.codename1.ui.layouts.BorderLayout)64 ActionEvent (com.codename1.ui.events.ActionEvent)27 Container (com.codename1.ui.Container)21 Form (com.codename1.ui.Form)18 ActionListener (com.codename1.ui.events.ActionListener)18 Component (com.codename1.ui.Component)15 BoxLayout (com.codename1.ui.layouts.BoxLayout)14 Label (com.codename1.ui.Label)12 Button (com.codename1.ui.Button)10 IOException (java.io.IOException)9 Dialog (com.codename1.ui.Dialog)8 Hashtable (java.util.Hashtable)8 Command (com.codename1.ui.Command)6 TextArea (com.codename1.ui.TextArea)6 FlowLayout (com.codename1.ui.layouts.FlowLayout)6 LayeredLayout (com.codename1.ui.layouts.LayeredLayout)6 Vector (java.util.Vector)6 RadioButton (com.codename1.ui.RadioButton)5 Animation (com.codename1.ui.animations.Animation)4 Style (com.codename1.ui.plaf.Style)4