Java Examples for javax.swing.text.DocumentFilter

The following java examples will help you to understand the usage of javax.swing.text.DocumentFilter. These source code samples are taken from different open source projects.

Example 1
Project: open-traffic-simulation-master  File: InputFilterUtility.java View source code
@Override
public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
    try {
        if (string.equals(".") && !fb.getDocument().getText(0, fb.getDocument().getLength()).contains(".")) {
            super.insertString(fb, offset, string, attr);
            return;
        }
        Double.parseDouble(string);
        super.insertString(fb, offset, string, attr);
    } catch (Exception e) {
        Toolkit.getDefaultToolkit().beep();
    }
}
Example 2
Project: UFOSGE-master  File: NumericFormattedTextField.java View source code
public void remove(DocumentFilter.FilterBypass fb, int offs, int length) throws BadLocationException {
    // System.out.println("[NumericFormattedDocumentFilter] remove()");
    String docText = fb.getDocument().getText(0, fb.getDocument().getLength());
    String newStr = docText.substring(0, offs) + docText.substring(offs + length);
    if (newStr.length() == 0) {
        // System.out.println("  : calling replace() instead.");
        fb.replace(0, docText.length(), "0", null);
        if (docText.length() == 0) {
            Toolkit.getDefaultToolkit().beep();
            Util.displayTooltip(field);
        }
        return;
    }
    long numericValue;
    if (!field.hasFocus()) {
        try {
            numericValue = ((Number) field.getFormatter().stringToValue(field.getText())).longValue();
            fb.remove(offs, length);
            return;
        } catch (ParseException e) {
            Toolkit.getDefaultToolkit().beep();
            Util.displayTooltip(field);
            return;
        }
    }
    try {
        numericValue = Long.parseLong(newStr);
        if (numericValue >= minValue && numericValue <= maxValue) {
            value = numericValue;
            fb.remove(offs, length);
        } else {
            Toolkit.getDefaultToolkit().beep();
            Util.displayTooltip(field);
        }
    } catch (NumberFormatException e) {
        Toolkit.getDefaultToolkit().beep();
        Util.displayTooltip(field);
    }
}
Example 3
Project: many-ql-master  File: NumberBox.java View source code
private PlainDocument getPlainDocument() {
    PlainDocument plainDocument = new PlainDocument();
    plainDocument.setDocumentFilter(new DocumentFilter() {

        @Override
        public void insertString(FilterBypass fb, int off, String str, AttributeSet attr) throws BadLocationException {
            // remove non-digits
            fb.insertString(off, str.replaceAll("\\D++", ""), attr);
        }

        @Override
        public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr) throws BadLocationException {
            // remove non-digits
            fb.replace(off, len, str.replaceAll("\\D++", ""), attr);
        }
    });
    return plainDocument;
}
Example 4
Project: fa15-ceg3120-master  File: NewContractorPane.java View source code
@Override
public void focusLost(FocusEvent ev) {
    // Verify email upon focusLostEvent
    String name = field.getName();
    AbstractDocument doc = (AbstractDocument) field.getDocument();
    DocumentFilter filt = doc.getDocumentFilter();
    if (name != null && field.getName().equals("email")) {
        if (filt instanceof DocumentEmailFilter) {
            try {
                ((DocumentEmailFilter) filt).setToFilter(true);
                String contents = doc.getText(0, doc.getLength());
                doc.remove(0, doc.getLength());
                doc.insertString(0, contents, null);
                ((DocumentEmailFilter) filt).setToFilter(false);
            } catch (BadLocationException e) {
                e.printStackTrace();
            }
        }
    }
}
Example 5
Project: jtheque-core-master  File: ConstraintManager.java View source code
/**
     * Configure a JTextField with the constraint.
     *
     * @param field     The field to configure.
     * @param fieldName The name of the field.
     */
public static void configure(JTextField field, String fieldName) {
    if (CONSTRAINTS.containsKey(fieldName) && CONSTRAINTS.get(fieldName).isLengthControlled()) {
        DocumentFilter filter = new DocumentLengthFilterAvert(CONSTRAINTS.get(fieldName).getMaxLength(), field);
        Document document = field.getDocument();
        ((AbstractDocument) document).setDocumentFilter(filter);
    }
}
Example 6
Project: gluu-opendj-master  File: TimeDocumentFilter.java View source code
/**
   * {@inheritDoc}
   */
public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException {
    String text = fb.getDocument().getText(offset, length);
    int index = text.indexOf(":");
    if (index == -1) {
        fb.remove(offset, length);
    } else {
        // index value is relative to offset
        if (index > 0) {
            fb.remove(offset, index);
        }
        if (index < length - 1) {
            fb.remove(offset + index + 1, length - index - 1);
        }
    }
    updateCaretPosition(fb);
}
Example 7
Project: OpenDJ-master  File: TimeDocumentFilter.java View source code
/** {@inheritDoc} */
public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException {
    String text = fb.getDocument().getText(offset, length);
    int index = text.indexOf(":");
    if (index == -1) {
        fb.remove(offset, length);
    } else {
        // index value is relative to offset
        if (index > 0) {
            fb.remove(offset, index);
        }
        if (index < length - 1) {
            fb.remove(offset + index + 1, length - index - 1);
        }
    }
    updateCaretPosition(fb);
}
Example 8
Project: JamVM-PH-master  File: AbstractDocument.java View source code
/**
   * Replaces a piece of content in this <code>Document</code> with
   * another piece of content.
   * 
   * <p>If a {@link DocumentFilter} is installed in this document, the
   * corresponding method of the filter object is called.</p>
   * 
   * <p>The method has no effect if <code>length</code> is zero (and
   * only zero) and, at the same time, <code>text</code> is
   * <code>null</code> or has zero length.</p>
   *
   * @param offset the start offset of the fragment to be removed
   * @param length the length of the fragment to be removed
   * @param text the text to replace the content with
   * @param attributes the text attributes to assign to the new content
   *
   * @throws BadLocationException if <code>offset</code> or
   *         <code>offset + length</code> or invalid locations within this
   *         document
   *
   * @since 1.4
   */
public void replace(int offset, int length, String text, AttributeSet attributes) throws BadLocationException {
    // Bail out if we have a bogus replacement (Behavior observed in RI).
    if (length == 0 && (text == null || text.length() == 0))
        return;
    writeLock();
    try {
        if (documentFilter == null) {
            // It is important to call the methods which again do the checks
            // of the arguments and the DocumentFilter because subclasses may
            // have overridden these methods and provide crucial behavior
            // which would be skipped if we call the non-checking variants.
            // An example for this is PlainDocument where insertString can
            // provide a filtering of newlines.
            remove(offset, length);
            insertString(offset, text, attributes);
        } else
            documentFilter.replace(getBypass(), offset, length, text, attributes);
    } finally {
        writeUnlock();
    }
}
Example 9
Project: CodenameOne-master  File: BorderEditor.java View source code
public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
    if (fb.getDocument().getLength() + string.length() > 6) {
        return;
    }
    for (int iter = 0; iter < string.length(); iter++) {
        char c = string.charAt(iter);
        if (!(Character.isDigit(c) || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'))) {
            return;
        }
    }
    fb.insertString(offset, string, attr);
    updateBorder(false);
}
Example 10
Project: lwuit-master  File: BorderEditor.java View source code
public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
    if (fb.getDocument().getLength() + string.length() > 6) {
        return;
    }
    for (int iter = 0; iter < string.length(); iter++) {
        char c = string.charAt(iter);
        if (!(Character.isDigit(c) || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'))) {
            return;
        }
    }
    fb.insertString(offset, string, attr);
    updateBorder(false);
}
Example 11
Project: voxels-master  File: NumberBox.java View source code
@Override
public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
    StringBuilder sb = new StringBuilder();
    sb.append(fb.getDocument().getText(0, fb.getDocument().getLength()));
    sb.insert(offset, text);
    if (invalidContent(sb.toString()))
        return;
    fb.insertString(offset, text, attr);
    currentString = sb.toString();
    notifyListeners();
}
Example 12
Project: nbruby-master  File: PluginProgressPanel.java View source code
private void attach(JTextComponent textComponent) {
    this.textComponent = textComponent;
    textComponent.addKeyListener(this);
    textComponent.getDocument().addDocumentListener(this);
    if (textComponent.getDocument() instanceof AbstractDocument) {
        ((AbstractDocument) textComponent.getDocument()).setDocumentFilter(new DocumentFilter() {

            @Override
            public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
                if (offset >= startOffset) {
                    super.insertString(fb, offset, string, attr);
                }
            }

            @Override
            public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
                if (offset >= startOffset) {
                    super.remove(fb, offset, length);
                }
            }

            @Override
            public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
                if (offset >= startOffset) {
                    super.replace(fb, offset, length, text, attrs);
                }
            }
        });
    }
}
Example 13
Project: bither-desktop-java-master  File: Numbers.java View source code
/**
     * @param decimalFormat The decimal format appropriate for this locale
     * @return A number formatter that is locale-aware and configured for doubles
     */
private static NumberFormatter newNumberFormatter(final DecimalFormat decimalFormat, final int maxEditLength) {
    // Create the number formatter with local-sensitive adjustments
    NumberFormatter displayFormatter = new NumberFormatter(decimalFormat) {

        // The max input length for the given symbol
        DocumentFilter documentFilter = new DocumentMaxLengthFilter(maxEditLength);

        @Override
        public Object stringToValue(String text) throws ParseException {
            // RU locale (and others) requires a non-breaking space for a grouping separator
            text = text.replace(' ', ' ');
            return super.stringToValue(text);
        }

        @Override
        protected DocumentFilter getDocumentFilter() {
            return documentFilter;
        }
    };
    // Use a BigDecimal for widest value handling
    displayFormatter.setValueClass(BigDecimal.class);
    return displayFormatter;
}
Example 14
Project: classpath-doctor-master  File: ClassPathPanel.java View source code
private JTextArea buildTextComponent() {
    JTextArea result = new JTextArea();
    PlainDocument doc = new PlainDocument();
    doc.setDocumentFilter(new DocumentFilter() {

        @Override
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
            if ("\n".equals(string)) {
                // don't insert any new lines
                return;
            }
            super.insertString(fb, offset, string, attr);
        }

        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            if (length > 0) {
                fb.remove(offset, length);
            }
            insertString(fb, offset, text, null);
        }
    });
    result.setDocument(doc);
    result.setWrapStyleWord(true);
    result.setLineWrap(true);
    return result;
}
Example 15
Project: multibit-hd-master  File: Numbers.java View source code
/**
   * @param decimalFormat The decimal format appropriate for this locale
   *
   * @return A number formatter that is locale-aware and configured for doubles
   */
private static NumberFormatter newNumberFormatter(final DecimalFormat decimalFormat, final int maxEditLength) {
    // Create the number formatter with local-sensitive adjustments
    NumberFormatter displayFormatter = new NumberFormatter(decimalFormat) {

        // The max input length for the given symbol
        DocumentFilter documentFilter = new DocumentMaxLengthFilter(maxEditLength);

        @Override
        public Object stringToValue(String text) throws ParseException {
            // RU locale (and others) requires a non-breaking space for a grouping separator
            text = text.replace(' ', ' ');
            return super.stringToValue(text);
        }

        @Override
        protected DocumentFilter getDocumentFilter() {
            return documentFilter;
        }
    };
    // Use a BigDecimal for widest value handling
    displayFormatter.setValueClass(BigDecimal.class);
    return displayFormatter;
}
Example 16
Project: ProjectLibre-master  File: FixedSizeFilter.java View source code
// This method is called when characters in the document are replace with other characters
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String str, AttributeSet attrs) throws BadLocationException {
    int newLength = fb.getDocument().getLength() - length + (str == null ? 0 : str.length());
    int overflow = newLength - maxSize;
    if (overflow > 0) {
        str = str.substring(0, str.length() - overflow);
        newLength = fb.getDocument().getLength() - length + (str == null ? 0 : str.length());
    }
    if (newLength <= maxSize) {
        fb.replace(offset, length, str, attrs);
    } else {
        throw new BadLocationException("New characters exceeds max size of document", offset);
    }
}
Example 17
Project: vhdllab-master  File: TextEditor.java View source code
@Override
protected JComponent doInitWithoutData() {
    textPane = new CustomJTextPane(this);
    wrapInScrollPane = false;
    JScrollPane jsp = new JScrollPane(textPane);
    LineNumbers.createInstance(textPane, jsp, 30);
    Document document = textPane.getDocument();
    if (document instanceof AbstractDocument) {
        ((AbstractDocument) document).setDocumentFilter(new DocumentFilter() {

            @Override
            public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
                if (text != null && (text.length() - length) > 10 && !text.equals(CustomJTextPane.getClipboardText()) && !textIsBlank(text)) {
                    informPastingIsDisabled();
                } else {
                    super.replace(fb, offset, length, text, attrs);
                }
            }

            private boolean textIsBlank(String text) {
                if (text == null)
                    return true;
                for (char c : text.toCharArray()) {
                    switch(c) {
                        case ' ':
                            break;
                        case '\t':
                            break;
                        case '\r':
                            break;
                        case '\n':
                            break;
                        default:
                            return false;
                    }
                }
                return true;
            }

            private void informPastingIsDisabled() {
                JFrame frame = Application.instance().getActiveWindow().getControl();
                JOptionPane.showMessageDialog(frame, "Pasting text from outside of vhdllab is disabled!", "Paste text", JOptionPane.INFORMATION_MESSAGE);
            }
        });
    }
    textPane.addCaretListener(this);
    return jsp;
}
Example 18
Project: discobot-master  File: StructuredSyntaxDocumentFilter.java View source code
/**
     * Remove a string from the document, and then parse it if the parser has been
     * set.
     *
     * @param fb
     * @param offset
     * @param length
     * @throws BadLocationException
     */
public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException {
    // does not get done properly, so first replace and remove after parsing
    if (offset == 0 && length != fb.getDocument().getLength()) {
        fb.replace(0, length, "\n", lexer.defaultStyle);
        // start on either side of the removed text
        parseDocument(offset, 2);
        fb.remove(offset, 1);
    } else {
        fb.remove(offset, length);
        // start on either side of the removed text
        if (offset + 1 < fb.getDocument().getLength()) {
            parseDocument(offset, 1);
        } else if (offset - 1 > 0) {
            parseDocument(offset - 1, 1);
        } else {
            // empty text
            mlTextRunSet.clear();
        }
    }
}
Example 19
Project: groovy-core-master  File: StructuredSyntaxDocumentFilter.java View source code
/**
     * Remove a string from the document, and then parse it if the parser has been
     * set.
     *
     * @param fb
     * @param offset
     * @param length
     * @throws BadLocationException
     */
public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException {
    // does not get done properly, so first replace and remove after parsing
    if (offset == 0 && length != fb.getDocument().getLength()) {
        fb.replace(0, length, "\n", lexer.defaultStyle);
        // start on either side of the removed text
        parseDocument(offset, 2);
        fb.remove(offset, 1);
    } else {
        fb.remove(offset, length);
        // start on either side of the removed text
        if (offset + 1 < fb.getDocument().getLength()) {
            parseDocument(offset, 1);
        } else if (offset - 1 > 0) {
            parseDocument(offset - 1, 1);
        } else {
            // empty text
            mlTextRunSet.clear();
        }
    }
}
Example 20
Project: groovy-master  File: StructuredSyntaxDocumentFilter.java View source code
/**
     * Remove a string from the document, and then parse it if the parser has been
     * set.
     *
     * @param fb
     * @param offset
     * @param length
     * @throws BadLocationException
     */
public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException {
    // does not get done properly, so first replace and remove after parsing
    if (offset == 0 && length != fb.getDocument().getLength()) {
        fb.replace(0, length, "\n", lexer.defaultStyle);
        // start on either side of the removed text
        parseDocument(offset, 2);
        fb.remove(offset, 1);
    } else {
        fb.remove(offset, length);
        // start on either side of the removed text
        if (offset + 1 < fb.getDocument().getLength()) {
            parseDocument(offset, 1);
        } else if (offset - 1 > 0) {
            parseDocument(offset - 1, 1);
        } else {
            // empty text
            mlTextRunSet.clear();
        }
    }
}
Example 21
Project: vassal-master  File: ServerConfigurer.java View source code
public Component getControls() {
    if (controls == null) {
        controls = new JPanel(new MigLayout());
        header = new JLabel(DISCONNECTED);
        //$NON-NLS-1$
        controls.add(header, "wrap");
        ButtonGroup group = new ButtonGroup();
        jabberButton = new JRadioButton(JABBER_BUTTON);
        jabberButton.addItemListener(new ItemListener() {

            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    noUpdate = true;
                    setValue(buildJabberProperties());
                    noUpdate = false;
                }
                jabberHostPrompt.setEnabled(jabberButton.isSelected());
                jabberHost.setEnabled(jabberButton.isSelected() && jabberHostPrompt.isSelected());
                jabberAccountName.setEnabled(jabberButton.isSelected());
                jabberPassword.setEnabled(jabberButton.isSelected());
                jabberAccountPrompt.setEnabled(jabberButton.isSelected());
                jabberPasswordPrompt.setEnabled(jabberButton.isSelected());
            }
        });
        //$NON-NLS-1$
        jabberAccountPrompt = new JLabel(Resources.getString("Server.account_name"));
        jabberAccountPrompt.setEnabled(false);
        jabberAccountName = new JTextField();
        jabberAccountName.setEnabled(false);
        //$NON-NLS-1$
        jabberPasswordPrompt = new JLabel(Resources.getString("Server.password"));
        jabberPasswordPrompt.setEnabled(false);
        jabberPassword = new JPasswordField();
        jabberPassword.setEnabled(false);
        //$NON-NLS-1$
        jabberHostPrompt = new JCheckBox(Resources.getString("Server.host"));
        jabberHostPrompt.setEnabled(false);
        jabberHost = new JTextField(18);
        jabberHost.setEnabled(false);
        jabberHostPrompt.addItemListener(new ItemListener() {

            public void itemStateChanged(ItemEvent e) {
                jabberHost.setEnabled(jabberHostPrompt.isSelected() && jabberButton.isSelected());
                docListener.changedUpdate(null);
            }
        });
        //$NON-NLS-1$
        jabberHost.setText(JabberClientFactory.DEFAULT_JABBER_HOST + ":" + JabberClientFactory.DEFAULT_JABBER_PORT);
        docListener = new DocumentListener() {

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

            private void updateValue() {
                noUpdate = true;
                setValue(buildJabberProperties());
                noUpdate = false;
            }

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

            public void removeUpdate(DocumentEvent e) {
                updateValue();
            }
        };
        ((AbstractDocument) jabberAccountName.getDocument()).setDocumentFilter(new DocumentFilter() {

            @Override
            public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
                if (text != null) {
                    super.replace(fb, offset, length, StringUtils.escapeNode(text).toLowerCase(), attrs);
                }
            }

            @Override
            public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
                if (string != null) {
                    super.insertString(fb, offset, StringUtils.escapeNode(string).toLowerCase(), attr);
                }
            }
        });
        jabberHost.getDocument().addDocumentListener(docListener);
        jabberAccountName.getDocument().addDocumentListener(docListener);
        jabberPassword.getDocument().addDocumentListener(docListener);
        // Disable Jabber server until next release
        if ("true".equals(System.getProperty("enableJabber"))) {
            //$NON-NLS-1$ //$NON-NLS-2$
            group.add(jabberButton);
            //$NON-NLS-1$
            controls.add(jabberButton, "wrap");
            //$NON-NLS-1$
            controls.add(jabberAccountPrompt, "gap 40");
            //$NON-NLS-1$
            controls.add(jabberAccountName, "wrap, growx");
            //$NON-NLS-1$
            controls.add(jabberPasswordPrompt, "gap 40");
            //$NON-NLS-1$
            controls.add(jabberPassword, "wrap, growx");
            //$NON-NLS-1$
            controls.add(jabberHostPrompt, "gap 40");
            //$NON-NLS-1$
            controls.add(jabberHost, "wrap, growx");
        }
        p2pButton = new JRadioButton(P2P_BUTTON);
        p2pButton.addItemListener(new ItemListener() {

            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    noUpdate = true;
                    setValue(buildPeerProperties());
                    noUpdate = false;
                }
            }
        });
        group.add(p2pButton);
        //$NON-NLS-1$
        controls.add(p2pButton, "wrap");
        legacyButton = new JRadioButton(LEGACY_BUTTON);
        legacyButton.addItemListener(new ItemListener() {

            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    noUpdate = true;
                    setValue(buildLegacyProperties());
                    noUpdate = false;
                }
            }
        });
        controls.add(legacyButton);
        group.add(legacyButton);
    }
    return controls;
}
Example 22
Project: LauncherV3-master  File: ModpackSelector.java View source code
private void initComponents() {
    setLayout(new BorderLayout());
    setBackground(LauncherFrame.COLOR_SELECTOR_BACK);
    setMaximumSize(new Dimension(287, getMaximumSize().height));
    JPanel header = new JPanel();
    header.setLayout(new GridBagLayout());
    header.setBorder(BorderFactory.createEmptyBorder(4, 8, 4, 4));
    header.setBackground(LauncherFrame.COLOR_SELECTOR_OPTION);
    add(header, BorderLayout.PAGE_START);
    filterContents = new WatermarkTextField(resources.getString("launcher.packselector.filter.hotfix"), LauncherFrame.COLOR_BLUE_DARKER);
    filterContents.setFont(resources.getFont(ResourceLoader.FONT_OPENSANS, 14));
    filterContents.setBorder(new RoundBorder(LauncherFrame.COLOR_BUTTON_BLUE, 1, 8));
    filterContents.setForeground(LauncherFrame.COLOR_BLUE);
    filterContents.setBackground(LauncherFrame.COLOR_FORMELEMENT_INTERNAL);
    filterContents.setSelectedTextColor(Color.black);
    filterContents.setSelectionColor(LauncherFrame.COLOR_BUTTON_BLUE);
    filterContents.setCaretColor(LauncherFrame.COLOR_BUTTON_BLUE);
    filterContents.setColumns(20);
    ((AbstractDocument) filterContents.getDocument()).setDocumentFilter(new DocumentFilter() {

        @Override
        public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
            if (fb.getDocument().getLength() + string.length() <= MAX_SEARCH_STRING) {
                fb.insertString(offset, string, attr);
            }
        }

        @Override
        public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException {
            fb.remove(offset, length);
        }

        @Override
        public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            int finalTextLength = (fb.getDocument().getLength() - length) + text.length();
            if (finalTextLength > MAX_SEARCH_STRING)
                text = text.substring(0, text.length() - (finalTextLength - MAX_SEARCH_STRING));
            fb.replace(offset, length, text, attrs);
        }
    });
    filterContents.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void insertUpdate(DocumentEvent e) {
            detectFilterChanges();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            detectFilterChanges();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            detectFilterChanges();
        }
    });
    header.add(filterContents, new GridBagConstraints(1, 0, 1, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(3, 0, 3, 0), 0, 12));
    widgetList = new JPanel();
    widgetList.setOpaque(false);
    widgetList.setLayout(new GridBagLayout());
    scrollPane = new JScrollPane(widgetList, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPane.setOpaque(false);
    scrollPane.setBorder(BorderFactory.createEmptyBorder());
    scrollPane.getViewport().setOpaque(false);
    scrollPane.getVerticalScrollBar().setUI(new SimpleScrollbarUI(LauncherFrame.COLOR_SCROLL_TRACK, LauncherFrame.COLOR_SCROLL_THUMB));
    scrollPane.getVerticalScrollBar().setPreferredSize(new Dimension(10, 10));
    scrollPane.getVerticalScrollBar().setUnitIncrement(12);
    add(scrollPane, BorderLayout.CENTER);
    widgetList.add(Box.createHorizontalStrut(294), new GridBagConstraints(0, 0, 1, 1, 1, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
    widgetList.add(Box.createGlue(), new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
}
Example 23
Project: mct-master  File: PlotBehaviorPanel.java View source code
@SuppressWarnings("serial")
private JTextField createPaddingTextField(AxisType axisType, AxisBounds bound) {
    final JFormattedTextField tField = new JFormattedTextField(new InternationalFormatter(NumberFormat.getIntegerInstance()) {

        protected DocumentFilter getDocumentFilter() {
            return filter;
        }

        private DocumentFilter filter = new PaddingFilter();
    });
    tField.setColumns(PADDING_COLUMNS);
    tField.setHorizontalAlignment(JTextField.RIGHT);
    if (bound.equals(AxisBounds.MIN)) {
        tField.setText(axisType.getMinimumDefaultPaddingAsText());
    } else {
        tField.setText(axisType.getMaximumDefaultPaddingAsText());
    }
    tField.addAncestorListener(new AncestorListener() {

        @Override
        public void ancestorAdded(AncestorEvent event) {
            tField.selectAll();
            tField.removeAncestorListener(this);
        }

        @Override
        public void ancestorMoved(AncestorEvent event) {
        }

        @Override
        public void ancestorRemoved(AncestorEvent event) {
        }
    });
    return tField;
}
Example 24
Project: jSite-master  File: ProjectPage.java View source code
/**
	 * Creates the information panel.
	 *
	 * @return The information panel
	 */
private JComponent createInformationPanel() {
    JPanel informationPanel = new JPanel(new BorderLayout(12, 12));
    JPanel informationTable = new JPanel(new GridBagLayout());
    JPanel functionButtons = new JPanel(new FlowLayout(FlowLayout.LEADING, 12, 12));
    functionButtons.setBorder(new EmptyBorder(-12, -12, -12, -12));
    functionButtons.add(new JButton(projectAddAction));
    functionButtons.add(new JButton(projectDeleteAction));
    functionButtons.add(new JButton(projectCloneAction));
    functionButtons.add(new JButton(projectManageKeysAction));
    informationPanel.add(functionButtons, BorderLayout.PAGE_START);
    informationPanel.add(informationTable, BorderLayout.CENTER);
    final JLabel projectInformationLabel = new JLabel("<html><b>" + I18n.getMessage("jsite.project.project.information") + "</b></html>");
    informationTable.add(projectInformationLabel, new GridBagConstraints(0, 0, 3, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
    projectNameTextField = new JTextField();
    projectNameTextField.getDocument().putProperty("name", "project.name");
    projectNameTextField.getDocument().addDocumentListener(this);
    projectNameTextField.setEnabled(false);
    final TLabel projectNameLabel = new TLabel(I18n.getMessage("jsite.project.project.name") + ":", KeyEvent.VK_N, projectNameTextField);
    informationTable.add(projectNameLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(6, 18, 0, 0), 0, 0));
    informationTable.add(projectNameTextField, new GridBagConstraints(1, 1, 2, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL, new Insets(6, 6, 0, 0), 0, 0));
    projectDescriptionTextField = new JTextField();
    projectDescriptionTextField.getDocument().putProperty("name", "project.description");
    projectDescriptionTextField.getDocument().addDocumentListener(this);
    projectDescriptionTextField.setEnabled(false);
    final TLabel projectDescriptionLabel = new TLabel(I18n.getMessage("jsite.project.project.description") + ":", KeyEvent.VK_D, projectDescriptionTextField);
    informationTable.add(projectDescriptionLabel, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(6, 18, 0, 0), 0, 0));
    informationTable.add(projectDescriptionTextField, new GridBagConstraints(1, 2, 2, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(6, 6, 0, 0), 0, 0));
    projectLocalPathTextField = new JTextField();
    projectLocalPathTextField.getDocument().putProperty("name", "project.localpath");
    projectLocalPathTextField.getDocument().addDocumentListener(this);
    projectLocalPathTextField.setEnabled(false);
    final TLabel projectLocalPathLabel = new TLabel(I18n.getMessage("jsite.project.project.local-path") + ":", KeyEvent.VK_L, projectLocalPathTextField);
    informationTable.add(projectLocalPathLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(6, 18, 0, 0), 0, 0));
    informationTable.add(projectLocalPathTextField, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(6, 6, 0, 0), 0, 0));
    informationTable.add(new JButton(projectLocalPathBrowseAction), new GridBagConstraints(2, 3, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(6, 6, 0, 0), 0, 0));
    final JLabel projectAddressLabel = new JLabel("<html><b>" + I18n.getMessage("jsite.project.project.address") + "</b></html>");
    informationTable.add(projectAddressLabel, new GridBagConstraints(0, 4, 3, 1, 1.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(12, 0, 0, 0), 0, 0));
    projectPathTextField = new JTextField();
    projectPathTextField.getDocument().putProperty("name", "project.path");
    projectPathTextField.getDocument().addDocumentListener(this);
    ((AbstractDocument) projectPathTextField.getDocument()).setDocumentFilter(new DocumentFilter() {

        /**
			 * {@inheritDoc}
			 */
        @Override
        @SuppressWarnings("synthetic-access")
        public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
            super.insertString(fb, offset, string.replaceAll("/", ""), attr);
            updateCompleteURI();
        }

        /**
			 * {@inheritDoc}
			 */
        @Override
        @SuppressWarnings("synthetic-access")
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            super.replace(fb, offset, length, text.replaceAll("/", ""), attrs);
            updateCompleteURI();
        }

        /**
			 * {@inheritDoc}
			 */
        @Override
        @SuppressWarnings("synthetic-access")
        public void remove(FilterBypass fb, int offset, int length) throws BadLocationException {
            super.remove(fb, offset, length);
            updateCompleteURI();
        }
    });
    projectPathTextField.setEnabled(false);
    final TLabel projectPathLabel = new TLabel(I18n.getMessage("jsite.project.project.path") + ":", KeyEvent.VK_P, projectPathTextField);
    informationTable.add(projectPathLabel, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(6, 18, 0, 0), 0, 0));
    informationTable.add(projectPathTextField, new GridBagConstraints(1, 5, 2, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(6, 6, 0, 0), 0, 0));
    projectCompleteUriTextField = new JTextField();
    projectCompleteUriTextField.setEditable(false);
    final TLabel projectUriLabel = new TLabel(I18n.getMessage("jsite.project.project.uri") + ":", KeyEvent.VK_U, projectCompleteUriTextField);
    informationTable.add(projectUriLabel, new GridBagConstraints(0, 6, 1, 1, 0.0, 0.0, GridBagConstraints.LINE_START, GridBagConstraints.NONE, new Insets(6, 18, 0, 0), 0, 0));
    informationTable.add(projectCompleteUriTextField, new GridBagConstraints(1, 6, 1, 1, 1.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(6, 6, 0, 0), 0, 0));
    informationTable.add(new JButton(projectCopyURIAction), new GridBagConstraints(2, 6, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(6, 6, 0, 0), 0, 0));
    I18nContainer.getInstance().registerRunnable(new Runnable() {

        @Override
        public void run() {
            projectInformationLabel.setText("<html><b>" + I18n.getMessage("jsite.project.project.information") + "</b></html>");
            projectNameLabel.setText(I18n.getMessage("jsite.project.project.name") + ":");
            projectDescriptionLabel.setText(I18n.getMessage("jsite.project.project.description") + ":");
            projectLocalPathLabel.setText(I18n.getMessage("jsite.project.project.local-path") + ":");
            projectAddressLabel.setText("<html><b>" + I18n.getMessage("jsite.project.project.address") + "</b></html>");
            projectPathLabel.setText(I18n.getMessage("jsite.project.project.path") + ":");
            projectUriLabel.setText(I18n.getMessage("jsite.project.project.uri") + ":");
        }
    });
    return informationPanel;
}
Example 25
Project: rapidminer-studio-master  File: AnnotationsDecorator.java View source code
/**
	 * Creates and adds the JEditorPane for the currently selected annotation to the process
	 * renderer.
	 */
private void createEditor() {
    final WorkflowAnnotation selected = model.getSelected();
    Rectangle2D loc = selected.getLocation();
    // JEditorPane to edit the comment string
    editPane = new JEditorPane("text/html", "");
    editPane.setBorder(null);
    int paneX = (int) (loc.getX() * rendererModel.getZoomFactor());
    int paneY = (int) (loc.getY() * rendererModel.getZoomFactor());
    int index = view.getModel().getProcessIndex(selected.getProcess());
    Point absolute = ProcessDrawUtils.convertToAbsoluteProcessPoint(new Point(paneX, paneY), index, rendererModel);
    editPane.setBounds((int) absolute.getX(), (int) absolute.getY(), (int) (loc.getWidth() * rendererModel.getZoomFactor()), (int) (loc.getHeight() * rendererModel.getZoomFactor()));
    editPane.setText(AnnotationDrawUtils.createStyledCommentString(selected));
    // use proxy for paste actions to trigger reload of editor after paste
    Action pasteFromClipboard = editPane.getActionMap().get(PASTE_FROM_CLIPBOARD_ACTION_NAME);
    Action paste = editPane.getActionMap().get(PASTE_ACTION_NAME);
    if (pasteFromClipboard != null) {
        editPane.getActionMap().put(PASTE_FROM_CLIPBOARD_ACTION_NAME, new PasteAnnotationProxyAction(pasteFromClipboard, this));
    }
    if (paste != null) {
        editPane.getActionMap().put(PASTE_ACTION_NAME, new PasteAnnotationProxyAction(paste, this));
    }
    // use proxy for transfer actions to convert e.g. HTML paste to plaintext paste
    editPane.setTransferHandler(new TransferHandlerAnnotationPlaintext(editPane));
    // IMPORTANT: Linebreaks do not work without the following!
    // this filter inserts a \r every time the user enters a newline
    // this signal is later used to convert newline to <br/>
    ((HTMLDocument) editPane.getDocument()).setDocumentFilter(new DocumentFilter() {

        @Override
        public void insertString(DocumentFilter.FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException {
            // this is never called..
            super.insertString(fb, offs, str.replaceAll("\n", "\n" + AnnotationDrawUtils.ANNOTATION_HTML_NEWLINE_SIGNAL), a);
        }

        @Override
        public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException {
            if (selected instanceof OperatorAnnotation) {
                // operator annotations have a character limit, enforce here
                try {
                    int existingLength = AnnotationDrawUtils.getPlaintextFromEditor(editPane, false).length() - length;
                    if (existingLength + str.length() > OperatorAnnotation.MAX_CHARACTERS) {
                        // insert at beginning or end is fine, cut off excess characters
                        if (existingLength <= 0 || offs >= existingLength) {
                            int acceptableLength = OperatorAnnotation.MAX_CHARACTERS - existingLength;
                            int newLength = Math.max(acceptableLength, 0);
                            str = str.substring(0, newLength);
                        } else {
                            // inserting into middle, do NOT paste at all
                            return;
                        }
                    }
                } catch (IOException e) {
                }
            }
            super.replace(fb, offs, length, str.replaceAll("\n", "\n" + AnnotationDrawUtils.ANNOTATION_HTML_NEWLINE_SIGNAL), a);
        }
    });
    // set background color
    if (selected.getStyle().getAnnotationColor() == AnnotationColor.TRANSPARENT) {
        editPane.setBackground(Color.WHITE);
    } else {
        editPane.setBackground(selected.getStyle().getAnnotationColor().getColorHighlight());
    }
    editPane.addFocusListener(new FocusAdapter() {

        @Override
        public void focusLost(final FocusEvent e) {
            // right-click menu
            if (e.isTemporary()) {
                return;
            }
            if (editPane != null && e.getOppositeComponent() != null) {
                // style edit menu, no real focus loss
                if (SwingUtilities.isDescendingFrom(e.getOppositeComponent(), editPanel)) {
                    return;
                }
                if (SwingUtilities.isDescendingFrom(e.getOppositeComponent(), colorOverlay)) {
                    return;
                }
                if (colorOverlay.getParent() == e.getOppositeComponent()) {
                    return;
                }
                saveEdit(selected);
                removeEditor();
            }
        }
    });
    editPane.addKeyListener(new KeyAdapter() {

        /** keep track of control down so Ctrl+Enter works but Enter+Ctrl not */
        private boolean controlDown;

        @Override
        public void keyPressed(final KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_CONTROL) {
                controlDown = true;
            }
            // consume so undo/redo etc are not passed to the process
            if (SwingTools.isControlOrMetaDown(e) && e.getKeyCode() == KeyEvent.VK_Z || e.getKeyCode() == KeyEvent.VK_Y) {
                e.consume();
            }
        }

        @Override
        public void keyReleased(final KeyEvent e) {
            switch(e.getKeyCode()) {
                case KeyEvent.VK_CONTROL:
                    controlDown = false;
                    break;
                case KeyEvent.VK_ENTER:
                    if (!controlDown) {
                        updateEditorHeight(selected);
                    } else {
                        // if control was down before Enter was pressed, save & exit
                        saveEdit(selected);
                        removeEditor();
                        model.setSelected(null);
                    }
                    break;
                case KeyEvent.VK_ESCAPE:
                    // ignore changes on escape
                    removeEditor();
                    model.setSelected(null);
                    break;
                default:
                    break;
            }
        }
    });
    editPane.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void removeUpdate(DocumentEvent e) {
            updateEditorHeight(selected);
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            updateEditorHeight(selected);
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            updateEditorHeight(selected);
        }
    });
    view.add(editPane);
    editPane.selectAll();
}
Example 26
Project: esms-master  File: SMSPanel.java View source code
@Override
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
    //if reached size limit, crop the text and show a warning
    String currentText = fb.getDocument().getText(0, fb.getDocument().getLength());
    if ((currentText.length() + (text != null ? text.length() : 0) - length) > envelope.getMaxTextLength()) {
        Context.mainFrame.getStatusPanel().setStatusMessage(l10n.getString("SMSPanel.Text_is_too_long!"), null, null, false);
        Context.mainFrame.getStatusPanel().hideStatusMessageAfter(5000);
        int maxlength = envelope.getMaxTextLength(currentText) - currentText.length() + length;
        maxlength = Math.max(maxlength, 0);
        if (text != null) {
            text = text.substring(0, maxlength);
        }
    }
    super.replace(fb, offset, length, text, lastStyle);
    timer.restart();
}
Example 27
Project: chartsy-master  File: UppercaseDocumentFilter.java View source code
public void insertString(DocumentFilter.FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
    fb.insertString(offset, text.toUpperCase(), attr);
}
Example 28
Project: chatty-master  File: RegexDocumentFilter.java View source code
@Override
public void insertString(DocumentFilter.FilterBypass fb, int off, String str, AttributeSet attr) {
    try {
        fb.insertString(off, pattern.matcher(str).replaceAll(""), attr);
    } catch (BadLocationExceptionNullPointerException |  ex) {
    }
}
Example 29
Project: jedit_cc4401-master  File: CPDOptionPane.java View source code
public void remove(DocumentFilter.FilterBypass fb, int offset, int length) throws BadLocationException {
    super.remove(fb, offset, length);
}
Example 30
Project: commons-swing-master  File: FloatFormatter.java View source code
@Override
protected DocumentFilter getDocumentFilter() {
    return filter;
}
Example 31
Project: Crimson-master  File: FieldLimiter.java View source code
public void replace(DocumentFilter.FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
    fb.replace(offset, length, uppercase ? text.toUpperCase() : text, attrs);
}
Example 32
Project: exist-master  File: UmaskEditorFormatter.java View source code
@Override
protected DocumentFilter getDocumentFilter() {
    return new UmaskDocumentFilter();
}
Example 33
Project: XSLT-master  File: UmaskEditorFormatter.java View source code
@Override
protected DocumentFilter getDocumentFilter() {
    return new UmaskDocumentFilter();
}
Example 34
Project: binnavi-master  File: CHexFormatter.java View source code
@Override
protected DocumentFilter getDocumentFilter() {
    return filter;
}
Example 35
Project: medsavant-master  File: FixedLengthTextFilter.java View source code
public void insertString(DocumentFilter.FilterBypass filtby, int ofs, String text, AttributeSet attrSet) throws BadLocationException {
    if (filtby.getDocument().getLength() + text.length() <= maxLength) {
        filtby.insertString(ofs, text, attrSet);
    } else {
        Toolkit.getDefaultToolkit().beep();
    }
}
Example 36
Project: JDK-master  File: ValueFormatter.java View source code
@Override
protected DocumentFilter getDocumentFilter() {
    return this.filter;
}
Example 37
Project: Work_book-master  File: FormatTestFrame.java View source code
protected DocumentFilter getDocumentFilter() {
    return filter;
}
Example 38
Project: jdk7u-jdk-master  File: ValueFormatter.java View source code
@Override
protected DocumentFilter getDocumentFilter() {
    return this.filter;
}
Example 39
Project: openjdk-master  File: ValueFormatter.java View source code
@Override
protected DocumentFilter getDocumentFilter() {
    return this.filter;
}
Example 40
Project: openjdk8-jdk-master  File: ValueFormatter.java View source code
@Override
protected DocumentFilter getDocumentFilter() {
    return this.filter;
}
Example 41
Project: haskell-java-parser-master  File: JFormattedTextField.java View source code
protected DocumentFilter getDocumentFilter() {
    throw new InternalError("not implemented");
}
Example 42
Project: erjang-master  File: TTYTextAreaDriverControl.java View source code
public void insertString(DocumentFilter.FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
    if (offset >= startPos)
        super.insertString(fb, offset, string, attr);
}
Example 43
Project: servoy-client-master  File: FixedDefaultFormatter.java View source code
/**
	 * Returns the <code>DocumentFilter</code> used to restrict the characters
	 * that can be input into the <code>JFormattedTextField</code>.
	 *
	 * @return DocumentFilter to restrict edits
	 */
@Override
protected DocumentFilter getDocumentFilter() {
    if (documentFilter == null) {
        documentFilter = new DefaultDocumentFilter();
    }
    return documentFilter;
}