Example usage for javax.swing JTextField addKeyListener

List of usage examples for javax.swing JTextField addKeyListener

Introduction

In this page you can find the example usage for javax.swing JTextField addKeyListener.

Prototype

public synchronized void addKeyListener(KeyListener l) 

Source Link

Document

Adds the specified key listener to receive key events from this component.

Usage

From source file:org.boaboa.vistas.FormularioVenta.java

/**
 * Creates new form FormularioVenta//from  w ww  . java  2 s.  c  om
 */
public void Nletras(JTextField a) {
    a.addKeyListener(new KeyAdapter() {
        public void keyTyped(KeyEvent e) {
            char c = e.getKeyChar();
            if (!Character.isDigit(c)) {
                e.consume();
            }
        }
    });
}

From source file:org.openconcerto.erp.core.common.ui.DeviseField.java

public static void addFilteringKeyListener(final JTextField textField) {

    textField.addKeyListener(new KeyAdapter() {
        public void keyTyped(java.awt.event.KeyEvent keyEvent) {

            final char keychar = keyEvent.getKeyChar();

            if (keychar == KeyEvent.VK_BACK_SPACE) {
                return;
            }//from  w w w. j  a va2s  . c  o m

            // pas plus de 2 chiffres apres la virgule
            int pointPosition = textField.getText().indexOf('.');
            if (Character.isDigit(keychar)) {
                if (pointPosition > -1) {
                    // System.err.println("Text Selected :: " + textField.getSelectedText());
                    if (textField.getSelectedText() == null) {
                        if (textField.getCaretPosition() <= pointPosition) {
                            return;
                        } else {
                            if (textField.getText().substring(pointPosition).length() <= 2) {
                                return;
                            }
                        }
                    } else {
                        return;
                    }
                } else {
                    return;
                }
            }

            if (keychar == KeyEvent.VK_PERIOD && textField.getText().indexOf('.') < 0)
                return;
            // if (keychar == KeyEvent.VK_MINUS && (textField.getText().indexOf('-') < 0) &&
            // textField.getCaretPosition() == 0)
            // return;

            keyEvent.consume();
        }
    });
}

From source file:org.openmicroscopy.shoola.agents.imviewer.util.player.MoviePlayerControl.java

/** Adds listeners to the UI components. */
private void initListeners() {
    JTextField editor = view.editor;
    editor.addKeyListener(new KeyAdapter() {

        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER)
                editorActionHandler();/*from w  ww . java  2 s . com*/
        }
    });
    //JButton
    attachButtonListener(view.play, PLAY_CMD);
    attachButtonListener(view.pause, PAUSE_CMD);
    attachButtonListener(view.stop, STOP_CMD);
    //JComboBox
    JComboBox box = view.movieTypes;
    box.setActionCommand("" + MOVIE_TYPE_CMD);
    box.addActionListener(this);
    //JSpinner
    view.fps.addChangeListener(this);
    //MoviePane
    attachFieldListeners(view.startT);
    attachFieldListeners(view.endT);
    attachFieldListeners(view.startZ);
    attachFieldListeners(view.endZ);
    attachButtonListener(view.acrossZ, ACROSS_Z_CMD);
    attachButtonListener(view.acrossT, ACROSS_T_CMD);
    //attachButtonListener(view.acrossZT, ACROSS_ZT_CMD);
    view.tSlider.addPropertyChangeListener(this);
    view.zSlider.addPropertyChangeListener(this);
}

From source file:org.ut.biolab.medsavant.client.project.ProjectWizard.java

private AbstractWizardPage getNamePage() {

    //setup page/*w  ww  .  j  av  a2s  .  c o  m*/
    final DefaultWizardPage page = new DefaultWizardPage(PAGENAME_NAME) {
        @Override
        public void setupWizardButtons() {
            fireButtonEvent(ButtonEvent.HIDE_BUTTON, ButtonNames.FINISH);
            fireButtonEvent(ButtonEvent.HIDE_BUTTON, ButtonNames.BACK);
            if (projectName == null || projectName.equals("")) {
                fireButtonEvent(ButtonEvent.DISABLE_BUTTON, ButtonNames.NEXT);
            } else {
                fireButtonEvent(ButtonEvent.ENABLE_BUTTON, ButtonNames.NEXT);
            }
        }
    };
    page.addText("Choose a name for the project. \n" + "The name cannot already be in use. ");

    //setup text field
    final JTextField namefield = new JTextField();
    namefield.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            if (namefield.getText() != null && !namefield.getText().equals("")) {
                projectName = namefield.getText();
                page.fireButtonEvent(ButtonEvent.ENABLE_BUTTON, ButtonNames.NEXT);
            } else {
                page.fireButtonEvent(ButtonEvent.DISABLE_BUTTON, ButtonNames.NEXT);
            }
        }
    });
    page.addComponent(namefield);
    if (modify) {
        namefield.setText(projectName);
    }

    return page;
}

From source file:org.ut.biolab.medsavant.client.query.view.NumberSearchConditionEditorView.java

@Override
public void loadViewFromSearchConditionParameters(String encoding) throws ConditionRestorationException {

    double[] selectedValues;
    if (encoding == null) {
        selectedValues = null;/*from   w  w  w .  j ava2 s  .  c o  m*/
    } else {
        selectedValues = NumericConditionEncoder.unencodeConditions(encoding);
    }

    final double[] extremeValues = generator.getExtremeNumericValues();
    this.removeAll();

    if (extremeValues == null || (extremeValues[0] == 0 && extremeValues[1] == 0)) {
        JPanel p = new JPanel();
        p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
        p.add(Box.createHorizontalGlue());
        p.add(new JLabel("<html>All values are blank for this condition.</html>"));
        p.add(Box.createHorizontalGlue());
        this.add(p);
        return;
    }

    setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    JPanel p = ViewUtil.getClearPanel();
    ViewUtil.applyVerticalBoxLayout(p);

    JPanel labelPanel = ViewUtil.getClearPanel();
    ViewUtil.applyHorizontalBoxLayout(labelPanel);
    labelPanel.add(Box.createHorizontalGlue());
    labelPanel.add(new JLabel("Filtering variants where " + item.getName() + ": "));
    labelPanel.add(Box.createHorizontalGlue());
    ButtonGroup group = new ButtonGroup();
    //JRadioButton isButton = new JRadioButton("is within the following range:");
    //JRadioButton nullButton = new JRadioButton("is missing");
    //group.add(isButton);
    //group.add(nullButton);

    final JCheckBox nullButton = new JCheckBox("include missing values");

    JPanel bp = ViewUtil.getClearPanel();
    ViewUtil.applyHorizontalBoxLayout(bp);
    p.add(labelPanel);
    p.add(bp);
    add(p);
    final DecimalRangeSlider slider = new DecimalRangeSlider();

    slider.setMajorTickSpacing(5);
    slider.setMinorTickSpacing(1);

    final JTextField fromBox = new JTextField();
    final JTextField toBox = new JTextField();

    nullButton.setSelected(NumericConditionEncoder.encodesNull(encoding));

    nullButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            encodeValue(ViewUtil.parseDoubleFromFormattedString(fromBox.getText()),
                    ViewUtil.parseDoubleFromFormattedString(toBox.getText()), extremeValues[0],
                    extremeValues[1], nullButton.isSelected());
        }
    });

    fromBox.setMaximumSize(new Dimension(10000, 24));
    toBox.setMaximumSize(new Dimension(10000, 24));
    fromBox.setPreferredSize(new Dimension(FROM_TO_WIDTH, 24));
    toBox.setPreferredSize(new Dimension(FROM_TO_WIDTH, 24));
    fromBox.setMinimumSize(new Dimension(FROM_TO_WIDTH, 24));
    toBox.setMinimumSize(new Dimension(FROM_TO_WIDTH, 24));
    fromBox.setHorizontalAlignment(JTextField.RIGHT);
    toBox.setHorizontalAlignment(JTextField.RIGHT);

    final JLabel fromLabel = new JLabel();
    final JLabel toLabel = new JLabel();

    ViewUtil.makeMini(fromLabel);
    ViewUtil.makeMini(toLabel);

    JPanel fromToContainer = ViewUtil.getClearPanel();
    ViewUtil.applyHorizontalBoxLayout(fromToContainer);
    fromToContainer.add(Box.createHorizontalGlue());
    fromToContainer.add(fromBox);
    fromToContainer.add(new JLabel(" - "));
    fromToContainer.add(toBox);
    fromToContainer.add(Box.createHorizontalGlue());

    JPanel minMaxContainer = ViewUtil.getClearPanel();
    minMaxContainer.setLayout(new BoxLayout(minMaxContainer, BoxLayout.X_AXIS));

    JPanel sliderContainer = ViewUtil.getClearPanel();
    sliderContainer.setLayout(new BoxLayout(sliderContainer, BoxLayout.Y_AXIS));
    sliderContainer.add(slider);

    JPanel nullValueContainer = ViewUtil.getClearPanel();
    ViewUtil.applyHorizontalBoxLayout(nullValueContainer);
    nullValueContainer.add(Box.createHorizontalGlue());
    nullValueContainer.add(nullButton);
    nullButton.setBackground(nullValueContainer.getBackground()); //fixes a windows issue.
    nullValueContainer.add(Box.createHorizontalGlue());

    JPanel labelContainer = ViewUtil.getClearPanel();
    labelContainer.setLayout(new BoxLayout(labelContainer, BoxLayout.X_AXIS));
    labelContainer.add(fromLabel);
    labelContainer.add(Box.createHorizontalGlue());
    labelContainer.add(toLabel);
    sliderContainer.add(labelContainer);
    minMaxContainer.add(Box.createHorizontalGlue());
    minMaxContainer.add(sliderContainer);
    minMaxContainer.add(Box.createHorizontalGlue());

    add(fromToContainer);
    add(minMaxContainer);
    add(nullValueContainer);
    add(Box.createVerticalBox());

    slider.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent e) {
            if (slider.isEnabled()) {
                fromBox.setText(ViewUtil.numToString(slider.getLow()));
                toBox.setText(ViewUtil.numToString(slider.getHigh()));
                encodeValue(ViewUtil.parseDoubleFromFormattedString(fromBox.getText()),
                        ViewUtil.parseDoubleFromFormattedString(toBox.getText()), extremeValues[0],
                        extremeValues[1], nullButton.isSelected());
            }
        }
    });

    final KeyListener keyListener = new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            int key = e.getKeyCode();
            if (key == KeyEvent.VK_ENTER) {
                Range selectedRage = new Range(getNumber(fromBox.getText()), getNumber(toBox.getText()));
                setSelectedValues(slider, fromBox, toBox, selectedRage);
            }
        }

        private double getNumber(String s) {
            try {
                return Double.parseDouble(s.replaceAll(",", ""));
            } catch (NumberFormatException ignored) {
                return 0;
            }
        }
    };

    CaretListener caretListener = new CaretListener() {
        @Override
        public void caretUpdate(CaretEvent ce) {
            if (!isAdjustingSlider) {
                try {
                    encodeValue(ViewUtil.parseDoubleFromFormattedString(fromBox.getText()),
                            ViewUtil.parseDoubleFromFormattedString(toBox.getText()), extremeValues[0],
                            extremeValues[1], nullButton.isSelected());
                } catch (Exception e) {
                }
            }
        }
    };

    fromBox.addKeyListener(keyListener);

    toBox.addKeyListener(keyListener);

    fromBox.addCaretListener(caretListener);

    toBox.addCaretListener(caretListener);

    slider.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            isAdjustingSlider = true;
            fromBox.setText(ViewUtil.numToString(slider.getLow()));
            toBox.setText(ViewUtil.numToString(slider.getHigh()));
            isAdjustingSlider = false;
        }
    });

    JPanel bottomContainer = new JPanel();

    bottomContainer.setLayout(new BoxLayout(bottomContainer, BoxLayout.X_AXIS));

    bottomContainer.add(Box.createHorizontalGlue());

    add(bottomContainer);

    setExtremeValues(slider, fromLabel, toLabel, fromBox, toBox, 0,
            new Range(extremeValues[0], extremeValues[1]));

    if (encoding != null) {
        double[] d = NumericConditionEncoder.unencodeConditions(encoding);
        setSelectedValues(slider, fromBox, toBox, new Range(d[0], d[1]));
    }
}

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   www.  j  a  v  a2s.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:richtercloud.reflection.form.builder.typehandler.StringTypeHandler.java

@Override
public Pair<JComponent, ComponentHandler<?>> handle(Type type, String fieldValue, String fieldName,
        Class<?> declaringClass, final FieldUpdateListener<FieldUpdateEvent<String>> updateListener,
        ReflectionFormBuilder reflectionFormBuilder)
        throws IllegalArgumentException, IllegalAccessException, FieldHandlingException {
    final JTextField retValue = new JTextField(fieldValue);
    retValue.addKeyListener(new KeyListener() {

        @Override/*from ww  w.  ja  v a2s.  c om*/
        public void keyTyped(KeyEvent e) {
            updateListener.onUpdate(new FieldUpdateEvent<>(retValue.getText()));
        }

        @Override
        public void keyPressed(KeyEvent e) {
            updateListener.onUpdate(new FieldUpdateEvent<>(retValue.getText()));
        }

        @Override
        public void keyReleased(KeyEvent e) {
            updateListener.onUpdate(new FieldUpdateEvent<>(retValue.getText()));
        }
    }); //action listener doesn't register text change events with keyboard
    return new ImmutablePair<JComponent, ComponentHandler<?>>(retValue, this);
}

From source file:uk.ac.liverpool.narrative.SolutionGraph.java

/**
 * @param template/*from ww  w .  j ava 2 s  . c om*/
 * @param out
 * @param in
 * @param current
 * @return
 * @throws IOException
 */
private StringBuilder mainLoop(final Template template, final JTextArea out, final JTextField in,
        STRIPSState current) throws IOException {
    Collection<Action> aa = ggraph.getOutEdges(current);
    StringBuilder ssf = new StringBuilder();
    if (aa == null) {
        out.append("No action from the start?\n");
        return ssf;
    }

    do {

        if (aa.size() == 1) {
            Action a = aa.iterator().next();
            out.append(actionToString(template, a));
            ssf.append(actionToString(template, a));
            if (a != null) {
                current = ggraph.getOpposite(current, a);

            }
        } else if (aa.size() > 1) {
            int n = 0;
            final Map<Integer, Action> hm = new MapWrapper<Integer, Action>();
            out.append("   Please select the next action: " + "\n");
            Iterator<Action> it = aa.iterator();
            while (it.hasNext()) {
                n++;
                Action a = it.next();
                out.append("   " + n + ") " + actionToString(template, a));
                hm.put(n, a);
            }
            out.append("" + "\n");
            final STRIPSState c2 = current;
            in.addKeyListener(new KeyAdapter() {
                @Override
                public void keyReleased(KeyEvent e) {
                    if (e.getKeyCode() != KeyEvent.VK_ENTER)
                        return;
                    int a = 0;
                    String s = in.getText();
                    try {
                        a = Integer.parseInt(s);
                    } catch (Exception x) {

                    }
                    try {
                        a = Integer.parseInt(s);
                        Action a2 = hm.get(a);
                        if (a2 != null) {
                            out.append(actionToString(template, a2));
                            in.removeKeyListener(this);
                            in.setText("");
                            mainLoop(template, out, in, ggraph.getOpposite(c2, a2));
                        }

                    } catch (Exception x) {
                        return;
                    }
                    super.keyReleased(e);
                }
            });
            return ssf;
        } else {
            break;
        }

        aa = ggraph.getOutEdges(current);
    } while (aa.size() > 0);
    out.append("The end");
    return ssf;
}