Example usage for java.awt Component addFocusListener

List of usage examples for java.awt Component addFocusListener

Introduction

In this page you can find the example usage for java.awt Component addFocusListener.

Prototype

public synchronized void addFocusListener(FocusListener l) 

Source Link

Document

Adds the specified focus listener to receive focus events from this component when this component gains input focus.

Usage

From source file:Main.java

private static void addComponentListeners(Component c, Object... objs) {
    if (c == null)
        return;/*from   ww  w  .  j a  v  a 2s  . co m*/
    ComponentListener componentListener = search(objs, ComponentListener.class);
    FocusListener focusListener = search(objs, FocusListener.class);
    HierarchyBoundsListener hierarchyBoundsListener = search(objs, HierarchyBoundsListener.class);
    HierarchyListener hierarchyListener = search(objs, HierarchyListener.class);
    InputMethodListener inputMethodListener = search(objs, InputMethodListener.class);
    KeyListener keyListener = search(objs, KeyListener.class);
    MouseListener mouseListener = search(objs, MouseListener.class);
    MouseMotionListener mouseMotionListener = search(objs, MouseMotionListener.class);
    MouseWheelListener mouseWheelListener = search(objs, MouseWheelListener.class);
    if (componentListener != null)
        c.addComponentListener(componentListener);
    if (focusListener != null)
        c.addFocusListener(focusListener);
    if (hierarchyBoundsListener != null)
        c.addHierarchyBoundsListener(hierarchyBoundsListener);
    if (hierarchyListener != null)
        c.addHierarchyListener(hierarchyListener);
    if (inputMethodListener != null)
        c.addInputMethodListener(inputMethodListener);
    if (keyListener != null)
        c.addKeyListener(keyListener);
    if (mouseListener != null)
        c.addMouseListener(mouseListener);
    if (mouseMotionListener != null)
        c.addMouseMotionListener(mouseMotionListener);
    if (mouseWheelListener != null)
        c.addMouseWheelListener(mouseWheelListener);
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopLookupField.java

public DesktopLookupField() {
    composition = new JPanel();
    composition.setLayout(new BorderLayout());
    composition.setFocusable(false);//w w  w. ja  v a  2 s . c  o  m

    comboBox = new ExtendedComboBox() {
        @Override
        public void flushValue() {
            super.flushValue();

            flushSelectedValue();
        }
    };
    comboBox.setEditable(true);
    comboBox.setPrototypeDisplayValue("AAAAAAAAAAAA");
    autoComplete = AutoCompleteSupport.install(comboBox, items);

    for (int i = 0; i < comboBox.getComponentCount(); i++) {
        java.awt.Component component = comboBox.getComponent(i);
        component.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                initOptions();

                // update text representation based on entity properties
                updateTextRepresentation();
            }

            @Override
            public void focusLost(FocusEvent e) {
                // Reset invalid value
                checkSelectedValue();
            }
        });
    }
    // set value only on PopupMenu closing to avoid firing listeners on keyboard navigation
    comboBox.addPopupMenuListener(new PopupMenuListener() {
        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            comboBox.updatePopupWidth();
        }

        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            if (!autoComplete.isEditableState()) {
                // Only if really item changed
                Object selectedItem = comboBox.getSelectedItem();
                if (selectedItem instanceof ValueWrapper) {
                    Object selectedValue = ((ValueWrapper) selectedItem).getValue();
                    setValue(selectedValue);
                } else if (selectedItem instanceof String && newOptionAllowed && newOptionHandler != null) {
                    restorePreviousItemText();
                    newOptionHandler.addNewOption((String) selectedItem);
                } else if ((selectedItem != null) && !newOptionAllowed) {
                    updateComponent(prevValue);
                }

                updateMissingValueState();

                fireUserSelectionListeners();
            }
        }

        @Override
        public void popupMenuCanceled(PopupMenuEvent e) {
        }
    });
    comboBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (settingValue || disableActionListener)
                return;
            Object selectedItem = comboBox.getSelectedItem();
            if (selectedItem instanceof String && newOptionAllowed && newOptionHandler != null) {
                restorePreviousItemText();
                newOptionHandler.addNewOption((String) selectedItem);
            }

            updateMissingValueState();
        }
    });

    setFilterMode(DEFAULT_FILTER_MODE);

    textField = new JTextField();
    textField.setEditable(false);
    UserSessionSource sessionSource = AppBeans.get(UserSessionSource.NAME);
    valueFormatter = new DefaultValueFormatter(sessionSource.getLocale());

    composition.add(comboBox, BorderLayout.CENTER);
    impl = comboBox;

    DesktopComponentsHelper.adjustSize(comboBox);
    DesktopComponentsHelper.adjustSize(textField);

    textField.setMinimumSize(
            new Dimension(comboBox.getMinimumSize().width, textField.getPreferredSize().height));

    initClearShortcut();
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopSearchField.java

public DesktopSearchField() {
    composition = new JPanel();
    composition.setLayout(new BorderLayout());
    composition.setFocusable(false);//from   w  w  w .j ava 2  s. com

    comboBox = new SearchComboBox() {
        @Override
        public void setPopupVisible(boolean v) {
            if (!items.isEmpty()) {
                super.setPopupVisible(v);
            } else if (!v) {
                super.setPopupVisible(false);
            }
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if (SearchAutoCompleteSupport.SEARCH_ENTER_COMMAND.equals(e.getActionCommand())) {
                enterHandling = true;
            }

            super.actionPerformed(e);
        }
    };
    comboBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (settingValue || disableActionListener)
                return;

            if ("comboBoxEdited".equals(e.getActionCommand())) {
                Object selectedItem = comboBox.getSelectedItem();

                if (popupItemSelectionHandling) {
                    if (selectedItem instanceof ValueWrapper) {
                        Object selectedValue = ((ValueWrapper) selectedItem).getValue();
                        setValue(selectedValue);
                        updateOptionsDsItem();
                    } else if (selectedItem instanceof String) {
                        handleSearch((String) selectedItem);
                    }
                    popupItemSelectionHandling = false;
                } else if (enterHandling) {
                    if (selectedItem instanceof String) {
                        boolean found = false;
                        String newFilter = (String) selectedItem;
                        if (prevValue != null) {
                            if (Objects.equals(getDisplayString((Entity) prevValue), newFilter)) {
                                found = true;
                            }
                        }
                        if (!found) {
                            handleSearch(newFilter);
                        } else {
                            updateComponent(prevValue);
                            clearSearchVariants();
                        }
                    } else {
                        // Disable variants after select
                        clearSearchVariants();
                    }
                    enterHandling = false;
                }
            }

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    updateEditState();
                }
            });
        }
    });

    Component editorComponent = comboBox.getEditor().getEditorComponent();
    editorComponent.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent e) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    updateEditState();
                }
            });
        }
    });

    comboBox.setEditable(true);
    comboBox.setPrototypeDisplayValue("AAAAAAAAAAAA");
    autoComplete = SearchAutoCompleteSupport.install(comboBox, items);
    autoComplete.setFilterEnabled(false);

    for (int i = 0; i < comboBox.getComponentCount(); i++) {
        java.awt.Component component = comboBox.getComponent(i);
        component.addFocusListener(new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent e) {
                clearSearchVariants();
                // Reset invalid value

                checkSelectedValue();
            }
        });
    }
    // set value only on PopupMenu closing to avoid firing listeners on keyboard navigation
    comboBox.addPopupMenuListener(new PopupMenuListener() {
        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            comboBox.updatePopupWidth();
        }

        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            if (!autoComplete.isEditableState()) {
                // Only if realy item changed
                if (!enterHandling) {
                    Object selectedItem = comboBox.getSelectedItem();
                    if (selectedItem instanceof ValueWrapper) {
                        Object selectedValue = ((ValueWrapper) selectedItem).getValue();
                        setValue(selectedValue);
                        updateOptionsDsItem();
                    } else if (selectedItem instanceof String) {
                        handleSearch((String) selectedItem);
                    }
                } else {
                    popupItemSelectionHandling = true;
                }

                updateMissingValueState();
            }
        }

        @Override
        public void popupMenuCanceled(PopupMenuEvent e) {
            clearSearchVariants();
        }
    });

    setFilterMode(DEFAULT_FILTER_MODE);

    textField = new JTextField();
    textField.setEditable(false);
    UserSessionSource sessionSource = AppBeans.get(UserSessionSource.NAME);
    valueFormatter = new DefaultValueFormatter(sessionSource.getLocale());

    composition.add(comboBox, BorderLayout.CENTER);
    impl = comboBox;

    DesktopComponentsHelper.adjustSize(comboBox);
}

From source file:com.haulmont.cuba.desktop.gui.components.DesktopSuggestionField.java

public DesktopSuggestionField() {
    composition = new JPanel();
    composition.setLayout(new BorderLayout());
    composition.setFocusable(false);/*  ww  w. j  a  v  a2  s .  c o  m*/

    comboBox = new SearchComboBox() {
        @Override
        public void setPopupVisible(boolean v) {
            if (!items.isEmpty()) {
                super.setPopupVisible(v);
            } else if (!v) {
                super.setPopupVisible(false);
            }
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            if (SearchAutoCompleteSupport.SEARCH_ENTER_COMMAND.equals(e.getActionCommand())) {
                enterHandling = true;
            }

            super.actionPerformed(e);
        }
    };

    comboBox.addActionListener(e -> {
        if (settingValue || disableActionListener) {
            return;
        }

        if ("comboBoxEdited".equals(e.getActionCommand())) {
            Object selectedItem = comboBox.getSelectedItem();

            if (popupItemSelectionHandling) {
                if (selectedItem instanceof ValueWrapper) {
                    Object selectedValue = ((ValueWrapper) selectedItem).getValue();
                    setValue(selectedValue);
                }
            } else if (enterHandling) {
                if (selectedItem instanceof String) {
                    boolean found = false;
                    String newFilter = (String) selectedItem;
                    if (prevValue != null) {
                        if (Objects.equals(getDisplayString(prevValue), newFilter)) {
                            found = true;
                        }
                    }

                    final boolean searchStringEqualsToCurrentValue = found;
                    // we need to do it later
                    // unable to change current text from ActionListener
                    SwingUtilities.invokeLater(() -> {
                        updateComponent(prevValue);

                        if (!searchStringEqualsToCurrentValue) {
                            handleOnEnterAction(((String) selectedItem));
                        }
                    });
                } else if (currentSearchComponentText != null) {
                    // Disable variants after select
                    final String enterActionString = currentSearchComponentText;
                    SwingUtilities.invokeLater(() -> {
                        updateComponent(prevValue);

                        handleOnEnterAction(enterActionString);
                    });

                    currentSearchComponentText = null;
                }
            }

            clearSearchVariants();

            popupItemSelectionHandling = false;
            enterHandling = false;
        }

        SwingUtilities.invokeLater(this::updateEditState);
    });

    Component editorComponent = comboBox.getEditor().getEditorComponent();
    editorComponent.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent e) {
            SwingUtilities.invokeLater(() -> {
                updateEditState();

                if (e.getKeyChar() != '\n') {
                    handleSearchInput();
                }
            });
        }

        @Override
        public void keyPressed(KeyEvent e) {
            SwingUtilities.invokeLater(() -> {
                if (e.getKeyCode() == KeyEvent.VK_DOWN && arrowDownActionHandler != null
                        && !comboBox.isPopupVisible()) {
                    arrowDownActionHandler.onArrowDownKeyPressed(getComboBoxEditorField().getText());
                }
            });
        }
    });

    comboBox.setEditable(true);
    comboBox.setPrototypeDisplayValue("AAAAAAAAAAAA");

    autoComplete = SearchAutoCompleteSupport.install(comboBox, items);
    autoComplete.setFilterEnabled(false);

    for (int i = 0; i < comboBox.getComponentCount(); i++) {
        Component component = comboBox.getComponent(i);
        component.addFocusListener(new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent e) {
                clearSearchVariants();
                // Reset invalid value

                checkSelectedValue();
            }
        });
    }

    final JTextField searchEditorComponent = getComboBoxEditorField();
    searchEditorComponent.addActionListener(e -> currentSearchComponentText = searchEditorComponent.getText());

    // set value only on PopupMenu closing to avoid firing listeners on keyboard navigation
    comboBox.addPopupMenuListener(new PopupMenuListener() {
        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
            comboBox.updatePopupWidth();
        }

        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            if (!autoComplete.isEditableState()) {
                popupItemSelectionHandling = comboBox.getSelectedIndex() >= 0;

                // Only if really item changed
                if (!enterHandling) {
                    Object selectedItem = comboBox.getSelectedItem();
                    if (selectedItem instanceof ValueWrapper) {
                        Object selectedValue = ((ValueWrapper) selectedItem).getValue();
                        setValue(selectedValue);

                        clearSearchVariants();
                    }
                }

                updateMissingValueState();
            }
        }

        @Override
        public void popupMenuCanceled(PopupMenuEvent e) {
            clearSearchVariants();
        }
    });

    textField = new JTextField();
    textField.setEditable(false);
    UserSessionSource sessionSource = AppBeans.get(UserSessionSource.NAME);
    valueFormatter = new DefaultValueFormatter(sessionSource.getLocale());

    composition.add(comboBox, BorderLayout.CENTER);
    impl = comboBox;

    DesktopComponentsHelper.adjustSize(comboBox);

    Configuration configuration = AppBeans.get(Configuration.NAME);
    asyncSearchDelayMs = configuration.getConfig(ClientConfig.class).getSuggestionFieldAsyncSearchDelayMs();
}

From source file:com.mac.tarchan.desktop.event.EventQuery.java

/**
 * ?????????????/*from   w  w w .j  a v  a 2  s  .  c  o m*/
 * 
 * @param target ?
 * @param action ?????????????
 * @param property ???????????? 
 * @return ??
 * @see FocusListener#focusLost(java.awt.event.FocusEvent)
 */
public EventQuery blur(Object target, String action, String property) {
    FocusListener focusLost = EventHandler.create(FocusListener.class, target, action, property, "focusLost");
    for (Component child : list) {
        child.addFocusListener(focusLost);
    }
    return this;
}

From source file:com.mac.tarchan.desktop.event.EventQuery.java

/**
 * ????????/*from w ww.j ava 2 s .  c o m*/
 * 
 * @param target ?
 * @param action ?????????????
 * @param property ???????????? 
 * @return ??
 * @see FocusListener#focusGained(java.awt.event.FocusEvent)
 */
public EventQuery focus(Object target, String action, String property) {
    FocusListener focusGained = EventHandler.create(FocusListener.class, target, action, property,
            "focusGained");
    for (Component child : list) {
        child.addFocusListener(focusGained);
    }
    return this;
}

From source file:self.philbrown.javaQuery.$.java

/**
 * Refreshes the listeners for focus changes
 *///from   w w w  . j  av  a2 s.  c om
private void setupFocusListener() {
    for (final Component view : views) {
        view.addFocusListener(new FocusListener() {

            @Override
            public void focusGained(FocusEvent event) {
                if (onFocus != null)
                    onFocus.invoke($.with(view));
            }

            @Override
            public void focusLost(FocusEvent event) {
                if (offFocus != null)
                    offFocus.invoke($.with(view));
            }

        });
    }
}

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

/**
 * Creates the proper UI component for the Mapping item.
 * @param dbFieldType the field type//ww  w. ja v  a  2 s. c o m
 * @param caption the caption
 * @param fieldName the name of the field
 * @param dataFieldLength the length of the definition for that field
 * @param fieldType the field type
 * @return a UI component for editing
 */
protected JComponent createUIComp(final Class<?> dbFieldTypeArg, final String caption, final String fieldName,
        final Short fieldType, final Short fieldLength, final short columns, final short rows,
        final WorkbenchTemplateMappingItem wbtmi) {
    short uiType = WorkbenchTemplateMappingItem.UNKNOWN;
    //System.out.println(wbtmi.getCaption()+" "+wbtmi.getDataType()+" "+wbtmi.getFieldLength());
    Class<?> dbFieldType = dbFieldTypeArg;
    if (dbFieldType == null) {
        // if we can't find a class for the field (i.e. Genus Species, or other 'fake' fields), we say it's a string
        dbFieldType = String.class;
    }

    JComponent comp;
    Component focusComp;

    // handle dates
    if (dbFieldType.equals(Calendar.class) || dbFieldType.equals(Date.class)) {
        //ValFormattedTextField txt = new ValFormattedTextField("Date"); 
        //txt.setColumns(columns == -1 ? DEFAULT_TEXTFIELD_COLS : columns);
        ValTextField txt = new ValTextField(columns);
        txt.getDocument().addDocumentListener(docListener);
        comp = txt;
        focusComp = comp;
        uiType = WorkbenchTemplateMappingItem.TEXTFIELD_DATE;
    }
    //        else if (dbFieldType.equals(Boolean.class)) // strings
    //        {
    //            ValCheckBox checkBox = new ValCheckBox(caption, false, false);
    //            checkBox.addChangeListener(changeListener);
    //            comp      = checkBox;
    //            focusComp = comp;
    //            uiType = WorkbenchTemplateMappingItem.CHECKBOX;
    //        }
    else if (useComboBox(wbtmi)) {
        //ValComboBox comboBox = new ValComboBox(getValues(wbtmi), true);

        final JComboBox comboBox = new JComboBox(getValues(wbtmi));
        comboBox.setName("Form Combo");
        comboBox.setEditable(true);
        comboBox.addActionListener(new ActionListener() {

            /* (non-Javadoc)
             * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
             */
            @Override
            public void actionPerformed(ActionEvent arg0) {
                if (arg0.getSource() == comboBox) {
                    //System.out.println("ComboBox Action!" + ((JComboBox )arg0.getSource()).getName());
                    stateChange();
                }
            }

        });
        //           comboBox.getEditor().getEditorComponent().addFocusListener(new FocusListener() {
        //
        //            /* (non-Javadoc)
        //             * @see java.awt.event.FocusListener#focusGained(java.awt.event.FocusEvent)
        //             */
        //            @Override
        //            public void focusGained(FocusEvent arg0) {
        //               System.out.println("FOCUS GAINED");
        //               
        //            }
        //
        //            /* (non-Javadoc)
        //             * @see java.awt.event.FocusListener#focusLost(java.awt.event.FocusEvent)
        //             */
        //            @Override
        //            public void focusLost(FocusEvent arg0) {
        //               System.out.println("FOCUS LOST");
        //               
        //            }
        //              
        //           });
        comp = comboBox;
        focusComp = comp;
        uiType = WorkbenchTemplateMappingItem.COMBOBOX;
    } else if (useTextField(fieldName, fieldType, fieldLength)) {
        ValTextField txt = new ValTextField(columns);
        txt.getDocument().addDocumentListener(docListener);
        txt.setInputVerifier(new LengthInputVerifier(caption, fieldLength));
        comp = txt;
        focusComp = comp;
        uiType = WorkbenchTemplateMappingItem.TEXTFIELD;

    } else {
        JScrollPane taScrollPane = createTextArea(columns, rows);
        ((JTextArea) taScrollPane.getViewport().getView())
                .setInputVerifier(new LengthInputVerifier(caption, fieldLength));
        comp = taScrollPane;
        focusComp = taScrollPane.getViewport().getView();
        uiType = WorkbenchTemplateMappingItem.TEXTAREA;
    }

    wbtmi.setFieldType(uiType);

    focusComp.addFocusListener(new FocusListener() {
        public void focusGained(FocusEvent e) {
            selectControl(e.getSource());
        }

        public void focusLost(FocusEvent e) {
            //stateChange();
        }
    });

    comp.setEnabled(!readOnly);
    focusComp.setEnabled(!readOnly);

    comp.addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if (!readOnly) {
                if ((e.isControlDown() || e.isMetaDown()) && e.getKeyCode() == KeyEvent.VK_N) {
                    workbenchPane.addRowAfter();
                }
            }
            super.keyTyped(e);
        }

    });
    return comp;
}