Example usage for javax.swing.text JTextComponent getText

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

Introduction

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

Prototype

public String getText() 

Source Link

Document

Returns the text contained in this TextComponent.

Usage

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

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

    // title/*from www.jav  a2 s. c om*/
    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:net.sf.jabref.gui.AutoCompleteListener.java

/**
 * If user cancels autocompletion by/*from ww  w  .ja  va2 s  .  c o  m*/
 *   a) entering another letter than the completed word (and there is no other auto completion)
 *   b) space
 * the casing of the letters has to be kept
 * 
 * Global variable "lastBeginning" keeps track of typed letters.
 * We rely on this variable to reconstruct the text 
 * 
 * @param wordSeperatorTyped indicates whether the user has typed a white space character or a
 */
private void setUnmodifiedTypedLetters(JTextComponent comp, boolean lastBeginningContainsTypedCharacter,
        boolean wordSeperatorTyped) {
    if (lastBeginning == null) {
        LOGGER.debug("No last beginning found");
        // There was no previous input (if the user typed a word, where no autocompletion is available)
        // Thus, there is nothing to replace
        return;
    }
    LOGGER.debug("lastBeginning: >" + lastBeginning + '<');
    if (comp.getSelectedText() == null) {
        // if there is no selection
        // the user has typed the complete word, but possibly with a different casing
        // we need a replacement
        if (wordSeperatorTyped) {
            LOGGER.debug("Replacing complete word");
        } else {
            // if user did not press a white space character (space, ...),
            // then we do not do anything
            return;
        }
    } else {
        LOGGER.debug("Selected text " + comp.getSelectedText() + " will be removed");
        // remove completion suggestion
        comp.replaceSelection("");
    }

    lastCaretPosition = comp.getCaretPosition();

    int endIndex = lastCaretPosition - lastBeginning.length();
    if (lastBeginningContainsTypedCharacter) {
        // the current letter is NOT contained in comp.getText(), but in lastBeginning
        // thus lastBeginning.length() is one too large
        endIndex++;
    }
    String text = comp.getText();
    comp.setText(text.substring(0, endIndex).concat(lastBeginning).concat(text.substring(lastCaretPosition)));
    if (lastBeginningContainsTypedCharacter) {
        // the current letter is NOT contained in comp.getText()
        // Thus, cursor position also did not get updated
        lastCaretPosition++;
    }
    comp.setCaretPosition(lastCaretPosition);
    lastBeginning = null;
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.FormPane.java

@Override
public void swapTextFieldType(final InputPanel inputPanel, final short fieldLen) {
    JTextComponent oldComp;
    short fieldType;
    short rows;//w  ww  . j  av  a2s . com
    if (inputPanel.getComp() instanceof JTextField) {
        JTextField tf = (JTextField) inputPanel.getComp();
        tf.getDocument().removeDocumentListener(docListener);
        fieldType = WorkbenchTemplateMappingItem.TEXTAREA;
        oldComp = tf;
        rows = DEFAULT_TEXTAREA_ROWS;
    } else {
        JTextArea ta = (JTextArea) inputPanel.getComp();
        ta.getDocument().removeDocumentListener(docListener);
        fieldType = WorkbenchTemplateMappingItem.TEXTFIELD;
        oldComp = ta;
        rows = DEFAULT_TEXTFIELD_ROWS;
    }

    WorkbenchTemplateMappingItem wbtmi = inputPanel.getWbtmi();
    inputPanel.setComp(createUIComp(WorkbenchTask.getDataType(wbtmi), wbtmi.getCaption(), wbtmi.getFieldName(),
            fieldType, wbtmi.getDataFieldLength(), fieldLen, rows, wbtmi));

    ignoreChanges = true;
    ((JTextComponent) inputPanel.getComp()).setText(oldComp.getText());
    ignoreChanges = false;

    hasChanged = true;
    workbenchPane.setChanged(true);
}

From source file:net.sf.jabref.gui.autocompleter.AutoCompleteListener.java

@Override
public void keyTyped(KeyEvent e) {
    LOGGER.debug("key typed event caught " + e.getKeyCode());
    char ch = e.getKeyChar();
    if (ch == '\n') {
        // this case is handled at keyPressed(e)
        return;//from   w  ww  .  j  a  v  a2  s . co m
    }

    // don't do auto completion inside words
    if (!atEndOfWord((JTextComponent) e.getSource())) {
        return;
    }

    if ((e.getModifiers() | InputEvent.SHIFT_MASK) == InputEvent.SHIFT_MASK) {
        // plain key or SHIFT + key is pressed, no handling of CTRL+key,  META+key, ...
        if (Character.isLetter(ch) || Character.isDigit(ch)
                || (Character.isWhitespace(ch) && completer.isSingleUnitField())) {
            JTextComponent comp = (JTextComponent) e.getSource();

            if (toSetIn == null) {
                LOGGER.debug("toSetIn is null");
            } else {
                LOGGER.debug("toSetIn: >" + toSetIn + '<');
            }

            // The case-insensitive system is a bit tricky here
            // If keyword is "TODO" and user types "tO", then this is treated as "continue" as the "O" matches the "O"
            // If keyword is "TODO" and user types "To", then this is treated as "discont" as the "o" does NOT match the "O".

            if ((toSetIn != null) && (toSetIn.length() > 1) && (ch == toSetIn.charAt(1))) {
                // User continues on the word that was suggested.
                LOGGER.debug("cont");

                toSetIn = toSetIn.substring(1);
                if (!toSetIn.isEmpty()) {
                    int cp = comp.getCaretPosition();
                    //comp.setCaretPosition(cp+1-toSetIn.);
                    comp.select((cp + 1) - toSetIn.length(), cp);
                    lastBeginning = lastBeginning + ch;

                    e.consume();
                    lastCaretPosition = comp.getCaretPosition();

                    lastCompletions = findCompletions(lastBeginning);
                    lastShownCompletion = 0;
                    for (int i = 0; i < lastCompletions.size(); i++) {
                        String lastCompletion = lastCompletions.get(i);
                        if (lastCompletion.endsWith(toSetIn)) {
                            lastShownCompletion = i;
                            break;
                        }

                    }
                    if (toSetIn.length() < 2) {
                        // User typed the last character of the autocompleted word
                        // We have to replace the automcompletion word by the typed word.
                        // This helps if the user presses "space" after the completion
                        // "space" indicates that the user does NOT want the autocompletion,
                        // but the typed word
                        String text = comp.getText();
                        comp.setText(text.substring(0, lastCaretPosition - lastBeginning.length())
                                + lastBeginning + text.substring(lastCaretPosition));
                        // there is no selected text, therefore we are not updating the selection
                        toSetIn = null;
                    }
                    return;
                }
            }

            if ((toSetIn != null) && ((toSetIn.length() <= 1) || (ch != toSetIn.charAt(1)))) {
                // User discontinues the word that was suggested.
                lastBeginning = lastBeginning + ch;

                LOGGER.debug("discont toSetIn: >" + toSetIn + "'<' lastBeginning: >" + lastBeginning + '<');

                List<String> completed = findCompletions(lastBeginning);
                if ((completed != null) && (!completed.isEmpty())) {
                    lastShownCompletion = 0;
                    lastCompletions = completed;
                    String sno = completed.get(0);
                    // toSetIn = string used for autocompletion last time
                    // this string has to be removed
                    // lastCaretPosition is the position of the caret after toSetIn.
                    int lastLen = toSetIn.length() - 1;
                    toSetIn = sno.substring(lastBeginning.length() - 1);
                    String text = comp.getText();
                    //we do not use toSetIn as we want to obey the casing of "sno"
                    comp.setText(text.substring(0, (lastCaretPosition - lastLen - lastBeginning.length()) + 1)
                            + sno + text.substring(lastCaretPosition));
                    int startSelect = (lastCaretPosition + 1) - lastLen;
                    int endSelect = (lastCaretPosition + toSetIn.length()) - lastLen;
                    comp.select(startSelect, endSelect);

                    lastCaretPosition = comp.getCaretPosition();
                    e.consume();
                    return;
                } else {
                    setUnmodifiedTypedLetters(comp, true, false);
                    e.consume();
                    toSetIn = null;
                    return;
                }
            }

            LOGGER.debug("case else");

            comp.replaceSelection("");

            StringBuffer currentword = getCurrentWord(comp);

            // only "real characters" end up here
            assert (!Character.isISOControl(ch));
            currentword.append(ch);
            startCompletion(currentword, e);
            return;
        } else {
            if (Character.isWhitespace(ch)) {
                assert (!completer.isSingleUnitField());
                LOGGER.debug("whitespace && !singleUnitField");
                // start a new search if end-of-field is reached

                // replace displayed letters with typed letters
                setUnmodifiedTypedLetters((JTextComponent) e.getSource(), false, true);
                resetAutoCompletion();
                return;
            }

            LOGGER.debug("No letter/digit/whitespace or CHAR_UNDEFINED");
            // replace displayed letters with typed letters
            setUnmodifiedTypedLetters((JTextComponent) e.getSource(), false, !Character.isISOControl(ch));
            resetAutoCompletion();
            return;
        }
    }
    resetAutoCompletion();
}

From source file:net.sf.jabref.gui.AutoCompleteListener.java

@Override
public void keyTyped(KeyEvent e) {
    LOGGER.debug("key typed event caught " + e.getKeyCode());
    char ch = e.getKeyChar();
    if (ch == '\n') {
        // this case is handled at keyPressed(e)
        return;/*from ww w  . j  ava 2 s.c  o  m*/
    }

    if ((e.getModifiers() | InputEvent.SHIFT_MASK) == InputEvent.SHIFT_MASK) {
        // plain key or SHIFT + key is pressed, no handling of CTRL+key,  META+key, ...
        if (Character.isLetter(ch) || Character.isDigit(ch)
                || (Character.isWhitespace(ch) && completer.isSingleUnitField())) {
            JTextComponent comp = (JTextComponent) e.getSource();

            if (toSetIn == null) {
                LOGGER.debug("toSetIn is null");
            } else {
                LOGGER.debug("toSetIn: >" + toSetIn + '<');
            }

            // The case-insensitive system is a bit tricky here
            // If keyword is "TODO" and user types "tO", then this is treated as "continue" as the "O" matches the "O"
            // If keyword is "TODO" and user types "To", then this is treated as "discont" as the "o" does NOT match the "O".

            if ((toSetIn != null) && (toSetIn.length() > 1) && (ch == toSetIn.charAt(1))) {
                // User continues on the word that was suggested.
                LOGGER.debug("cont");

                toSetIn = toSetIn.substring(1);
                if (!toSetIn.isEmpty()) {
                    int cp = comp.getCaretPosition();
                    //comp.setCaretPosition(cp+1-toSetIn.);
                    //System.out.println(cp-toSetIn.length()+" - "+cp);
                    comp.select((cp + 1) - toSetIn.length(), cp);
                    lastBeginning = lastBeginning + ch;

                    e.consume();
                    lastCaretPosition = comp.getCaretPosition();

                    //System.out.println("Added char: '"+toSetIn+"'");
                    //System.out.println("LastBeginning: '"+lastBeginning+"'");

                    lastCompletions = findCompletions(lastBeginning, comp);
                    lastShownCompletion = 0;
                    for (int i = 0; i < lastCompletions.length; i++) {
                        String lastCompletion = lastCompletions[i];
                        //System.out.println("Completion["+i+"] = "+lastCompletion);
                        if (lastCompletion.endsWith(toSetIn)) {
                            lastShownCompletion = i;
                            break;
                        }

                    }
                    //System.out.println("Index now: "+lastShownCompletion);
                    if (toSetIn.length() < 2) {
                        // User typed the last character of the autocompleted word
                        // We have to replace the automcompletion word by the typed word.
                        // This helps if the user presses "space" after the completion
                        // "space" indicates that the user does NOT want the autocompletion,
                        // but the typed word
                        String text = comp.getText();
                        comp.setText(text.substring(0, lastCaretPosition - lastBeginning.length())
                                + lastBeginning + text.substring(lastCaretPosition));
                        // there is no selected text, therefore we are not updating the selection
                        toSetIn = null;
                    }
                    return;
                }
            }

            if ((toSetIn != null) && ((toSetIn.length() <= 1) || (ch != toSetIn.charAt(1)))) {
                // User discontinues the word that was suggested.
                lastBeginning = lastBeginning + ch;

                LOGGER.debug("discont toSetIn: >" + toSetIn + "'<' lastBeginning: >" + lastBeginning + '<');

                String[] completed = findCompletions(lastBeginning, comp);
                if ((completed != null) && (completed.length > 0)) {
                    lastShownCompletion = 0;
                    lastCompletions = completed;
                    String sno = completed[0];
                    // toSetIn = string used for autocompletion last time
                    // this string has to be removed
                    // lastCaretPosition is the position of the caret after toSetIn.
                    int lastLen = toSetIn.length() - 1;
                    toSetIn = sno.substring(lastBeginning.length() - 1);
                    String text = comp.getText();
                    //Util.pr(""+lastLen);
                    //we do not use toSetIn as we want to obey the casing of "sno"
                    comp.setText(text.substring(0, (lastCaretPosition - lastLen - lastBeginning.length()) + 1)
                            + sno + text.substring(lastCaretPosition));
                    int startSelect = (lastCaretPosition + 1) - lastLen;
                    int endSelect = (lastCaretPosition + toSetIn.length()) - lastLen;
                    comp.select(startSelect, endSelect);

                    lastCaretPosition = comp.getCaretPosition();
                    e.consume();
                    return;
                } else {
                    setUnmodifiedTypedLetters(comp, true, false);
                    e.consume();
                    toSetIn = null;
                    return;
                }
            }

            LOGGER.debug("case else");

            comp.replaceSelection("");

            StringBuffer currentword = getCurrentWord(comp);
            if (currentword == null) {
                currentword = new StringBuffer();
            }

            // only "real characters" end up here
            assert (!Character.isISOControl(ch));
            currentword.append(ch);
            startCompletion(currentword, e);
            return;
        } else {
            if (Character.isWhitespace(ch)) {
                assert (!completer.isSingleUnitField());
                LOGGER.debug("whitespace && !singleUnitField");
                // start a new search if end-of-field is reached

                // replace displayed letters with typed letters
                setUnmodifiedTypedLetters((JTextComponent) e.getSource(), false, true);
                resetAutoCompletion();
                return;
            }

            LOGGER.debug("No letter/digit/whitespace or CHAR_UNDEFINED");
            // replace displayed letters with typed letters 
            setUnmodifiedTypedLetters((JTextComponent) e.getSource(), false, !Character.isISOControl(ch));
            resetAutoCompletion();
            return;
        }
    }
    resetAutoCompletion();
}

From source file:net.sourceforge.squirrel_sql.fw.datasetviewer.cellcomponent.BaseKeyTextHandler.java

/**
 * Ensure, that a sign character is entered at the right position.
 * Valid characters for a sign is the <code>-</code>. If the corresponding {@link ColumnDisplayDefinition#isSigned()} is 
 * <code>false</code>, than a sign is not allowed for this column.
 * Otherwise, a sign character is allowed at the first position of the text if there is not already a sign char present.
 * <B>If the entered sign character is not valid, then the keyEvent will be consumed and a beep will be processed.</B>
 * <p>For example:</p>/*from   w w  w .j a  va2s. c  o  m*/
 * Allowed:
 * <li>42</li>
 * <li>-42</li>
 * Not allowed:
 * <li>-.42</li>
 * <li>--42</li>
 * <li>42-42</li>
 * <li>-42-42</li>
 * <li>42-</li>
 * @param keyEvent KeyEvent, which insert a character
 * @param textComponent Text component, where the character was typed.
 * @param colDef Display definition of the affected column. This will be used, for finding out, if the data type can be signed.
 * @param beepHelper Helper for beeping, if a sign char is would be inserted at a wrong position.
 */
protected void checkSignCharacter(KeyEvent keyEvent, JTextComponent textComponent,
        ColumnDisplayDefinition colDef, IToolkitBeepHelper beepHelper) {
    char c = keyEvent.getKeyChar();
    String text = textComponent.getText();

    if (isSignCharacter(c)) {
        boolean ok = true;
        if (colDef.isSigned() == false) {
            ok = false;
        } else if (!text.equals("<null>") && text.length() != 0) {
            int caretPosition = textComponent.getCaretPosition();
            if (caretPosition != 0 || isSignCharacter(text.charAt(0))) {
                ok = false;
            }
        }
        if (ok == false) {
            /*
             *  user entered '+' or '-' at a bad place,
             *  Maybe not at the first position, or there is not a numeric char at the beginning - maybe we have already a sign
             */
            beepHelper.beep(textComponent);
            keyEvent.consume();
        }
    }
}

From source file:op.tools.SYSTools.java

public static BigDecimal checkBigDecimal(javax.swing.event.CaretEvent evt, boolean nees2BePositive) {
    BigDecimal bd = null;//from   ww w .ja  va  2s .c  o  m
    JTextComponent txt = (JTextComponent) evt.getSource();
    Action toolTipAction = txt.getActionMap().get("hideTip");
    if (toolTipAction != null) {
        ActionEvent hideTip = new ActionEvent(txt, ActionEvent.ACTION_PERFORMED, "");
        toolTipAction.actionPerformed(hideTip);
    }
    try {
        OPDE.debug(txt.getText());
        OPDE.debug(assimilateDecimalSeparators(txt.getText()));

        bd = parseDecimal(txt.getText());

        //            bd = BigDecimal.valueOf(Double.parseDouble(assimilateDecimalSeparators(txt.getText())));
        OPDE.debug(bd);
        if (nees2BePositive && bd.compareTo(BigDecimal.ZERO) <= 0) {
            txt.setToolTipText("<html><font color=\"red\"><b>" + SYSTools.xx("misc.msg.invalidnumber")
                    + "</b></font></html>");
            toolTipAction = txt.getActionMap().get("postTip");
            bd = BigDecimal.ONE;
        } else {
            txt.setToolTipText("");
        }

    } catch (NumberFormatException ex) {
        if (nees2BePositive) {
            bd = BigDecimal.ONE;
        } else {
            bd = BigDecimal.ZERO;
        }
        txt.setToolTipText(
                "<html><font color=\"red\"><b>" + SYSTools.xx("misc.msg.invalidnumber") + "</b></font></html>");
        toolTipAction = txt.getActionMap().get("postTip");
        if (toolTipAction != null) {
            ActionEvent postTip = new ActionEvent(txt, ActionEvent.ACTION_PERFORMED, "");
            toolTipAction.actionPerformed(postTip);
        }
    }
    return bd;
}

From source file:openlr.mapviewer.coding.ui.ApplyChangesListener.java

/**
 * Applies the current values of the properties form to the properties
 * holder of the current application runtime.
 *//*from  w w w . jav a  2 s .  c o  m*/
void applyChanges() {
    FileConfiguration config = propsHolder.getProperties(type);

    for (Map.Entry<String, JTextComponent> entry : optionsTextFields.entrySet()) {

        JTextComponent textComponent = entry.getValue();
        String text = textComponent.getText();
        config.setProperty(entry.getKey(), text);
        propsHolder.setProperties(type, config);

        textComponent.setBorder(STANDARD_TEXT_BOX_BORDER);
    }
}

From source file:org.apache.cayenne.modeler.util.PathChooserComboBoxCellEditor.java

protected void parsePathString(char lastEnteredCharacter) {
    JTextComponent editorComponent = (JTextComponent) (comboBoxPathChooser).getEditor().getEditorComponent();
    String pathString = editorComponent.getText();
    if (pathString != null && pathString.isEmpty()) {
        setComboModelAccordingToPath("");
        previousEmbeddedLevel = 0;/* ww  w . j a  va  2 s .  c om*/
        return;
    }

    if (lastEnteredCharacter == '.') {
        processDotEntered();
        previousEmbeddedLevel = StringUtils.countMatches(pathString, ".");
        return;
    }

    int currentEmbeddedLevel = StringUtils.countMatches(pathString, ".");
    if (previousEmbeddedLevel != currentEmbeddedLevel) {
        previousEmbeddedLevel = currentEmbeddedLevel;
        String[] pathStrings = pathString.split(Pattern.quote("."));
        String lastStringInPath = pathStrings[pathStrings.length - 1];
        String saveDbAttributePath = pathString;
        pathString = pathString.replaceAll(lastStringInPath + "$", "");
        List<String> currentNodeChildren = new ArrayList<>();
        currentNodeChildren.addAll(getChildren(getCurrentNode(pathString), pathString));
        comboBoxPathChooser.setModel(new DefaultComboBoxModel<>(currentNodeChildren.toArray(new String[0])));
        comboBoxPathChooser.setSelectedItem(saveDbAttributePath);
    }
}

From source file:org.apache.cayenne.modeler.util.PathChooserComboBoxCellEditor.java

protected void processDotEntered() {
    JTextComponent editorComponent = (JTextComponent) (comboBoxPathChooser).getEditor().getEditorComponent();

    String dbAttributePath = editorComponent.getText();
    if (".".equals(dbAttributePath)) {
        setComboModelAccordingToPath("");
        return;//from   ww w. j a va 2  s.  c  o m
    }
    char secondFromEndCharacter = dbAttributePath.charAt(dbAttributePath.length() - 2);
    if (secondFromEndCharacter == '.') {
        // two dots entered one by one , we replace it by one dot
        editorComponent.setText(dbAttributePath.substring(0, dbAttributePath.length() - 1));
        return;
    }
    String[] pathStrings = dbAttributePath.split(Pattern.quote("."));
    String lastStringInPath = pathStrings[pathStrings.length - 1];

    //we will check if lastStringInPath is correct name of DbAttribute or DbRelationship
    //for appropriate previous node in path. if it is not we won't add entered dot to dbAttributePath
    String dbAttributePathForPreviousNode;
    if (pathStrings.length == 1) {
        //previous root is treeModel.getRoot()
        dbAttributePathForPreviousNode = "";
    } else {
        dbAttributePathForPreviousNode = dbAttributePath.replaceAll('.' + lastStringInPath + ".$", "");
    }
    List<String> potentialVariantsToChoose = getChildren(getCurrentNode(dbAttributePathForPreviousNode), "");
    if (potentialVariantsToChoose.contains(lastStringInPath)
            && !(getCurrentNode(dbAttributePath) instanceof DbAttribute)) {
        setComboModelAccordingToPath(dbAttributePath);
    } else {
        editorComponent.setText(dbAttributePath.substring(0, dbAttributePath.length() - 1));
    }
}