Example usage for javax.swing.text JTextComponent getDocument

List of usage examples for javax.swing.text JTextComponent getDocument

Introduction

In this page you can find the example usage for javax.swing.text JTextComponent getDocument.

Prototype

public Document getDocument() 

Source Link

Document

Fetches the model associated with the editor.

Usage

From source file:edu.ku.brc.specify.conversion.CustomDBConverterPanel.java

/**
 * Creates a Document dbConverterListener so the UI is updated when the doc changes
 * @param textField the text field to be changed
 *///w  ww  .j  a v a2 s  . c  om
protected void addDocListenerForTextComp(final JTextComponent textField) {
    textField.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
            updateUIControls();
        }

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

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

From source file:net.sf.taverna.t2.activities.spreadsheet.views.SpreadsheetImportConfigView.java

@Override
protected void initialise() {
    super.initialise();
    newConfiguration = getJson().deepCopy();

    // title/*from   w  ww.j ava2 s .c o m*/
    titlePanel = new JPanel(new BorderLayout());
    titlePanel.setBackground(Color.WHITE);
    addDivider(titlePanel, SwingConstants.BOTTOM, true);

    titleLabel = new JLabel(SpreadsheetImportUIText.getString("SpreadsheetImportConfigView.panelTitle"));
    titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 13.5f));
    titleIcon = new JLabel("");
    titleMessage = new DialogTextArea(DEFAULT_MESSAGE);
    titleMessage.setMargin(new Insets(5, 10, 10, 10));
    // titleMessage.setMinimumSize(new Dimension(0, 30));
    titleMessage.setFont(titleMessage.getFont().deriveFont(11f));
    titleMessage.setEditable(false);
    titleMessage.setFocusable(false);
    // titleMessage.setFont(titleLabel.getFont().deriveFont(Font.PLAIN,
    // 12f));

    // column range
    columnLabel = new JLabel(
            SpreadsheetImportUIText.getString("SpreadsheetImportConfigView.columnSectionLabel"));

    JsonNode columnRange = newConfiguration.get("columnRange");
    columnFromValue = new JTextField(new UpperCaseDocument(),
            SpreadsheetUtils.getColumnLabel(columnRange.get("start").intValue()), 4);
    columnFromValue.setMinimumSize(columnFromValue.getPreferredSize());
    columnToValue = new JTextField(new UpperCaseDocument(),
            SpreadsheetUtils.getColumnLabel(columnRange.get("end").intValue()), 4);
    columnToValue.setMinimumSize(columnToValue.getPreferredSize());

    columnFromValue.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
        }

        public void insertUpdate(DocumentEvent e) {
            checkValue(columnFromValue.getText());
        }

        public void removeUpdate(DocumentEvent e) {
            checkValue(columnFromValue.getText());
        }

        private void checkValue(String text) {
            if (text.trim().equals("")) {
                addErrorMessage(EMPTY_FROM_COLUMN_ERROR_MESSAGE);
            } else if (text.trim().matches("[A-Za-z]+")) {
                String fromColumn = columnFromValue.getText().toUpperCase();
                String toColumn = columnToValue.getText().toUpperCase();
                int fromColumnIndex = SpreadsheetUtils.getColumnIndex(fromColumn);
                int toColumnIndex = SpreadsheetUtils.getColumnIndex(toColumn);
                if (checkColumnRange(fromColumnIndex, toColumnIndex)) {
                    columnMappingTableModel.setFromColumn(fromColumnIndex);
                    columnMappingTableModel.setToColumn(toColumnIndex);
                    newConfiguration.set("columnRange", newConfiguration.objectNode()
                            .put("start", fromColumnIndex).put("end", toColumnIndex));
                    validatePortNames();
                }
                removeErrorMessage(FROM_COLUMN_ERROR_MESSAGE);
                removeErrorMessage(EMPTY_FROM_COLUMN_ERROR_MESSAGE);
            } else {
                addErrorMessage(FROM_COLUMN_ERROR_MESSAGE);
                removeErrorMessage(EMPTY_FROM_COLUMN_ERROR_MESSAGE);
            }
        }

    });

    columnToValue.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
        }

        public void insertUpdate(DocumentEvent e) {
            checkValue(columnToValue.getText());
        }

        public void removeUpdate(DocumentEvent e) {
            checkValue(columnToValue.getText());
        }

        private void checkValue(String text) {
            if (text.trim().equals("")) {
                addErrorMessage(EMPTY_TO_COLUMN_ERROR_MESSAGE);
            } else if (text.trim().matches("[A-Za-z]+")) {
                String fromColumn = columnFromValue.getText().toUpperCase();
                String toColumn = columnToValue.getText().toUpperCase();
                int fromColumnIndex = SpreadsheetUtils.getColumnIndex(fromColumn);
                int toColumnIndex = SpreadsheetUtils.getColumnIndex(toColumn);
                if (checkColumnRange(fromColumnIndex, toColumnIndex)) {
                    columnMappingTableModel.setFromColumn(fromColumnIndex);
                    columnMappingTableModel.setToColumn(toColumnIndex);
                    newConfiguration.set("columnRange", newConfiguration.objectNode()
                            .put("start", fromColumnIndex).put("end", toColumnIndex));
                    validatePortNames();
                }
                removeErrorMessage(TO_COLUMN_ERROR_MESSAGE);
                removeErrorMessage(EMPTY_TO_COLUMN_ERROR_MESSAGE);

            } else {
                addErrorMessage(TO_COLUMN_ERROR_MESSAGE);
                removeErrorMessage(EMPTY_TO_COLUMN_ERROR_MESSAGE);
            }
        }
    });

    // row range
    rowLabel = new JLabel(SpreadsheetImportUIText.getString("SpreadsheetImportConfigView.rowSectionLabel"));
    addDivider(rowLabel, SwingConstants.TOP, false);

    rowSelectAllOption = new JCheckBox(
            SpreadsheetImportUIText.getString("SpreadsheetImportConfigView.selectAllRowsOption"));
    rowExcludeFirstOption = new JCheckBox(
            SpreadsheetImportUIText.getString("SpreadsheetImportConfigView.excludeHeaderRowOption"));
    rowIgnoreBlankRows = new JCheckBox(
            SpreadsheetImportUIText.getString("SpreadsheetImportConfigView.ignoreBlankRowsOption"));
    rowSelectAllOption.setFocusable(false);
    rowExcludeFirstOption.setFocusable(false);

    JsonNode rowRange = newConfiguration.get("rowRange");
    rowFromValue = new JTextField(new NumericDocument(), String.valueOf(rowRange.get("start").intValue() + 1),
            4);
    if (rowRange.get("end").intValue() == -1) {
        rowToValue = new JTextField(new NumericDocument(), "", 4);
    } else {
        rowToValue = new JTextField(new NumericDocument(), String.valueOf(rowRange.get("end").intValue() + 1),
                4);
    }
    rowFromValue.setMinimumSize(rowFromValue.getPreferredSize());
    rowToValue.setMinimumSize(rowToValue.getPreferredSize());

    if (newConfiguration.get("allRows").booleanValue()) {
        rowSelectAllOption.setSelected(true);
        rowFromValue.setEditable(false);
        rowFromValue.setEnabled(false);
        rowToValue.setEditable(false);
        rowToValue.setEnabled(false);
    } else {
        rowExcludeFirstOption.setEnabled(false);
    }
    rowExcludeFirstOption.setSelected(newConfiguration.get("excludeFirstRow").booleanValue());
    rowIgnoreBlankRows.setSelected(newConfiguration.get("ignoreBlankRows").booleanValue());

    rowFromValue.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
        }

        public void insertUpdate(DocumentEvent e) {
            checkValue(rowFromValue.getText());
        }

        public void removeUpdate(DocumentEvent e) {
            checkValue(rowFromValue.getText());
        }

        private void checkValue(String text) {
            if (text.trim().equals("")) {
                addErrorMessage(EMPTY_FROM_ROW_ERROR_MESSAGE);
            } else if (text.trim().matches("[1-9][0-9]*")) {
                checkRowRange(rowFromValue.getText(), rowToValue.getText());
                int fromRow = Integer.parseInt(rowFromValue.getText());
                ((ObjectNode) newConfiguration.get("rowRange")).put("start", fromRow - 1);
                removeErrorMessage(FROM_ROW_ERROR_MESSAGE);
                removeErrorMessage(EMPTY_FROM_ROW_ERROR_MESSAGE);
            } else {
                addErrorMessage(FROM_ROW_ERROR_MESSAGE);
                removeErrorMessage(EMPTY_FROM_ROW_ERROR_MESSAGE);
            }
        }
    });

    rowToValue.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
        }

        public void insertUpdate(DocumentEvent e) {
            checkValue(rowToValue.getText());
        }

        public void removeUpdate(DocumentEvent e) {
            checkValue(rowToValue.getText());
        }

        private void checkValue(String text) {
            if (text.trim().equals("")) {
                ((ObjectNode) newConfiguration.get("rowRange")).put("end", -1);
                removeErrorMessage(TO_ROW_ERROR_MESSAGE);
                removeErrorMessage(INCONSISTENT_ROW_MESSAGE);
            } else if (text.trim().matches("[0-9]+")) {
                checkRowRange(rowFromValue.getText(), rowToValue.getText());
                int toRow = Integer.parseInt(rowToValue.getText());
                ((ObjectNode) newConfiguration.get("rowRange")).put("end", toRow - 1);
                removeErrorMessage(TO_ROW_ERROR_MESSAGE);
            } else {
                addErrorMessage(TO_ROW_ERROR_MESSAGE);
            }
        }
    });

    rowSelectAllOption.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                newConfiguration.put("allRows", true);
                rowExcludeFirstOption.setEnabled(true);
                if (rowExcludeFirstOption.isSelected()) {
                    rowFromValue.setText("2");
                } else {
                    rowFromValue.setText("1");
                }
                rowToValue.setText("");
                rowFromValue.setEditable(false);
                rowFromValue.setEnabled(false);
                rowToValue.setEditable(false);
                rowToValue.setEnabled(false);
            } else {
                newConfiguration.put("allRows", false);
                rowExcludeFirstOption.setEnabled(false);
                rowFromValue.setEditable(true);
                rowFromValue.setEnabled(true);
                rowToValue.setEditable(true);
                rowToValue.setEnabled(true);
            }
        }
    });

    rowExcludeFirstOption.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                newConfiguration.put("excludeFirstRow", true);
                rowFromValue.setText("2");
                ((ObjectNode) newConfiguration.get("rowRange")).put("start", 1);
            } else {
                newConfiguration.put("excludeFirstRow", false);
                rowFromValue.setText("1");
                ((ObjectNode) newConfiguration.get("rowRange")).put("start", 0);
            }
        }
    });

    rowIgnoreBlankRows.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            newConfiguration.put("ignoreBlankRows", e.getStateChange() == ItemEvent.SELECTED);
        }
    });

    // empty cells
    emptyCellLabel = new JLabel(
            SpreadsheetImportUIText.getString("SpreadsheetImportConfigView.emptyCellSectionLabel"));
    addDivider(emptyCellLabel, SwingConstants.TOP, false);

    emptyCellButtonGroup = new ButtonGroup();
    emptyCellEmptyStringOption = new JRadioButton(
            SpreadsheetImportUIText.getString("SpreadsheetImportConfigView.emptyStringOption"));
    emptyCellUserDefinedOption = new JRadioButton(
            SpreadsheetImportUIText.getString("SpreadsheetImportConfigView.userDefinedOption"));
    emptyCellErrorValueOption = new JRadioButton(
            SpreadsheetImportUIText.getString("SpreadsheetImportConfigView.generateErrorOption"));
    emptyCellEmptyStringOption.setFocusable(false);
    emptyCellUserDefinedOption.setFocusable(false);
    emptyCellErrorValueOption.setFocusable(false);

    emptyCellUserDefinedValue = new JTextField(newConfiguration.get("emptyCellValue").textValue());

    emptyCellButtonGroup.add(emptyCellEmptyStringOption);
    emptyCellButtonGroup.add(emptyCellUserDefinedOption);
    emptyCellButtonGroup.add(emptyCellErrorValueOption);

    if (newConfiguration.get("emptyCellPolicy").textValue().equals("GENERATE_ERROR")) {
        emptyCellErrorValueOption.setSelected(true);
        emptyCellUserDefinedValue.setEnabled(false);
        emptyCellUserDefinedValue.setEditable(false);
    } else if (newConfiguration.get("emptyCellPolicy").textValue().equals("EMPTY_STRING")) {
        emptyCellEmptyStringOption.setSelected(true);
        emptyCellUserDefinedValue.setEnabled(false);
        emptyCellUserDefinedValue.setEditable(false);
    } else {
        emptyCellUserDefinedOption.setSelected(true);
        emptyCellUserDefinedValue.setText(newConfiguration.get("emptyCellValue").textValue());
        emptyCellUserDefinedValue.setEnabled(true);
        emptyCellUserDefinedValue.setEditable(true);
    }

    emptyCellEmptyStringOption.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            newConfiguration.put("emptyCellPolicy", "EMPTY_STRING");
            emptyCellUserDefinedValue.setEnabled(false);
            emptyCellUserDefinedValue.setEditable(false);
        }
    });
    emptyCellUserDefinedOption.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            newConfiguration.put("emptyCellPolicy", "USER_DEFINED");
            emptyCellUserDefinedValue.setEnabled(true);
            emptyCellUserDefinedValue.setEditable(true);
            emptyCellUserDefinedValue.requestFocusInWindow();
        }
    });
    emptyCellErrorValueOption.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            newConfiguration.put("emptyCellPolicy", "GENERATE_ERROR");
            emptyCellUserDefinedValue.setEnabled(false);
            emptyCellUserDefinedValue.setEditable(false);
        }
    });

    emptyCellUserDefinedValue.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
            newConfiguration.put("emptyCellValue", emptyCellUserDefinedValue.getText());
        }

        public void insertUpdate(DocumentEvent e) {
            newConfiguration.put("emptyCellValue", emptyCellUserDefinedValue.getText());
        }

        public void removeUpdate(DocumentEvent e) {
            newConfiguration.put("emptyCellValue", emptyCellUserDefinedValue.getText());
        }
    });

    // column mappings
    columnMappingLabel = new JLabel(
            SpreadsheetImportUIText.getString("SpreadsheetImportConfigView.columnMappingSectionLabel"));
    addDivider(columnMappingLabel, SwingConstants.TOP, false);

    Map<String, String> columnToPortMapping = new HashMap<>();
    if (newConfiguration.has("columnNames")) {
        for (JsonNode columnName : newConfiguration.get("columnNames")) {
            columnToPortMapping.put(columnName.get("column").textValue(), columnName.get("port").textValue());
        }
    }
    columnMappingTableModel = new SpreadsheetImportConfigTableModel(columnFromValue.getText(),
            columnToValue.getText(), columnToPortMapping);

    columnMappingTable = new JTable();
    columnMappingTable.setRowSelectionAllowed(false);
    columnMappingTable.getTableHeader().setReorderingAllowed(false);
    columnMappingTable.setGridColor(Color.LIGHT_GRAY);
    // columnMappingTable.setFocusable(false);

    columnMappingTable.setColumnModel(new DefaultTableColumnModel() {
        public TableColumn getColumn(int columnIndex) {
            TableColumn column = super.getColumn(columnIndex);
            if (columnIndex == 0) {
                column.setMaxWidth(100);
            }
            return column;
        }
    });

    TableCellEditor defaultEditor = columnMappingTable.getDefaultEditor(String.class);
    if (defaultEditor instanceof DefaultCellEditor) {
        DefaultCellEditor defaultCellEditor = (DefaultCellEditor) defaultEditor;
        defaultCellEditor.setClickCountToStart(1);
        Component editorComponent = defaultCellEditor.getComponent();
        if (editorComponent instanceof JTextComponent) {
            final JTextComponent textField = (JTextComponent) editorComponent;
            textField.getDocument().addDocumentListener(new DocumentListener() {
                public void changedUpdate(DocumentEvent e) {
                    updateModel(textField.getText());
                }

                public void insertUpdate(DocumentEvent e) {
                    updateModel(textField.getText());
                }

                public void removeUpdate(DocumentEvent e) {
                    updateModel(textField.getText());
                }

                private void updateModel(String text) {
                    int row = columnMappingTable.getEditingRow();
                    int column = columnMappingTable.getEditingColumn();
                    columnMappingTableModel.setValueAt(text, row, column);

                    ArrayNode columnNames = newConfiguration.arrayNode();
                    Map<String, String> columnToPortMapping = columnMappingTableModel.getColumnToPortMapping();
                    for (Entry<String, String> entry : columnToPortMapping.entrySet()) {
                        columnNames.add(newConfiguration.objectNode().put("column", entry.getKey()).put("port",
                                entry.getValue()));
                    }
                    newConfiguration.put("columnNames", columnNames);
                    validatePortNames();
                }

            });
        }
    }

    columnMappingTable.setModel(columnMappingTableModel);

    // output format
    outputFormatLabel = new JLabel(
            SpreadsheetImportUIText.getString("SpreadsheetImportConfigView.outputFormatSectionLabel"));

    outputFormatMultiplePort = new JRadioButton(
            SpreadsheetImportUIText.getString("SpreadsheetImportConfigView.multiplePortOption"));
    outputFormatSinglePort = new JRadioButton(
            SpreadsheetImportUIText.getString("SpreadsheetImportConfigView.singlePortOption"));
    outputFormatMultiplePort.setFocusable(false);
    outputFormatSinglePort.setFocusable(false);

    outputFormatDelimiterLabel = new JLabel(
            SpreadsheetImportUIText.getString("SpreadsheetImportConfigView.userDefinedCsvDelimiter"));
    outputFormatDelimiter = new JTextField(newConfiguration.get("csvDelimiter").textValue(), 5);

    outputFormatButtonGroup = new ButtonGroup();
    outputFormatButtonGroup.add(outputFormatMultiplePort);
    outputFormatButtonGroup.add(outputFormatSinglePort);

    if (newConfiguration.get("outputFormat").textValue().equals("PORT_PER_COLUMN")) {
        outputFormatMultiplePort.setSelected(true);
        outputFormatDelimiterLabel.setEnabled(false);
        outputFormatDelimiter.setEnabled(false);
    } else {
        outputFormatSinglePort.setSelected(true);
        columnMappingLabel.setEnabled(false);
        enableTable(columnMappingTable, false);
    }

    outputFormatMultiplePort.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            outputFormatDelimiterLabel.setEnabled(false);
            outputFormatDelimiter.setEnabled(false);
            columnMappingLabel.setEnabled(true);
            enableTable(columnMappingTable, true);
            newConfiguration.put("outputFormat", "PORT_PER_COLUMN");
        }
    });
    outputFormatSinglePort.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            outputFormatDelimiterLabel.setEnabled(true);
            outputFormatDelimiter.setEnabled(true);
            columnMappingLabel.setEnabled(false);
            enableTable(columnMappingTable, false);
            newConfiguration.put("outputFormat", "SINGLE_PORT");
        }

    });
    outputFormatDelimiter.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
            handleUpdate();
        }

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

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

        private void handleUpdate() {
            String text = null;
            try {
                text = StringEscapeUtils.unescapeJava(outputFormatDelimiter.getText());
            } catch (RuntimeException re) {
            }
            if (text == null || text.length() == 0) {
                newConfiguration.put("csvDelimiter", ",");
            } else {
                newConfiguration.put("csvDelimiter", text.substring(0, 1));
            }
        }

    });

    // buttons
    nextButton = new JButton(SpreadsheetImportUIText.getString("SpreadsheetImportConfigView.nextButton"));
    nextButton.setFocusable(false);
    nextButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            backButton.setVisible(true);
            nextButton.setVisible(false);
            cardLayout.last(contentPanel);
        }
    });

    backButton = new JButton(SpreadsheetImportUIText.getString("SpreadsheetImportConfigView.backButton"));
    backButton.setFocusable(false);
    backButton.setVisible(false);
    backButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            nextButton.setVisible(true);
            backButton.setVisible(false);
            cardLayout.first(contentPanel);
        }
    });

    buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    addDivider(buttonPanel, SwingConstants.TOP, true);

    removeAll();
    layoutPanel();
}

From source file:edu.ku.brc.af.ui.db.DatabaseLoginPanel.java

/**
 * Creates a Document listener so the UI is updated when the doc changes
 * @param textField the text field to be changed
 *//*from   ww w .j  a  v  a  2  s  .co m*/
protected void addDocListenerForTextComp(final JTextComponent textField) {
    textField.getDocument().addDocumentListener(new DocumentAdaptor() {
        @Override
        protected void changed(DocumentEvent e) {
            updateUIControls();
        }
    });
}

From source file:net.pandoragames.far.ui.swing.component.UndoHistory.java

/**
 * Registers the specified text component for the undo history.
 * This enables the <code>ctrl + z</code> and <code>ctrl + y</code> shortcuts.
 * @param component to be registered for undos.
 */// w  w  w.  jav a  2 s.co  m
public void registerUndoHistory(JTextComponent component) {
    // Create an undo action and add it to the text component
    undoAction = new AbstractAction("Undo") {
        public void actionPerformed(ActionEvent evt) {
            if (UndoHistory.this.canUndo()) {
                UndoHistory.this.undo();
            }
        }
    };
    undoAction.setEnabled(false);
    component.getActionMap().put(ACTION_KEY_UNDO, undoAction);

    // Create a redo action and add it to the text component
    redoAction = new AbstractAction("Redo") {
        public void actionPerformed(ActionEvent evt) {
            if (UndoHistory.this.canRedo()) {
                UndoHistory.this.redo();
            }
        }
    };
    redoAction.setEnabled(false);
    component.getActionMap().put(ACTION_KEY_REDO, redoAction);

    // Bind the actions to ctl-Z and ctl-Y
    component.getInputMap().put(KeyStroke.getKeyStroke("control Z"), ACTION_KEY_UNDO);
    undoAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control Z"));
    component.getInputMap().put(KeyStroke.getKeyStroke("control Y"), ACTION_KEY_REDO);
    redoAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("control Y"));

    // registers this UndoHistory as an UndoableEditListener
    component.getDocument().addUndoableEditListener(this);
}

From source file:edu.ku.brc.af.ui.forms.validation.FormValidator.java

/**
 * @param textField textField to be hooked up
 * @param id id of control/*from ww  w  . ja  v  a 2 s.  com*/
 * @param isRequiredArg whether the field must be filled in
 * @param valType the type of validation to do
 * @param valStr the validation rule where the subject is its name
 * @param changeListenerOnly indicates whether to create a validator
 */
public void hookupTextField(final JTextComponent textField, final String id, final boolean isRequiredArg,
        final UIValidator.Type valType, final String valStr, final boolean changeListenerOnly) {

    fields.put(id, textField);

    UIValidator.Type type = isRequiredArg ? UIValidator.Type.Changed : valType;

    UIValidator uiv = null;
    if (StringUtils.isEmpty(valStr)) {
        if (valType != UIValidator.Type.None) {
            uiv = createValidator(textField, valType);
        }
    } else {
        uiv = changeListenerOnly ? null : createValidator(textField, type, valStr);
    }

    if (uiv != null) {
        DataChangeNotifier dcn = new DataChangeNotifier(id, textField, uiv);
        dcn.addDataChangeListener(this);

        dcNotifiers.put(id, dcn);

        if (type == UIValidator.Type.Changed || isRequiredArg || changeListenerOnly) {
            textField.getDocument().addDocumentListener(dcn);

        } else if (type == UIValidator.Type.Focus) {
            textField.addFocusListener(dcn);

        } else {
            // Do nothing for UIValidator.Type.OK
        }
    }

    addRuleObjectMapping(id, textField);
}

From source file:com.hexidec.ekit.EkitCore.java

/**
 * Method for finding (and optionally replacing) a string in the text
 *//*from   w ww . j a  v  a 2 s . c om*/
private int findText(String findTerm, String replaceTerm, boolean bCaseSenstive, int iOffset) {
    JTextComponent jtpFindSource;
    if (sourceWindowActive || jtpSource.hasFocus()) {
        jtpFindSource = (JTextComponent) jtpSource;
    } else {
        jtpFindSource = (JTextComponent) jtpMain;
    }
    int searchPlace = -1;
    try {
        Document baseDocument = jtpFindSource.getDocument();
        searchPlace = (bCaseSenstive
                ? baseDocument.getText(0, baseDocument.getLength()).indexOf(findTerm, iOffset)
                : baseDocument.getText(0, baseDocument.getLength()).toLowerCase()
                        .indexOf(findTerm.toLowerCase(), iOffset));
        if (searchPlace > -1) {
            if (replaceTerm != null) {
                AttributeSet attribs = null;
                if (baseDocument instanceof HTMLDocument) {
                    Element element = ((HTMLDocument) baseDocument).getCharacterElement(searchPlace);
                    attribs = element.getAttributes();
                }
                baseDocument.remove(searchPlace, findTerm.length());
                baseDocument.insertString(searchPlace, replaceTerm, attribs);
                jtpFindSource.setCaretPosition(searchPlace + replaceTerm.length());
                jtpFindSource.requestFocus();
                jtpFindSource.select(searchPlace, searchPlace + replaceTerm.length());
            } else {
                jtpFindSource.setCaretPosition(searchPlace + findTerm.length());
                jtpFindSource.requestFocus();
                jtpFindSource.select(searchPlace, searchPlace + findTerm.length());
            }
        }
    } catch (BadLocationException ble) {
        logException("BadLocationException in actionPerformed method", ble);
        new SimpleInfoDialog(this.getWindow(), Translatrix.getTranslationString("Error"), true,
                Translatrix.getTranslationString("ErrorBadLocationException"), SimpleInfoDialog.ERROR);
    }
    return searchPlace;
}

From source file:net.sourceforge.pmd.util.designer.Designer.java

private static void makeTextComponentUndoable(JTextComponent textConponent) {
    final UndoManager undoManager = new UndoManager();
    textConponent.getDocument().addUndoableEditListener(new UndoableEditListener() {
        @Override// ww w .j av a 2s  .co m
        public void undoableEditHappened(UndoableEditEvent evt) {
            undoManager.addEdit(evt.getEdit());
        }
    });
    ActionMap actionMap = textConponent.getActionMap();
    InputMap inputMap = textConponent.getInputMap();
    actionMap.put("Undo", new AbstractAction("Undo") {
        @Override
        public void actionPerformed(ActionEvent evt) {
            try {
                if (undoManager.canUndo()) {
                    undoManager.undo();
                }
            } catch (CannotUndoException e) {
                throw new RuntimeException(e);
            }
        }
    });
    inputMap.put(KeyStroke.getKeyStroke("control Z"), "Undo");

    actionMap.put("Redo", new AbstractAction("Redo") {
        @Override
        public void actionPerformed(ActionEvent evt) {
            try {
                if (undoManager.canRedo()) {
                    undoManager.redo();
                }
            } catch (CannotRedoException e) {
                throw new RuntimeException(e);
            }
        }
    });
    inputMap.put(KeyStroke.getKeyStroke("control Y"), "Redo");
}

From source file:netbeanstypescript.TSCodeCompletion.java

@Override
public QueryType getAutoQuery(JTextComponent component, String typedText) {
    if (typedText.length() == 0) {
        return QueryType.NONE;
    }//from  w  ww. j  a  va2 s  .  com

    int offset = component.getCaretPosition();
    TokenSequence<? extends JsTokenId> ts = LexUtilities.getJsTokenSequence(component.getDocument(), offset);
    if (ts != null) {
        int diff = ts.move(offset);
        TokenId currentTokenId = null;
        if (diff == 0 && ts.movePrevious() || ts.moveNext()) {
            currentTokenId = ts.token().id();
        }

        char lastChar = typedText.charAt(typedText.length() - 1);
        if (currentTokenId == JsTokenId.BLOCK_COMMENT || currentTokenId == JsTokenId.DOC_COMMENT
                || currentTokenId == JsTokenId.LINE_COMMENT) {
            if (lastChar == '@') { //NOI18N
                return QueryType.COMPLETION;
            }
        } else if (currentTokenId == JsTokenId.STRING && lastChar == '/') {
            return QueryType.COMPLETION;
        } else {
            switch (lastChar) {
            case '.': //NOI18N
                if (OptionsUtils.forLanguage(JsTokenId.javascriptLanguage()).autoCompletionAfterDot()) {
                    return QueryType.COMPLETION;
                }
                break;
            default:
                if (OptionsUtils.forLanguage(JsTokenId.javascriptLanguage()).autoCompletionFull()) {
                    if (!Character.isWhitespace(lastChar) && CHARS_NO_AUTO_COMPLETE.indexOf(lastChar) == -1) {
                        return QueryType.COMPLETION;
                    }
                }
                return QueryType.NONE;
            }
        }
    }
    return QueryType.NONE;
}

From source file:org.apache.syncope.ide.netbeans.view.ResourceExplorerTopComponent.java

private void saveContent() {
    try {//from w  ww  . j  a va2  s .  c  o  m
        JTextComponent ed = EditorRegistry.lastFocusedComponent();
        Document document = ed.getDocument();
        String content = document.getText(0, document.getLength());
        String path = (String) document.getProperty(Document.TitleProperty);
        String[] temp = path.split(File.separator);
        String name = temp[temp.length - 1];
        String templateType = temp[temp.length - 2];
        temp = name.split("\\.");
        String format = temp[1];
        String key = temp[0];

        if (templateType.equals("Mail")) {
            if (format.equals("txt")) {
                mailTemplateManagerService.setFormat(key, MailTemplateFormat.TEXT,
                        IOUtils.toInputStream(content, encodingPattern));
            } else {
                mailTemplateManagerService.setFormat(key, MailTemplateFormat.HTML,
                        IOUtils.toInputStream(content, encodingPattern));
            }
        } else if (format.equals("html")) {
            reportTemplateManagerService.setFormat(key, ReportTemplateFormat.HTML,
                    IOUtils.toInputStream(content, encodingPattern));
        } else if (format.equals("fo")) {
            reportTemplateManagerService.setFormat(key, ReportTemplateFormat.FO,
                    IOUtils.toInputStream(content, encodingPattern));
        } else {
            reportTemplateManagerService.setFormat(key, ReportTemplateFormat.CSV,
                    IOUtils.toInputStream(content, encodingPattern));
        }
    } catch (BadLocationException e) {
        Exceptions.printStackTrace(e);
    }
}

From source file:org.executequery.gui.editor.autocomplete.QueryEditorAutoCompletePopupProvider.java

public void popupSelectionMade() {

    AutoCompleteListItem selectedListItem = (AutoCompleteListItem) autoCompletePopup.getSelectedItem();

    if (selectedListItem == null || selectedListItem.isNothingProposed()) {

        return;/*from  ww  w.  j a  va 2 s. c  o m*/
    }

    String selectedValue = selectedListItem.getInsertionValue();

    try {

        JTextComponent textComponent = queryEditorTextComponent();
        Document document = textComponent.getDocument();

        int caretPosition = textComponent.getCaretPosition();
        String wordAtCursor = queryEditor.getWordToCursor();

        if (StringUtils.isNotBlank(wordAtCursor)) {

            int wordAtCursorLength = wordAtCursor.length();
            int insertionIndex = caretPosition - wordAtCursorLength;

            if (selectedListItem.isKeyword() && isAllLowerCase(wordAtCursor)) {

                selectedValue = selectedValue.toLowerCase();
            }

            if (!Character.isLetterOrDigit(wordAtCursor.charAt(0))) {

                // cases where you might have a.column_name or similar

                insertionIndex++;
                wordAtCursorLength--;

            } else if (wordAtCursor.contains(".")) {

                int index = wordAtCursor.indexOf(".");
                insertionIndex += index + 1;
                wordAtCursorLength -= index + 1;
            }

            document.remove(insertionIndex, wordAtCursorLength);
            document.insertString(insertionIndex, selectedValue, null);

        } else {

            document.insertString(caretPosition, selectedValue, null);
        }

    } catch (BadLocationException e) {

        debug("Error on autocomplete insertion", e);

    } finally {

        autoCompletePopup.hidePopup();
    }

}