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:org.paxle.desktop.impl.event.MultipleChangesListener.java

public void addComp2Monitor(final Object comp) {
    if (comp instanceof JTextComponent) {
        final JTextComponent tc = (JTextComponent) comp;
        final Document doc = tc.getDocument();
        initialValues.put(doc, new CompEntry(tc.getText()));
        doc.addDocumentListener(this);
    } else {/*from ww  w. j ava2 s.c  o m*/
        final Class<?> clazz = comp.getClass();
        final int eidx = getEntryIndex(clazz);
        if (eidx < 0)
            throw new RuntimeException("component '" + clazz.getName() + "' not supported for monitoring");
        try {
            // save the initial value of the component for comparison purposes on state change
            initialValues.put(comp, new CompEntry(clazz.getMethod(GET_VALUES[eidx]).invoke(comp)));

            // register this as event listener for the component
            final Method method = clazz.getMethod("add" + ADD_LISTENERS[eidx].getSimpleName(),
                    ADD_LISTENERS[eidx]);
            method.invoke(comp, this);
            logger.debug("added " + ADD_LISTENERS[eidx].getSimpleName() + " for " + comp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.pentaho.ui.xul.swing.tags.SwingTree.java

private TableCellEditor getCellEditor(final SwingTreeCol col) {
    return new DefaultCellEditor(new JComboBox()) {

        JComponent control;/*from   w  w w.  j a  v a 2s .c  om*/

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
                final int row, final int column) {
            Component comp;
            ColumnType colType = col.getColumnType();
            if (colType == ColumnType.DYNAMIC) {
                colType = ColumnType.valueOf(extractDynamicColType(elements.toArray()[row], column));
            }

            final XulTreeCell cell = getRootChildren().getItem(row).getRow().getCell(column);
            switch (colType) {
            case CHECKBOX:
                final JCheckBox checkbox = new JCheckBox();
                final JTable tbl = table;
                checkbox.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        SwingTree.this.table.setValueAt(checkbox.isSelected(), row, column);
                        tbl.getCellEditor().stopCellEditing();
                    }
                });

                control = checkbox;
                if (value instanceof String) {
                    checkbox.setSelected(((String) value).equalsIgnoreCase("true")); //$NON-NLS-1$
                } else if (value instanceof Boolean) {
                    checkbox.setSelected((Boolean) value);
                } else if (value == null) {
                    checkbox.setSelected(false);
                }
                if (isSelected) {
                    checkbox.setBackground(Color.LIGHT_GRAY);
                }
                comp = checkbox;
                checkbox.setEnabled(!cell.isDisabled());
                break;
            case EDITABLECOMBOBOX:
            case COMBOBOX:
                Vector val = (value != null && value instanceof Vector) ? (Vector) value : new Vector();
                final JComboBox comboBox = new JComboBox(val);

                if (isSelected) {
                    comboBox.setBackground(Color.LIGHT_GRAY);
                }

                if (colType == ColumnType.EDITABLECOMBOBOX) {

                    comboBox.setEditable(true);
                    final JTextComponent textComp = (JTextComponent) comboBox.getEditor().getEditorComponent();

                    textComp.addKeyListener(new KeyListener() {
                        private String oldValue = ""; //$NON-NLS-1$

                        public void keyPressed(KeyEvent e) {
                            oldValue = textComp.getText();
                        }

                        public void keyReleased(KeyEvent e) {
                            if (oldValue != null && !oldValue.equals(textComp.getText())) {
                                SwingTree.this.table.setValueAt(textComp.getText(), row, column);

                                oldValue = textComp.getText();
                            } else if (oldValue == null) {
                                // AWT error where sometimes the keyReleased is fired before keyPressed.
                                oldValue = textComp.getText();
                            } else {
                                logger.debug("Special key pressed, ignoring"); //$NON-NLS-1$
                            }
                        }

                        public void keyTyped(KeyEvent e) {
                        }
                    });

                    comboBox.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
                            // if(textComp.hasFocus() == false && comboBox.hasFocus()){
                            SwingTree.logger.debug("Setting ComboBox value from editor: " //$NON-NLS-1$
                                    + comboBox.getSelectedItem() + ", " + row + ", " + column); //$NON-NLS-1$ //$NON-NLS-2$

                            SwingTree.this.table.setValueAt(comboBox.getSelectedIndex(), row, column);
                            // }
                        }
                    });
                } else {
                    comboBox.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {

                            SwingTree.logger.debug("Setting ComboBox value from editor: " //$NON-NLS-1$
                                    + comboBox.getSelectedItem() + ", " + row + ", " + column); //$NON-NLS-1$ //$NON-NLS-2$

                            SwingTree.this.table.setValueAt(comboBox.getSelectedIndex(), row, column);
                        }
                    });
                }

                control = comboBox;
                comboBox.setEnabled(!cell.isDisabled());
                comp = comboBox;
                break;
            case LABEL:
                JLabel lbl = new JLabel(cell.getLabel());
                comp = lbl;
                control = lbl;
                break;
            case CUSTOM:
                return new CustomCellEditorWrapper(cell, customEditors.get(col.getType()));
            default:
                final JTextField label = new JTextField((String) value);

                label.getDocument().addDocumentListener(new DocumentListener() {

                    public void changedUpdate(DocumentEvent arg0) {
                        SwingTree.this.table.setValueAt(label.getText(), row, column);
                    }

                    public void insertUpdate(DocumentEvent arg0) {
                        SwingTree.this.table.setValueAt(label.getText(), row, column);
                    }

                    public void removeUpdate(DocumentEvent arg0) {
                        SwingTree.this.table.setValueAt(label.getText(), row, column);
                    }

                });
                if (isSelected) {
                    label.setOpaque(true);
                    // label.setBackground(Color.LIGHT_GRAY);
                }

                control = label;
                comp = label;
                label.setEnabled(!cell.isDisabled());
                label.setDisabledTextColor(Color.DARK_GRAY);
                break;
            }

            return comp;
        }

        @Override
        public Object getCellEditorValue() {
            if (control instanceof JCheckBox) {
                return ((JCheckBox) control).isSelected();
            } else if (control instanceof JComboBox) {
                JComboBox box = (JComboBox) control;
                if (box.isEditable()) {
                    return ((JTextComponent) box.getEditor().getEditorComponent()).getText();
                } else {
                    return box.getSelectedIndex();
                }
            } else if (control instanceof JTextField) {
                return ((JTextField) control).getText();
            } else {
                return ((JLabel) control).getText();
            }
        }

    };

}

From source file:org.rockyroadshub.planner.core.gui.calendar.FormPane.java

private static boolean isEmpty(JTextComponent comp) {
    boolean b = StringUtils.isBlank(comp.getText());
    if (b) {//from   w w  w  .ja va  2s.c  o m
        MainFrame.showErrorDialog(comp.getName() + " is empty.");
    }
    return b;
}

From source file:pl.otros.logview.gui.LogViewMainFrame.java

private void initToolbar() {
    toolBar = new JToolBar();
    final JComboBox searchMode = new JComboBox(
            new String[] { "String contains search: ", "Regex search: ", "Query search: " });
    final SearchAction searchActionForward = new SearchAction(otrosApplication, SearchDirection.FORWARD);
    final SearchAction searchActionBackward = new SearchAction(otrosApplication, SearchDirection.REVERSE);
    searchFieldCbxModel = new DefaultComboBoxModel();
    searchField = new JXComboBox(searchFieldCbxModel);
    searchField.setEditable(true);//from  w w w.  jav a2  s  . co  m
    AutoCompleteDecorator.decorate(searchField);
    searchField.setMinimumSize(new Dimension(150, 10));
    searchField.setPreferredSize(new Dimension(250, 10));
    searchField.setToolTipText(
            "<HTML>Enter text to search.<BR/>" + "Enter - search next,<BR/>Alt+Enter search previous,<BR/>"
                    + "Ctrl+Enter - mark all found</HTML>");
    final DelayedSwingInvoke delayedSearchResultUpdate = new DelayedSwingInvoke() {
        @Override
        protected void performActionHook() {
            JTextComponent editorComponent = (JTextComponent) searchField.getEditor().getEditorComponent();
            int stringEnd = editorComponent.getSelectionStart();
            if (stringEnd < 0) {
                stringEnd = editorComponent.getText().length();
            }
            try {
                String selectedText = editorComponent.getText(0, stringEnd);
                if (StringUtils.isBlank(selectedText)) {
                    return;
                }
                OtrosJTextWithRulerScrollPane<JTextPane> logDetailWithRulerScrollPane = otrosApplication
                        .getSelectedLogViewPanel().getLogDetailWithRulerScrollPane();
                MessageUpdateUtils.highlightSearchResult(logDetailWithRulerScrollPane,
                        otrosApplication.getAllPluginables().getMessageColorizers());
                RulerBarHelper.scrollToFirstMarker(logDetailWithRulerScrollPane);
            } catch (BadLocationException e) {
                LOGGER.log(Level.SEVERE, "Can't update search highlight", e);
            }
        }
    };
    JTextComponent searchFieldTextComponent = (JTextComponent) searchField.getEditor().getEditorComponent();
    searchFieldTextComponent.getDocument().addDocumentListener(new DocumentInsertUpdateHandler() {
        @Override
        protected void documentChanged(DocumentEvent e) {
            delayedSearchResultUpdate.performAction();
        }
    });
    final MarkAllFoundAction markAllFoundAction = new MarkAllFoundAction(otrosApplication);
    final SearchModeValidatorDocumentListener searchValidatorDocumentListener = new SearchModeValidatorDocumentListener(
            (JTextField) searchField.getEditor().getEditorComponent(), observer, SearchMode.STRING_CONTAINS);
    SearchMode searchModeFromConfig = configuration.get(SearchMode.class, "gui.searchMode",
            SearchMode.STRING_CONTAINS);
    final String lastSearchString;
    int selectedSearchMode = 0;
    if (searchModeFromConfig.equals(SearchMode.STRING_CONTAINS)) {
        selectedSearchMode = 0;
        lastSearchString = configuration.getString(ConfKeys.SEARCH_LAST_STRING, "");
    } else if (searchModeFromConfig.equals(SearchMode.REGEX)) {
        selectedSearchMode = 1;
        lastSearchString = configuration.getString(ConfKeys.SEARCH_LAST_REGEX, "");
    } else if (searchModeFromConfig.equals(SearchMode.QUERY)) {
        selectedSearchMode = 2;
        lastSearchString = configuration.getString(ConfKeys.SEARCH_LAST_QUERY, "");
    } else {
        LOGGER.warning("Unknown search mode " + searchModeFromConfig);
        lastSearchString = "";
    }
    Component editorComponent = searchField.getEditor().getEditorComponent();
    if (editorComponent instanceof JTextField) {
        final JTextField sfTf = (JTextField) editorComponent;
        sfTf.getDocument().addDocumentListener(searchValidatorDocumentListener);
        sfTf.getDocument().addDocumentListener(new DocumentInsertUpdateHandler() {
            @Override
            protected void documentChanged(DocumentEvent e) {
                try {
                    int length = e.getDocument().getLength();
                    if (length > 0) {
                        searchResultColorizer.setSearchString(e.getDocument().getText(0, length));
                    }
                } catch (BadLocationException e1) {
                    LOGGER.log(Level.SEVERE, "Error: ", e1);
                }
            }
        });
        sfTf.addKeyListener(new SearchFieldKeyListener(searchActionForward, sfTf));
        sfTf.setText(lastSearchString);
    }
    searchMode.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            SearchMode mode = null;
            boolean validationEnabled = false;
            String confKey = null;
            String lastSearch = ((JTextField) searchField.getEditor().getEditorComponent()).getText();
            if (searchMode.getSelectedIndex() == 0) {
                mode = SearchMode.STRING_CONTAINS;
                searchValidatorDocumentListener.setSearchMode(mode);
                validationEnabled = false;
                searchMode.setToolTipText("Checking if log message contains string (case is ignored)");
                confKey = ConfKeys.SEARCH_LAST_STRING;
            } else if (searchMode.getSelectedIndex() == 1) {
                mode = SearchMode.REGEX;
                validationEnabled = true;
                searchMode
                        .setToolTipText("Checking if log message matches regular expression (case is ignored)");
                confKey = ConfKeys.SEARCH_LAST_REGEX;
            } else if (searchMode.getSelectedIndex() == 2) {
                mode = SearchMode.QUERY;
                validationEnabled = true;
                String querySearchTooltip = "<HTML>" + //
                "Advance search using SQL-like quries (i.e. level>=warning && msg~=failed && thread==t1)<BR/>" + //
                "Valid operator for query search is ==, ~=, !=, LIKE, EXISTS, <, <=, >, >=, &&, ||, ! <BR/>" + //
                "See wiki for more info<BR/>" + //
                "</HTML>";
                searchMode.setToolTipText(querySearchTooltip);
                confKey = ConfKeys.SEARCH_LAST_QUERY;
            }
            searchValidatorDocumentListener.setSearchMode(mode);
            searchValidatorDocumentListener.setEnable(validationEnabled);
            searchActionForward.setSearchMode(mode);
            searchActionBackward.setSearchMode(mode);
            markAllFoundAction.setSearchMode(mode);
            configuration.setProperty("gui.searchMode", mode);
            searchResultColorizer.setSearchMode(mode);
            List<Object> list = configuration.getList(confKey);
            searchFieldCbxModel.removeAllElements();
            for (Object o : list) {
                searchFieldCbxModel.addElement(o);
            }
            searchField.setSelectedItem(lastSearch);
        }
    });
    searchMode.setSelectedIndex(selectedSearchMode);
    final JCheckBox markFound = new JCheckBox("Mark search result");
    markFound.setMnemonic(KeyEvent.VK_M);
    searchField.addKeyListener(markAllFoundAction);
    configuration.addConfigurationListener(markAllFoundAction);
    JButton markAllFoundButton = new JButton(markAllFoundAction);
    final JComboBox markColor = new JComboBox(MarkerColors.values());
    markFound.setSelected(configuration.getBoolean("gui.markFound", true));
    markFound.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            boolean selected = markFound.isSelected();
            searchActionForward.setMarkFound(selected);
            searchActionBackward.setMarkFound(selected);
            configuration.setProperty("gui.markFound", markFound.isSelected());
        }
    });
    markColor.setRenderer(new MarkerColorsComboBoxRenderer());
    //      markColor.addActionListener(new ActionListener() {
    //
    //         @Override
    //         public void actionPerformed(ActionEvent e) {
    //            MarkerColors markerColors = (MarkerColors) markColor.getSelectedItem();
    //            searchActionForward.setMarkerColors(markerColors);
    //            searchActionBackward.setMarkerColors(markerColors);
    //            markAllFoundAction.setMarkerColors(markerColors);
    //            configuration.setProperty("gui.markColor", markColor.getSelectedItem());
    //            otrosApplication.setSelectedMarkColors(markerColors);
    //         }
    //      });
    markColor.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            MarkerColors markerColors = (MarkerColors) markColor.getSelectedItem();
            searchActionForward.setMarkerColors(markerColors);
            searchActionBackward.setMarkerColors(markerColors);
            markAllFoundAction.setMarkerColors(markerColors);
            configuration.setProperty("gui.markColor", markColor.getSelectedItem());
            otrosApplication.setSelectedMarkColors(markerColors);
        }
    });
    markColor.getModel()
            .setSelectedItem(configuration.get(MarkerColors.class, "gui.markColor", MarkerColors.Aqua));
    buttonSearch = new JButton(searchActionForward);
    buttonSearch.setMnemonic(KeyEvent.VK_N);
    JButton buttonSearchPrev = new JButton(searchActionBackward);
    buttonSearchPrev.setMnemonic(KeyEvent.VK_P);
    enableDisableComponetsForTabs.addComponet(buttonSearch);
    enableDisableComponetsForTabs.addComponet(buttonSearchPrev);
    enableDisableComponetsForTabs.addComponet(searchField);
    enableDisableComponetsForTabs.addComponet(markFound);
    enableDisableComponetsForTabs.addComponet(markAllFoundButton);
    enableDisableComponetsForTabs.addComponet(searchMode);
    enableDisableComponetsForTabs.addComponet(markColor);
    toolBar.add(searchMode);
    toolBar.add(searchField);
    toolBar.add(buttonSearch);
    toolBar.add(buttonSearchPrev);
    toolBar.add(markFound);
    toolBar.add(markAllFoundButton);
    toolBar.add(markColor);
    JButton nextMarked = new JButton(new JumpToMarkedAction(otrosApplication, Direction.FORWARD));
    nextMarked.setToolTipText(nextMarked.getText());
    nextMarked.setText("");
    nextMarked.setMnemonic(KeyEvent.VK_E);
    enableDisableComponetsForTabs.addComponet(nextMarked);
    toolBar.add(nextMarked);
    JButton prevMarked = new JButton(new JumpToMarkedAction(otrosApplication, Direction.BACKWARD));
    prevMarked.setToolTipText(prevMarked.getText());
    prevMarked.setText("");
    prevMarked.setMnemonic(KeyEvent.VK_R);
    enableDisableComponetsForTabs.addComponet(prevMarked);
    toolBar.add(prevMarked);
    enableDisableComponetsForTabs.addComponet(toolBar.add(new SearchByLevel(otrosApplication, 1, Level.INFO)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, 1, Level.WARNING)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, 1, Level.SEVERE)));
    enableDisableComponetsForTabs.addComponet(toolBar.add(new SearchByLevel(otrosApplication, -1, Level.INFO)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, -1, Level.WARNING)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, -1, Level.SEVERE)));
}

From source file:tufts.vue.ui.InspectorPane.java

private void loadText(JTextComponent c, String text) {
    String hasText = c.getText();
    // This prevents flashing where fields of
    // length greater the the visible area do
    // a flash-scroll when setting the text, even
    // if it's the same as what's there.
    if (hasText != text && !hasText.equals(text))
        c.setText(text);//  w  w  w  . j  a v a2  s  . c o m
}