Search in sources :

Example 6 with Constraint

use of com.codename1.ui.validation.Constraint in project CodenameOne by codenameone.

the class TableLayout method removeLayoutComponent.

/**
 * {@inheritDoc}
 */
public void removeLayoutComponent(Component comp) {
    // reflow the table
    Vector comps = new Vector();
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < columns; c++) {
            if (tablePositions[r * columns + c] != null) {
                if (tablePositions[r * columns + c].parent != comp) {
                    comps.addElement(tablePositions[r * columns + c]);
                } else {
                    tablePositions[r * columns + c].parent = null;
                }
            }
            tablePositions[r * columns + c] = null;
        }
    }
    currentRow = 0;
    currentColumn = 0;
    int count = comps.size();
    for (int iter = 0; iter < count; iter++) {
        Constraint con = (Constraint) comps.elementAt(iter);
        if (con == H_SPAN_CONSTRAINT || con == V_SPAN_CONSTRAINT || con == VH_SPAN_CONSTRAINT) {
            continue;
        }
        Component c = con.parent;
        con.parent = null;
        addLayoutComponent(con, c, c.getParent());
    }
}
Also used : Component(com.codename1.ui.Component) Vector(java.util.Vector)

Example 7 with Constraint

use of com.codename1.ui.validation.Constraint in project CodenameOne by codenameone.

the class TableLayout method layoutContainer.

/**
 * {@inheritDoc}
 */
public void layoutContainer(Container parent) {
    try {
        verticalSpanningExists = false;
        horizontalSpanningExists = false;
        // column and row size in pixels
        Style s = parent.getStyle();
        int top = s.getPaddingTop();
        int left = s.getPaddingLeft(parent.isRTL());
        int bottom = s.getPaddingBottom();
        int right = s.getPaddingRight(parent.isRTL());
        boolean rtl = parent.isRTL();
        // compute columns width and X position
        int[] columnSizes = new int[columns];
        boolean[] modifableColumnSize = new boolean[columns];
        boolean[] growingColumnSize = new boolean[columns];
        columnPositions = new int[columns];
        int pWidth = parent.getLayoutWidth() - parent.getSideGap() - left - right;
        int cslen = columnSizes.length;
        int availableReminder = pWidth;
        int growingWidth = 0;
        boolean hasGrowingCols = false;
        int totalWidth = 0;
        int totalModifyablePixels = 0;
        for (int iter = 0; iter < cslen; iter++) {
            int[] psize = getColumnWidthPixels(iter, pWidth);
            columnSizes[iter] = psize[0];
            availableReminder -= columnSizes[iter];
            totalWidth += columnSizes[iter];
            if (psize[1] < 0) {
                modifableColumnSize[iter] = true;
                totalModifyablePixels += columnSizes[iter];
            }
            if (psize[1] < -1) {
                growingColumnSize[iter] = true;
                hasGrowingCols = true;
                growingWidth += columnSizes[iter];
            }
        }
        // If there is some space left and some "auto growing" columns, attribute them the availableReminder space
        if (hasGrowingCols && availableReminder > 0) {
            for (int iter = 0; iter < cslen; iter++) {
                if (growingColumnSize[iter]) {
                    int sp = (int) (((float) columnSizes[iter]) / ((float) growingWidth) * availableReminder);
                    columnSizes[iter] += sp;
                }
            }
        }
        // to correctly display all the components given their preferred width, truncate or shrink the table
        if (!parent.isScrollableX() && pWidth < totalWidth) {
            if (truncateHorizontally) {
                // TODO: see if this is actually necessary to recompute the column size for truncated columns as the drawer should already automatically clip components with pixels out of the drawing boundaries
                availableReminder = pWidth;
                for (int iter = 0; iter < cslen; iter++) {
                    columnSizes[iter] = Math.min(columnSizes[iter], Math.max(0, availableReminder));
                    availableReminder -= columnSizes[iter];
                }
            } else {
                // try to recalculate the columns width so they are distributed sensibly
                int totalPixelsToRemove = totalWidth - pWidth;
                int totalPixelsNecessary = totalModifyablePixels - totalPixelsToRemove;
                // Go over the modifyable columns and remove the right pixels according to the ratio
                for (int iter = 0; iter < cslen; iter++) {
                    if (modifableColumnSize[iter]) {
                        columnSizes[iter] = (int) (((float) columnSizes[iter]) / ((float) totalModifyablePixels) * totalPixelsNecessary);
                    }
                }
            }
        }
        // Compute X position
        int currentX = left;
        for (int iter = 0; iter < cslen; iter++) {
            if (rtl) {
                currentX += columnSizes[iter];
                columnPositions[iter] = pWidth - currentX;
            } else {
                columnPositions[iter] = currentX;
                currentX += columnSizes[iter];
            }
        }
        // Compute rows height and Y position
        int[] rowSizes = new int[rows];
        boolean[] modifableRowSize = new boolean[rows];
        boolean[] growingRowSize = new boolean[rows];
        rowPositions = new int[rows];
        int pHeight = parent.getLayoutHeight() - parent.getBottomGap() - top - bottom;
        int rlen = rowSizes.length;
        availableReminder = pHeight;
        int growingHeight = 0;
        boolean hasGrowingRows = false;
        int totalHeight = 0;
        totalModifyablePixels = 0;
        for (int iter = 0; iter < rlen; iter++) {
            int[] psize = getRowHeightPixels(iter, pHeight);
            rowSizes[iter] = psize[0];
            availableReminder -= rowSizes[iter];
            totalHeight += rowSizes[iter];
            if (psize[0] < 0) {
                modifableRowSize[iter] = true;
                totalModifyablePixels += rowSizes[iter];
            }
            if (psize[0] < -1) {
                growingRowSize[iter] = true;
                hasGrowingRows = true;
                growingHeight += rowSizes[iter];
            }
        }
        // If there is some space left and some "auto growing" rows, attribute them the availableReminder space
        if (hasGrowingRows && availableReminder > 0) {
            for (int iter = 0; iter < rlen; iter++) {
                if (growingRowSize[iter]) {
                    int sp = (int) (((float) rowSizes[iter]) / ((float) growingHeight) * availableReminder);
                    rowSizes[iter] += sp;
                }
            }
        }
        // to correctly display all the components given their preferred height, truncate or shrink the table
        if (!parent.isScrollableY() && pHeight < totalHeight) {
            if (truncateVertically) {
                // TODO: see if this is actually necessary to recompute the row size for truncated rows as the drawer should already automatically clip components with pixels out of the drawing boundaries
                availableReminder = pHeight;
                for (int iter = 0; iter < rlen; iter++) {
                    rowSizes[iter] = Math.min(rowSizes[iter], Math.max(0, availableReminder));
                    availableReminder -= rowSizes[iter];
                }
            } else {
                // try to recalculate the rows height so they are distributed sensibly
                int totalPixelsToRemove = totalHeight - pHeight;
                int totalPixelsNecessary = totalModifyablePixels - totalPixelsToRemove;
                // Go over the modifyable rows and remove the bottom pixels according to the ratio
                for (int iter = 0; iter < rlen; iter++) {
                    if (modifableRowSize[iter]) {
                        rowSizes[iter] = (int) (((float) rowSizes[iter]) / ((float) totalModifyablePixels) * totalPixelsNecessary);
                    }
                }
            }
        }
        // Compute Y position
        int currentY = top;
        for (int iter = 0; iter < rlen; iter++) {
            rowPositions[iter] = currentY;
            currentY += rowSizes[iter];
        }
        // Place each cell component
        int clen = columnSizes.length;
        for (int r = 0; r < rlen; r++) {
            for (int c = 0; c < clen; c++) {
                Constraint con = tablePositions[r * columns + c];
                int conX, conY, conW, conH;
                if (con != null && con != H_SPAN_CONSTRAINT && con != V_SPAN_CONSTRAINT && con != VH_SPAN_CONSTRAINT) {
                    Style componentStyle = con.parent.getStyle();
                    int leftMargin = componentStyle.getMarginLeft(parent.isRTL());
                    int topMargin = componentStyle.getMarginTop();
                    // conX = left + leftMargin + columnPositions[c]; // bugfix table with padding not drawn correctly
                    // conY = top + topMargin + rowPositions[r]; // bugfix table with padding not drawn correctly
                    conX = leftMargin + columnPositions[c];
                    conY = topMargin + rowPositions[r];
                    if (con.spanHorizontal > 1) {
                        horizontalSpanningExists = true;
                        int w = columnSizes[c];
                        for (int sh = 1; sh < con.spanHorizontal; sh++) {
                            w += columnSizes[Math.min(c + sh, columnSizes.length - 1)];
                        }
                        // for RTL we need to move the component to the side so spanning will work
                        if (rtl) {
                            int spanEndPos = c + con.spanHorizontal - 1;
                            if (spanEndPos < 0) {
                                spanEndPos = 0;
                            } else if (spanEndPos > clen - 1) {
                                spanEndPos = clen - 1;
                            }
                            conX = left + leftMargin + columnPositions[spanEndPos];
                        }
                        conW = w - leftMargin - componentStyle.getMarginRight(parent.isRTL());
                    } else {
                        conW = columnSizes[c] - leftMargin - componentStyle.getMarginRight(parent.isRTL());
                    }
                    if (con.spanVertical > 1) {
                        verticalSpanningExists = true;
                        int h = rowSizes[r];
                        for (int sv = 1; sv < con.spanVertical; sv++) {
                            h += rowSizes[Math.min(r + sv, rowSizes.length - 1)];
                        }
                        conH = h - topMargin - componentStyle.getMarginBottom();
                    } else {
                        conH = rowSizes[r] - topMargin - componentStyle.getMarginBottom();
                    }
                    placeComponent(rtl, con, conX, conY, conW, conH);
                }
            }
        }
    } catch (ArrayIndexOutOfBoundsException err) {
        Log.e(err);
    }
}
Also used : Style(com.codename1.ui.plaf.Style)

Example 8 with Constraint

use of com.codename1.ui.validation.Constraint in project CodenameOne by codenameone.

the class JavaSEPort method editString.

/**
 * @inheritDoc
 */
public void editString(final Component cmp, final int maxSize, final int constraint, String text, final int keyCode) {
    if (scrollWheeling) {
        return;
    }
    if (System.getProperty("TextCompatMode") != null) {
        editStringLegacy(cmp, maxSize, constraint, text, keyCode);
        return;
    }
    if (editingInProgress != null) {
        final String fText = text;
        editingInProgress.invokeAfter(new Runnable() {

            public void run() {
                CN.callSerially(new Runnable() {

                    public void run() {
                        editString(cmp, maxSize, constraint, fText, keyCode);
                    }
                });
            }
        });
        editingInProgress.endEditing();
        return;
    }
    // a workaround to fix an issue where the previous Text Component wasn't removed properly.
    // java.awt.Component [] cmps = canvas.getComponents();
    // for (int i = 0; i < cmps.length; i++) {
    // java.awt.Component cmp1 = cmps[i];
    // if(cmp1 instanceof JScrollPane || cmp1 instanceof javax.swing.text.JTextComponent){
    // canvas.remove(cmp1);
    // }
    // }
    checkEDT();
    class Repainter {

        JComponent jcmp;

        javax.swing.border.Border origBorder;

        Repainter(JComponent jcmp) {
            this.jcmp = jcmp;
        }

        void repaint(long tm, int x, int y, int width, int height) {
            boolean oldShowEdtWarnings = showEDTWarnings;
            showEDTWarnings = false;
            // cmp.getSelectedStyle().getPadding(Component.TOP);
            int marginTop = 0;
            // cmp.getSelectedStyle().getPadding(Component.LEFT);
            int marginLeft = 0;
            // cmp.getSelectedStyle().getPadding(Component.RIGHT);
            int marginRight = 0;
            // cmp.getSelectedStyle().getPadding(Component.BOTTOM);
            int marginBottom = 0;
            int paddingTop = Math.round(cmp.getSelectedStyle().getPadding(Component.TOP) * zoomLevel);
            int paddingLeft = Math.round(cmp.getSelectedStyle().getPadding(Component.LEFT) * zoomLevel);
            int paddingRight = Math.round(cmp.getSelectedStyle().getPadding(Component.RIGHT) * zoomLevel);
            int paddingBottom = Math.round(cmp.getSelectedStyle().getPadding(Component.BOTTOM) * zoomLevel);
            Rectangle bounds;
            if (getSkin() != null) {
                bounds = new Rectangle((int) ((cmp.getAbsoluteX() + cmp.getScrollX() + getScreenCoordinates().x + canvas.x + marginLeft) * zoomLevel), (int) ((cmp.getAbsoluteY() + cmp.getScrollY() + getScreenCoordinates().y + canvas.y + marginTop) * zoomLevel), (int) ((cmp.getWidth() - marginLeft - marginRight) * zoomLevel), (int) ((cmp.getHeight() - marginTop - marginBottom) * zoomLevel));
            } else {
                bounds = new Rectangle(cmp.getAbsoluteX() + cmp.getScrollX() + marginLeft, cmp.getAbsoluteY() + cmp.getScrollY() + marginTop, cmp.getWidth() - marginRight - marginLeft, cmp.getHeight() - marginTop - marginBottom);
            }
            if (!jcmp.getBounds().equals(bounds)) {
                jcmp.setBounds(bounds);
                if (origBorder == null) {
                    origBorder = jcmp.getBorder();
                }
                // jcmp.setBorder(BorderFactory.createCompoundBorder(
                // origBorder,
                // BorderFactory.createEmptyBorder(paddingTop, paddingLeft, paddingBottom, paddingRight))
                // );
                jcmp.setBorder(BorderFactory.createEmptyBorder(paddingTop, paddingLeft, paddingBottom, paddingRight));
            }
            showEDTWarnings = oldShowEdtWarnings;
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    cmp.repaint();
                }
            });
        }
    }
    javax.swing.text.JTextComponent swingT;
    if (((com.codename1.ui.TextArea) cmp).isSingleLineTextArea()) {
        JTextComponent t;
        if ((constraint & TextArea.PASSWORD) == TextArea.PASSWORD) {
            t = new JPasswordField() {

                Repainter repainter = new Repainter(this);

                @Override
                public void repaint(long tm, int x, int y, int width, int height) {
                    if (repainter != null) {
                        repainter.repaint(tm, x, y, width, height);
                    }
                }
            };
        } else {
            t = new JTextField() {

                Repainter repainter = new Repainter(this);

                @Override
                public void repaint(long tm, int x, int y, int width, int height) {
                    if (repainter != null) {
                        repainter.repaint(tm, x, y, width, height);
                    }
                }
            };
        /*
                ((JTextField)t).addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if (cmp instanceof com.codename1.ui.TextField) {
                            final com.codename1.ui.TextField tf = (com.codename1.ui.TextField)cmp;
                            if (tf.getDoneListener() != null) {
                                Display.getInstance().callSerially(new Runnable() {
                                    public void run() {
                                        if (tf.getDoneListener() != null) {
                                            tf.fireDoneEvent();
                                        }
                                    }
                                });
                            }
                        }
                    }
                    
                });
                */
        }
        swingT = t;
        textCmp = swingT;
    } else {
        // Forward references so that we can access the scroll pane and its
        // repainter from inside the JTextArea.
        final Repainter[] fRepainter = new Repainter[1];
        final JScrollPane[] fPane = new JScrollPane[1];
        final com.codename1.ui.TextArea ta = (com.codename1.ui.TextArea) cmp;
        JTextArea t = new JTextArea() {

            @Override
            public void repaint(long tm, int x, int y, int width, int height) {
                // enough.
                if (fRepainter[0] != null && fPane[0] != null) {
                    Point p = SwingUtilities.convertPoint(this, x, y, fPane[0]);
                    fRepainter[0].repaint(tm, p.x, p.y, width, height);
                }
            }
        };
        t.setWrapStyleWord(true);
        t.setLineWrap(true);
        swingT = t;
        JScrollPane pane = new JScrollPane(swingT) {

            Repainter repainter = new Repainter(this);

            {
                fRepainter[0] = repainter;
            }

            @Override
            public void repaint(long tm, int x, int y, int width, int height) {
                if (repainter != null) {
                    repainter.repaint(tm, x, y, width, height);
                }
            }
        };
        fPane[0] = pane;
        if (ta.isGrowByContent()) {
            pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        }
        pane.setBorder(null);
        pane.setOpaque(false);
        pane.getViewport().setOpaque(false);
        // Without these scrollbars, it seems terribly difficult
        // to work with TextAreas that contain more text than can fit.
        // Commenting these out for better usability - at least on OS X.
        // pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
        // pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        textCmp = pane;
    }
    if (cmp.isRTL()) {
        textCmp.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    }
    DefaultCaret caret = (DefaultCaret) swingT.getCaret();
    caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
    swingT.setFocusTraversalKeysEnabled(false);
    TextEditUtil.setCurrentEditComponent(cmp);
    final javax.swing.text.JTextComponent txt = swingT;
    txt.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyPressed(KeyEvent e) {
        }

        @Override
        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_TAB) {
                if (e.isShiftDown()) {
                    TextEditUtil.editPrevTextArea();
                } else {
                    TextEditUtil.editNextTextArea();
                }
            }
        }
    });
    // swingT.setBorder(null);
    swingT.setOpaque(false);
    swingT.setForeground(new Color(cmp.getUnselectedStyle().getFgColor()));
    swingT.setCaretColor(new Color(cmp.getUnselectedStyle().getFgColor()));
    final javax.swing.text.JTextComponent tf = swingT;
    if (keyCode > 0) {
        text += ((char) keyCode);
        setText(tf, text);
        setCaretPosition(tf, text.length());
        if (cmp instanceof com.codename1.ui.TextField) {
            ((com.codename1.ui.TextField) cmp).setText(getText(tf));
        }
    } else {
        setText(tf, text);
    }
    textCmp.setBorder(null);
    textCmp.setOpaque(false);
    canvas.add(textCmp);
    int marginTop = cmp.getSelectedStyle().getPadding(Component.TOP);
    int marginLeft = cmp.getSelectedStyle().getPadding(Component.LEFT);
    int marginRight = cmp.getSelectedStyle().getPadding(Component.RIGHT);
    int marginBottom = cmp.getSelectedStyle().getPadding(Component.BOTTOM);
    if (getSkin() != null) {
        textCmp.setBounds((int) ((cmp.getAbsoluteX() + cmp.getScrollX() + getScreenCoordinates().x + canvas.x + marginLeft) * zoomLevel), (int) ((cmp.getAbsoluteY() + cmp.getScrollY() + getScreenCoordinates().y + canvas.y + marginTop) * zoomLevel), (int) ((cmp.getWidth() - marginLeft - marginRight) * zoomLevel), (int) ((cmp.getHeight() - marginTop - marginBottom) * zoomLevel));
        // System.out.println("Set bounds to "+textCmp.getBounds());
        java.awt.Font f = font(cmp.getStyle().getFont().getNativeFont());
        tf.setFont(f.deriveFont(f.getSize2D() * zoomLevel));
    } else {
        textCmp.setBounds(cmp.getAbsoluteX() + cmp.getScrollX() + marginLeft, cmp.getAbsoluteY() + cmp.getScrollY() + marginTop, cmp.getWidth() - marginRight - marginLeft, cmp.getHeight() - marginTop - marginBottom);
        // System.out.println("Set bounds to "+textCmp.getBounds());
        tf.setFont(font(cmp.getStyle().getFont().getNativeFont()));
    }
    if (tf instanceof JPasswordField && tf.getFont() != null && tf.getFont().getFontName().contains("Roboto")) {
        java.awt.Font fallback = new java.awt.Font(java.awt.Font.SANS_SERIF, java.awt.Font.PLAIN, tf.getFont().getSize());
        tf.setFont(fallback);
    }
    setCaretPosition(tf, getText(tf).length());
    // Windows Tablet Show Virtual Keyboard
    // REf https://stackoverflow.com/a/25783041/2935174
    final String sysroot = System.getenv("SystemRoot");
    String tabTipExe = "C:\\Program Files\\Common Files\\microsoft shared\\ink\\TabTip.exe";
    if (exposeFilesystem) {
        final boolean useTabTip = "tabtip".equalsIgnoreCase(Display.getInstance().getProperty("javase.win.vkb", "tabtip"));
        if (new File(tabTipExe).exists()) {
            try {
                if (useTabTip) {
                    // System.out.println("Opening TabTip");
                    ProcessBuilder pb = new ProcessBuilder("cmd", "/c", tabTipExe);
                    tabTipProcess = pb.start();
                } else {
                    // System.out.println("Opening OSK");
                    ProcessBuilder pb = new ProcessBuilder(sysroot + "/system32/osk.exe");
                    tabTipProcess = pb.start();
                }
            } catch (Exception e) {
                System.err.println("Failed to open VKB: " + e.getMessage());
            }
            tf.addFocusListener(new FocusListener() {

                @Override
                public void focusLost(FocusEvent arg0) {
                    // System.out.println("Lost focus...");
                    try {
                        if (tabTipProcess != null) {
                            tabTipProcess.destroy();
                        }
                    } catch (Exception ex) {
                    }
                    try {
                        if (useTabTip) {
                            Runtime.getRuntime().exec("cmd /c taskkill /IM TabTip.exe");
                        } else {
                            Runtime.getRuntime().exec("cmd /c taskkill /IM osk.exe");
                        }
                    } catch (IOException e) {
                        System.err.println("Problem closing VKB: " + e.getMessage());
                    }
                }

                @Override
                public void focusGained(FocusEvent arg0) {
                }
            });
        }
    }
    tf.requestFocus();
    tf.setSelectionStart(0);
    tf.setSelectionEnd(0);
    class Listener implements ActionListener, FocusListener, KeyListener, TextListener, Runnable, DocumentListener, EditingInProgress {

        private final JTextComponent textCmp;

        private final JComponent swingComponentToRemove;

        private boolean performed;

        private boolean fireDone;

        Listener(JTextComponent textCmp, JComponent swingComponentToRemove) {
            this.textCmp = textCmp;
            this.swingComponentToRemove = swingComponentToRemove;
            if (textCmp instanceof JTextArea) {
                if (((com.codename1.ui.TextArea) cmp).getDoneListener() != null) {
                    InputMap input = textCmp.getInputMap();
                    KeyStroke enter = KeyStroke.getKeyStroke("ENTER");
                    KeyStroke shiftEnter = KeyStroke.getKeyStroke("shift ENTER");
                    // input.get(enter)) = "insert-break"
                    input.put(shiftEnter, "insert-break");
                    input.put(enter, "text-submit");
                    ActionMap actions = textCmp.getActionMap();
                    actions.put("text-submit", new AbstractAction() {

                        @Override
                        public void actionPerformed(ActionEvent e) {
                            fireDone = true;
                            Listener.this.actionPerformed(null);
                        }
                    });
                }
            }
        }

        public void run() {
            while (swingComponentToRemove.getParent() != null) {
                synchronized (this) {
                    try {
                        wait(20);
                    } catch (InterruptedException ex) {
                    }
                }
            }
            EventQueue.invokeLater(new Runnable() {

                public void run() {
                    actionPerformed(null);
                }
            });
        }

        public void actionPerformed(ActionEvent e) {
            if (performed) {
                return;
            }
            performed = true;
            String txt = getText(tf);
            if (testRecorder != null) {
                testRecorder.editTextFieldCompleted(cmp, txt);
            }
            Display.getInstance().onEditingComplete(cmp, txt);
            if (e != null && cmp instanceof com.codename1.ui.TextField || fireDone) {
                final com.codename1.ui.TextArea cn1Tf = (com.codename1.ui.TextArea) cmp;
                if (cmp != null && cn1Tf.getDoneListener() != null) {
                    cn1Tf.fireDoneEvent();
                }
            }
            if (tf instanceof JTextField) {
                ((JTextField) tf).removeActionListener(this);
            }
            ((JTextComponent) tf).getDocument().removeDocumentListener(this);
            tf.removeFocusListener(this);
            canvas.remove(swingComponentToRemove);
            editingInProgress = null;
            currentlyEditingField = null;
            synchronized (this) {
                notify();
            }
            canvas.repaint();
            if (invokeAfter != null) {
                for (Runnable r : invokeAfter) {
                    r.run();
                }
                invokeAfter = null;
            }
        }

        public void focusGained(FocusEvent e) {
            setCaretPosition(tf, getText(tf).length());
        }

        public void focusLost(FocusEvent e) {
            actionPerformed(null);
        }

        public void keyTyped(KeyEvent e) {
            String t = getText(tf);
            if (t.length() >= ((TextArea) cmp).getMaxSize()) {
                e.consume();
            }
        }

        public void keyPressed(KeyEvent e) {
        }

        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                if (tf instanceof JTextField) {
                    actionPerformed(null);
                } else {
                    if (getCaretPosition(tf) >= getText(tf).length() - 1) {
                        actionPerformed(null);
                    }
                }
                return;
            }
            if (e.getKeyCode() == KeyEvent.VK_UP) {
                if (tf instanceof JTextField) {
                    actionPerformed(null);
                } else {
                    if (getCaretPosition(tf) <= 2) {
                        actionPerformed(null);
                    }
                }
                return;
            }
        }

        public void textValueChanged(TextEvent e) {
            // if (cmp instanceof com.codename1.ui.TextField) {
            updateText();
        // }
        }

        private void updateText() {
            Display.getInstance().callSerially(new Runnable() {

                public void run() {
                    // if(cmp instanceof com.codename1.ui.TextField) {
                    ((com.codename1.ui.TextArea) cmp).setText(getText(tf));
                // }
                }
            });
        }

        public void insertUpdate(DocumentEvent e) {
            updateText();
        }

        public void removeUpdate(DocumentEvent e) {
            updateText();
        }

        public void changedUpdate(DocumentEvent e) {
            updateText();
        }

        private ArrayList<Runnable> invokeAfter;

        @Override
        public void invokeAfter(Runnable r) {
            if (invokeAfter == null) {
                invokeAfter = new ArrayList<Runnable>();
            }
            invokeAfter.add(r);
        }

        @Override
        public void endEditing() {
            if (!EventQueue.isDispatchThread()) {
                EventQueue.invokeLater(new Runnable() {

                    public void run() {
                        endEditing();
                    }
                });
                return;
            }
            actionPerformed(null);
        }
    }
    ;
    final Listener l = new Listener(tf, textCmp);
    if (tf instanceof JTextField) {
        ((JTextField) tf).addActionListener(l);
    }
    ((JTextComponent) tf).getDocument().addDocumentListener(l);
    tf.addKeyListener(l);
    tf.addFocusListener(l);
    if (simulateAndroidKeyboard) {
        java.util.Timer t = new java.util.Timer();
        TimerTask tt = new TimerTask() {

            @Override
            public void run() {
                if (!Display.getInstance().isEdt()) {
                    Display.getInstance().callSerially(this);
                    return;
                }
                if (tf.getParent() != null) {
                    final int height = getScreenCoordinates().height;
                    JavaSEPort.this.sizeChanged(getScreenCoordinates().width, height / 2);
                    new UITimer(new Runnable() {

                        public void run() {
                            if (tf.getParent() != null) {
                                new UITimer(this).schedule(100, false, Display.getInstance().getCurrent());
                            } else {
                                JavaSEPort.this.sizeChanged(getScreenCoordinates().width, height);
                            }
                        }
                    }).schedule(100, false, Display.getInstance().getCurrent());
                }
            }
        };
        t.schedule(tt, 300);
    }
    editingInProgress = l;
    currentlyEditingField = cmp;
    new Thread(l).start();
}
Also used : TextArea(com.codename1.ui.TextArea) Rectangle(java.awt.Rectangle) JTextComponent(javax.swing.text.JTextComponent) Timer(java.util.Timer) AttributedString(java.text.AttributedString) DefaultCaret(javax.swing.text.DefaultCaret) FontRenderContext(java.awt.font.FontRenderContext) Color(java.awt.Color) java.util(java.util) EmptyBorder(javax.swing.border.EmptyBorder) TextArea(com.codename1.ui.TextArea) UITimer(com.codename1.ui.util.UITimer) Font(com.codename1.ui.Font) Point(java.awt.Point) JTextComponent(javax.swing.text.JTextComponent) Point(java.awt.Point) InvocationTargetException(java.lang.reflect.InvocationTargetException) SQLException(java.sql.SQLException) ParseException(java.text.ParseException) EOFException(java.io.EOFException) FontFormatException(java.awt.FontFormatException) LineUnavailableException(javax.sound.sampled.LineUnavailableException) javax.swing(javax.swing) UITimer(com.codename1.ui.util.UITimer) Timer(java.util.Timer) java.awt(java.awt)

Example 9 with Constraint

use of com.codename1.ui.validation.Constraint in project CodenameOne by codenameone.

the class JavaSEPort method editStringLegacy.

public void editStringLegacy(final Component cmp, int maxSize, int constraint, String text, int keyCode) {
    checkEDT();
    java.awt.Component awtTf;
    if (cmp instanceof com.codename1.ui.TextField) {
        java.awt.TextField t = new java.awt.TextField();
        awtTf = t;
        t.setSelectionEnd(0);
        t.setSelectionStart(0);
    } else {
        java.awt.TextArea t = new java.awt.TextArea("", 0, 0, java.awt.TextArea.SCROLLBARS_NONE);
        ;
        awtTf = t;
        t.setSelectionEnd(0);
        t.setSelectionStart(0);
    }
    final java.awt.Component tf = awtTf;
    if (keyCode > 0) {
        text += ((char) keyCode);
        setText(tf, text);
        setCaretPosition(tf, text.length());
        ((com.codename1.ui.TextField) cmp).setText(getText(tf));
    } else {
        setText(tf, text);
    }
    canvas.add(tf);
    if (getSkin() != null) {
        tf.setBounds((int) ((cmp.getAbsoluteX() + getScreenCoordinates().x + canvas.x) * zoomLevel), (int) ((cmp.getAbsoluteY() + getScreenCoordinates().y + canvas.y) * zoomLevel), (int) (cmp.getWidth() * zoomLevel), (int) (cmp.getHeight() * zoomLevel));
        java.awt.Font f = font(cmp.getStyle().getFont().getNativeFont());
        tf.setFont(f.deriveFont(f.getSize2D() * zoomLevel));
    } else {
        tf.setBounds(cmp.getAbsoluteX(), cmp.getAbsoluteY(), cmp.getWidth(), cmp.getHeight());
        tf.setFont(font(cmp.getStyle().getFont().getNativeFont()));
    }
    setCaretPosition(tf, getText(tf).length());
    tf.requestFocus();
    class Listener implements ActionListener, FocusListener, KeyListener, TextListener, Runnable {

        public synchronized void run() {
            while (tf.getParent() != null) {
                try {
                    wait(20);
                } catch (InterruptedException ex) {
                }
            }
        }

        public void actionPerformed(ActionEvent e) {
            String txt = getText(tf);
            if (testRecorder != null) {
                testRecorder.editTextFieldCompleted(cmp, txt);
            }
            Display.getInstance().onEditingComplete(cmp, txt);
            if (tf instanceof java.awt.TextField) {
                ((java.awt.TextField) tf).removeActionListener(this);
            }
            ((TextComponent) tf).removeTextListener(this);
            tf.removeFocusListener(this);
            canvas.remove(tf);
            synchronized (this) {
                notify();
            }
            canvas.repaint();
        }

        public void focusGained(FocusEvent e) {
            setCaretPosition(tf, getText(tf).length());
        }

        public void focusLost(FocusEvent e) {
            actionPerformed(null);
        }

        public void keyTyped(KeyEvent e) {
            String t = getText(tf);
            if (t.length() >= ((TextArea) cmp).getMaxSize()) {
                e.consume();
            }
        }

        public void keyPressed(KeyEvent e) {
        }

        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                if (tf instanceof java.awt.TextField) {
                    actionPerformed(null);
                } else {
                    if (getCaretPosition(tf) >= getText(tf).length() - 1) {
                        actionPerformed(null);
                    }
                }
                return;
            }
            if (e.getKeyCode() == KeyEvent.VK_UP) {
                if (tf instanceof java.awt.TextField) {
                    actionPerformed(null);
                } else {
                    if (getCaretPosition(tf) <= 2) {
                        actionPerformed(null);
                    }
                }
                return;
            }
        }

        public void textValueChanged(TextEvent e) {
            if (cmp instanceof com.codename1.ui.TextField) {
                ((com.codename1.ui.TextField) cmp).setText(getText(tf));
            }
        }
    }
    ;
    final Listener l = new Listener();
    if (tf instanceof java.awt.TextField) {
        ((java.awt.TextField) tf).addActionListener(l);
    }
    ((TextComponent) tf).addTextListener(l);
    tf.addKeyListener(l);
    tf.addFocusListener(l);
    if (simulateAndroidKeyboard) {
        java.util.Timer t = new java.util.Timer();
        TimerTask tt = new TimerTask() {

            @Override
            public void run() {
                if (!Display.getInstance().isEdt()) {
                    Display.getInstance().callSerially(this);
                    return;
                }
                if (tf.getParent() != null) {
                    final int height = getScreenCoordinates().height;
                    JavaSEPort.this.sizeChanged(getScreenCoordinates().width, height / 2);
                    new UITimer(new Runnable() {

                        public void run() {
                            if (tf.getParent() != null) {
                                new UITimer(this).schedule(100, false, Display.getInstance().getCurrent());
                            } else {
                                JavaSEPort.this.sizeChanged(getScreenCoordinates().width, height);
                            }
                        }
                    }).schedule(100, false, Display.getInstance().getCurrent());
                }
            }
        };
        t.schedule(tt, 300);
    }
    Display.getInstance().invokeAndBlock(l);
}
Also used : TextArea(com.codename1.ui.TextArea) UITimer(com.codename1.ui.util.UITimer) Timer(java.util.Timer) AttributedString(java.text.AttributedString) JTextComponent(javax.swing.text.JTextComponent) Point(java.awt.Point) java.util(java.util) UITimer(com.codename1.ui.util.UITimer) Timer(java.util.Timer) java.awt(java.awt)

Example 10 with Constraint

use of com.codename1.ui.validation.Constraint in project CodenameOne by codenameone.

the class BlackBerryImplementation method editString.

public void editString(final Component cmp, final int maxSize, final int constraint, final String text, int keyCode) {
    TextArea txtCmp = (TextArea) cmp;
    String edit = (String) txtCmp.getClientProperty("RIM.nativePopup");
    if (edit != null) {
        EditPopup editpop = new EditPopup(txtCmp, maxSize);
        editpop.startEdit();
    } else {
        nativeEdit(txtCmp, txtCmp.getMaxSize(), txtCmp.getConstraint(), txtCmp.getText(), keyCode);
    }
}
Also used : TextArea(com.codename1.ui.TextArea)

Aggregations

Component (com.codename1.ui.Component)7 TextArea (com.codename1.ui.TextArea)7 Container (com.codename1.ui.Container)5 Style (com.codename1.ui.plaf.Style)5 PeerComponent (com.codename1.ui.PeerComponent)3 BorderLayout (com.codename1.ui.layouts.BorderLayout)3 Inset (com.codename1.ui.layouts.LayeredLayout.LayeredLayoutConstraint.Inset)3 Point (java.awt.Point)3 java.util (java.util)3 Button (com.codename1.ui.Button)2 Form (com.codename1.ui.Form)2 Label (com.codename1.ui.Label)2 TextField (com.codename1.ui.TextField)2 ComponentAnimation (com.codename1.ui.animations.ComponentAnimation)2 Dimension (com.codename1.ui.geom.Dimension)2 BoxLayout (com.codename1.ui.layouts.BoxLayout)2 UITimer (com.codename1.ui.util.UITimer)2 java.awt (java.awt)2 AttributedString (java.text.AttributedString)2 Timer (java.util.Timer)2