synthcomboboxui.java

来自「java jdk 1.4的源码」· Java 代码 · 共 1,736 行 · 第 1/4 页

JAVA
1,736
字号
		result = getDefaultSize();		if (comboBox.isEditable()) {		    result.width = 100;		}            }        }	if ( comboBox.isEditable() ) {	    Dimension d = editor.getPreferredSize();	    result.width = Math.max(result.width,d.width);	    result.height = Math.max(result.height,d.height);	}                // Set the cached value        cachedDisplaySize.setSize(result.width, result.height);        isDisplaySizeDirty = false;        return result;    }    /**     * This has been refactored out in hopes that it may be investigated and     * simplified for the next major release. adding/removing     * the component to the currentValuePane and changing the font may be      * redundant operations.     */    private Dimension getSizeForComponent(Component comp) {	currentValuePane.add(comp);	comp.setFont(comboBox.getFont());	Dimension d = comp.getPreferredSize();	currentValuePane.remove(comp);	return d;    }	    //    // end Size Utility Methods    //=============================    //=================================    // begin Keyboard Action Management    //    /**     * Adds keyboard actions to the JComboBox.  Actions on enter and esc are already     * supplied.  Add more actions as you need them.     */    protected void installKeyboardActions() {	InputMap km = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);	SwingUtilities.replaceUIInputMap(comboBox, JComponent.			     WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, km);        LazyActionMap.installLazyActionMap(comboBox, this);    }    InputMap getInputMap(int condition) {	if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT) {            SynthContext context = getContext(comboBox, ENABLED);            InputMap map = (InputMap)context.getStyle().get(context,                                                 "ComboBox.ancestorInputMap");            context.dispose();            return map;	}	return null;    }    static Action homeAction = new NavigationalAction(KeyEvent.VK_HOME);    static Action endAction = new NavigationalAction(KeyEvent.VK_END);    static Action pgUpAction = new NavigationalAction(KeyEvent.VK_PAGE_UP);    static Action pgDownAction = new NavigationalAction(KeyEvent.VK_PAGE_DOWN);    public void loadActionMap(JComponent c, ActionMap map) {	map.put("hidePopup", new HidePopupAction());	map.put("pageDownPassThrough", pgDownAction);	map.put("pageUpPassThrough", pgUpAction);	map.put("homePassThrough", homeAction);	map.put("endPassThrough", endAction);	map.put("selectNext", new DownAction());	map.put("togglePopup", new AltAction());	map.put("spacePopup", new SpaceAction());	map.put("selectPrevious", new UpAction());	map.put("enterPressed", new EnterAction());    }    boolean isTableCellEditor() {	return isTableCellEditor;    }    /**     * Removes the focus InputMap and ActionMap.     */    protected void uninstallKeyboardActions() {	SwingUtilities.replaceUIInputMap(comboBox, JComponent.				 WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null);	SwingUtilities.replaceUIActionMap(comboBox, null);    }    //    // Actions    //     class HidePopupAction extends AbstractAction {	public void actionPerformed( ActionEvent e ) {	    JComboBox comboBox = (JComboBox)e.getSource();	    if ( comboBox.isEnabled() ) {		comboBox.firePopupMenuCanceled();		comboBox.setPopupVisible(false);	    }	}	public boolean isEnabled() {	    return comboBox.isPopupVisible();	}    }    static class NavigationalAction extends AbstractAction {        int keyCode;        NavigationalAction(int keyCode) {	    this.keyCode = keyCode;        }	public void actionPerformed(ActionEvent ev) {	    JComboBox comboBox = (JComboBox)ev.getSource();	    int index = getNextIndex(comboBox);            if (index >= 0 && index < comboBox.getItemCount()) {                comboBox.setSelectedIndex(index);            }        }        int getNextIndex(JComboBox comboBox) {            switch (keyCode) {            case KeyEvent.VK_PAGE_UP:                int listHeight = comboBox.getMaximumRowCount();                int index = comboBox.getSelectedIndex() - listHeight;                return (index < 0 ? 0: index);            case KeyEvent.VK_PAGE_DOWN:                listHeight = comboBox.getMaximumRowCount();                index = comboBox.getSelectedIndex() + listHeight;                int max = comboBox.getItemCount();                return (index < max ? index: max-1);            case KeyEvent.VK_HOME:                return 0;            case KeyEvent.VK_END:                return comboBox.getItemCount() - 1;            default:                return comboBox.getSelectedIndex();            }        }    }    static class DownAction extends AbstractAction {	public void actionPerformed(ActionEvent e) {	    JComboBox comboBox = (JComboBox)e.getSource();	    if ( comboBox.isEnabled() && comboBox.isShowing() ) {		if ( comboBox.isPopupVisible() ) {                    // PENDING: getUI() change		    SynthComboBoxUI ui = (SynthComboBoxUI)comboBox.getUI();		    ui.selectNextPossibleValue();		} else {		    comboBox.setPopupVisible(true);		}	    }	}    }    static class EnterAction extends AbstractAction {	public void actionPerformed(ActionEvent e) {	    JComboBox comboBox = (JComboBox)e.getSource();	    if ( !comboBox.isEnabled() ) {		return;	    }            // PENDING: getUI() change	    SynthComboBoxUI ui = (SynthComboBoxUI)comboBox.getUI();	    if ( ui.isTableCellEditor() ) {		// Forces the selection of the list item if the		// combo box is in a JTable.		comboBox.setSelectedIndex(ui.popup.getList().getSelectedIndex());	    } 	    else {		if (comboBox.isPopupVisible()) {		    comboBox.setPopupVisible(false);		} else {		    // Call the default button binding.		    // This is a pretty messy way of passing an event through		    // to the root pane.		    JRootPane root = SwingUtilities.getRootPane(comboBox);		    if (root != null) {			InputMap im = root.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);			ActionMap am = root.getActionMap();			if (im != null && am != null) {			    Object obj = im.get(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER,0));			    if (obj != null) {				Action action = am.get(obj);				if (action != null) {				    action.actionPerformed(e);				}			    }			}		    }		}	    }	}    }    static class AltAction extends AbstractAction {	public void actionPerformed(ActionEvent e) {	    JComboBox comboBox = (JComboBox)e.getSource();	    if ( comboBox.isEnabled() ) {                // PENDING: getUI change		SynthComboBoxUI ui = (SynthComboBoxUI)comboBox.getUI();		if ( ui.isTableCellEditor() ) {		    // Forces the selection of the list item if the		    // combo box is in a JTable.		    comboBox.setSelectedIndex(ui.popup.getList().getSelectedIndex());		} 		else {		    comboBox.setPopupVisible(!comboBox.isPopupVisible());		}            }	}    }    // Same as the AltAction except that it doesn't invoke if    // the space key is pressed in the editable text portion.    static class SpaceAction extends AltAction {	public void actionPerformed(ActionEvent e) {	    JComboBox comboBox = (JComboBox)e.getSource();	    if ( !comboBox.isEditable() ) {		super.actionPerformed(e);            }	}    }        static class UpAction extends AbstractAction {	public void actionPerformed(ActionEvent e) {	    JComboBox comboBox = (JComboBox)e.getSource();	    if ( comboBox.isEnabled() ) {		SynthComboBoxUI ui = (SynthComboBoxUI)comboBox.getUI();		if (ui.isPopupVisible(comboBox)) {                    ui.selectPreviousPossibleValue();                }            }        }    }    //    // end Keyboard Action Management    //===============================    class EditorFocusListener extends FocusAdapter {	/**	 * This will make the comboBox fire an ActionEvent if the editor	 * value is different from the selected item in the model.  	 * This allows for the entering of data in the combo box editor and	 * sends notification when tabbing or clicking out of focus.	 */         public void focusLost( FocusEvent e ) {	    ComboBoxEditor editor = comboBox.getEditor();            Object item = editor.getItem();            if (!e.isTemporary() && item != null && 		!item.equals( comboBox.getSelectedItem())) {                comboBox.actionPerformed                    (new ActionEvent(editor, 0, "",                                     EventQueue.getMostRecentEventTime(), 0));            }        }    }    class EditorActionListener implements ActionListener {	// Fix for 4515752: Forward the Enter pressed on the	// editable combo box to the default button if the item has	// not changed.	// Note: This could depend on event ordering. The first ActionEvent	// from the editor may be handled by the JComboBox in which case, the	// enterPressed action will always be invoked.	public void actionPerformed(ActionEvent evt) {	    Object item = comboBox.getEditor().getItem();	    if (item != null && item.equals(comboBox.getSelectedItem())) {		ActionMap am = comboBox.getActionMap();		if (am != null) {		    Action action = am.get("enterPressed");		    if (action != null) {			action.actionPerformed(new ActionEvent(comboBox, evt.getID(), 							       evt.getActionCommand(),							       evt.getModifiers()));		    }		}	    }	}    }    /**     * From BasicComboBoxRenderer v 1.18.     */    static class SynthComboBoxRenderer extends JLabel implements ListCellRenderer, UIResource {        public SynthComboBoxRenderer() {            super();            setName("ComboBox.renderer");            setText(" ");            // PENDING: rethink this, we shouldn't have to force this.            ((SynthLabelUI)getUI()).forceFetchStyle(this);        }        public void addNotify() {            String oldName = getName();            setName("ComboBox.renderer");            super.addNotify();            setName(oldName);        }        public boolean isOpaque() {            return true;        }        public Component getListCellRendererComponent(JList list, Object value,                         int index, boolean isSelected, boolean cellHasFocus) {            // PENDING: There needs to be a way to alter the selected state            // of the UI.            setName("ComboBox.rendererx");            if (isSelected) {                setBackground(list.getSelectionBackground());                setForeground(list.getSelectionForeground());            }            else {                setBackground(list.getBackground());                setForeground(list.getForeground());            }            setFont(list.getFont());            if (value instanceof Icon) {                setIcon((Icon)value);                setText("");            }            else {                String text = (value == null) ? " " : value.toString();                if ("".equals(text)) {                    text = " ";                }                setText(text);            }            return this;        }    }    /**     * From BasicCombBoxEditor v 1.24.     */    private static class SynthComboBoxEditor implements                              ComboBoxEditor, UIResource {        protected JTextField editor;        private Object oldValue;        public SynthComboBoxEditor() {            editor = new JTextField("",9);            editor.setName("ComboBox.textField");        }        public Component getEditorComponent() {            return editor;        }        /**          * Sets the item that should be edited.          *         * @param anObject the displayed value of the editor         */        public void setItem(Object anObject) {            String text;            if ( anObject != null )  {                text = anObject.toString();                oldValue = anObject;            } else {                text = "";            }            // workaround for 4530952            if (!text.equals(editor.getText())) {                editor.setText(text);            }        }        public Object getItem() {            Object newValue = editor.getText();                    if (oldValue != null && !(oldValue instanceof String))  {                // The original value is not a string. Should return the value in it's                // original type.                if (newValue.equals(oldValue.toString())) {                    return oldValue;                } else {                    // Must take the value from the editor and get the value and cast it to the new type.                    Class cls = oldValue.getClass();                    try {                        Method method = cls.getMethod("valueOf", new Class[]{String.class});                        newValue = method.invoke(oldValue, new Object[] { editor.getText()});                    } catch (Exception ex) {                        // Fail silently and return the newValue (a String object)                    }                }            }            return newValue;        }        public void selectAll() {            editor.selectAll();            editor.requestFocus();        }        public void addActionListener(ActionListener l) {            editor.addActionListener(l);        }        public void removeActionListener(ActionListener l) {            editor.removeActionListener(l);        }    }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?