working on it ...

Filters

Explore Public Snippets

Sort by

Found 95 snippets matching: combobox

    public by cghersi modified Jul 2, 2014  7403  1  7  2

    Java SWT: Combobox with AutoSuggestion feature

    This component can be safely used when you want to have a combobox with the capability to display automatic filtered suggestions based on the text already entered. It uses a couple of callback actions so that the caller can specify what to do when ENTER key is hit and how to load suggestions. The call back actions are specified by a simple interf
    package com.snip2code.ui.swt;
    
    import java.util.List;
    import java.util.Random;
    
    import org.apache.log4j.Logger;
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.custom.StackLayout;
    import org.eclipse.swt.events.FocusAdapter;
    import org.eclipse.swt.events.FocusEvent;
    import org.eclipse.swt.events.KeyAdapter;
    import org.eclipse.swt.events.KeyEvent;
    import org.eclipse.swt.events.MouseAdapter;
    import org.eclipse.swt.events.MouseEvent;
    import org.eclipse.swt.events.SelectionAdapter;
    import org.eclipse.swt.events.SelectionEvent;
    import org.eclipse.swt.graphics.Rectangle;
    import org.eclipse.swt.layout.FillLayout;
    import org.eclipse.swt.layout.GridData;
    import org.eclipse.swt.layout.GridLayout;
    import org.eclipse.swt.widgets.Composite;
    import org.eclipse.swt.widgets.Control;
    import org.eclipse.swt.widgets.Event;
    import org.eclipse.swt.widgets.Label;
    import org.eclipse.swt.widgets.Listener;
    import org.eclipse.swt.widgets.Shell;
    import org.eclipse.swt.widgets.Table;
    import org.eclipse.swt.widgets.TableItem;
    import org.eclipse.swt.widgets.Text;
    
    import com.snip2code.utils.Utils;
    
    
    /**
     * (c) 2011 snip2code inc.
     * This software is property of snip2code inc. Use or reproduction without permission is prohibited 
     *
     * This widget creates a textfield with an autosuggestion feature.
     * The list of suggestion is shown when the user clicks on the text field or starts typing in the text field
     */
    public class AutoSuggestionComposite extends Composite {
    
    	protected static Logger log = Logger.getLogger(AutoSuggestionComposite.class);
    	
    	private Composite textBoxStackPanel;
    	private StackLayout textboxLayout;
    	private Text textBox;
    	private Label tooltip;
    	private Shell popupShell;
    	private Table table;
    	private String tooltipMsg;
    
    	private ICallback<String, List<String>> loadSuggestionAction;
    	private ICallback<String, String> onEnterAction;
    	
    	private String text;
    	private int numOfDisplayedSuggestions;
    	
    	private static final String POPUPVISIB = "$$$POPUP_VISIB";
    	
    	private String uniqueID; //used to differentiate AutoSuggestion composites in the same dialog
    	private static Random rdn = new Random();
    	
    	/**
    	 * Create the dialog.
    	 * @param parent
    	 * @param style
    	 * @param tooltipMsg message to display when no input is entered
    	 * @param numOfDisplayedSuggestions masimum number of items suggested in the popup of suggestions
    	 * @param loadSuggestionAction callback to routine that loads the suggestions for autocomplete
    	 * @param onEnterAction callback when enter is pressed on the textbox
    	 */
    	public AutoSuggestionComposite(Composite parent, int style, String tooltipMsg, int numOfDisplayedSuggestions, 
    			ICallback<String, List<String>> loadSuggestionAction, ICallback<String, String> onEnterAction) {
    		super(parent, style);
    
    		textboxLayout = new StackLayout();
    		this.loadSuggestionAction = loadSuggestionAction;
    		this.onEnterAction = onEnterAction;
    		this.numOfDisplayedSuggestions = numOfDisplayedSuggestions;
    		this.tooltipMsg = tooltipMsg;
    		
    		uniqueID = rdn.nextInt() + tooltipMsg;
    		
    		createDialogArea();
    	}
    	
    	private void createDialogArea() {
    		this.setBackground(SWTUIUtilities.WHITE);
    		GridLayout gridLayout = new GridLayout();
    		gridLayout.marginHeight = 0;
    		gridLayout.marginWidth = 0;
    		this.setLayout(gridLayout);
    
    		//Panel with textbox and tooltip:
    		textBoxStackPanel = new Composite(this, SWT.NONE);
    		textBoxStackPanel.setLayout(textboxLayout);
    		GridData gdPanel = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
    		gdPanel.verticalIndent = 2;
    		textBoxStackPanel.setLayoutData(gdPanel);
    		
    		tooltip = new Label(textBoxStackPanel, SWT.NONE);
    		tooltip.setBackground(SWTUIUtilities.WHITE);
    		tooltip.setForeground(SWTUIUtilities.LIGHT_GREY);
    		tooltip.setFont(SWTUIUtilities.LBL_TEXT);
    		tooltip.setText(" " + tooltipMsg); //manual horizontal indent, cause StackLayout doesn't allow this feature
    		tooltip.addMouseListener(new MouseAdapter() {
    			@Override
    			public void mouseDown(MouseEvent e) {
    				setControlVisib(textBox, true);
    				textBoxStackPanel.layout();
    				textBox.setFocus();
    				loadSuggestions(null);
    			}
    		});
    		
    		textBox = new Text(textBoxStackPanel, SWT.NONE);
    		textBox.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
    		textBox.setFont(SWTUIUtilities.LBL_TEXT);
    		textBox.setBackground(SWTUIUtilities.WHITE);
    		textBox.setData(POPUPVISIB, uniqueID);
    		
    		//popup for suggestions:
    		popupShell = new Shell(getShell().getDisplay(), SWT.ON_TOP);
    		popupShell.setLayout(new FillLayout());
    		popupShell.setData(POPUPVISIB, uniqueID);
    		popupShell.setBackground(SWTUIUtilities.WHITE);
    		table = new Table(popupShell, SWT.SINGLE);
        	table.getVerticalBar().setVisible(false);
    		table.setFont(SWTUIUtilities.LBL_TEXT);
    		table.setData(POPUPVISIB, uniqueID);
    		for (int i = 0; i < numOfDisplayedSuggestions; i++) {
    			new TableItem(table, SWT.NONE);
    		}
    		
    		//Key Listener for Keyboards events:
    		textBox.addKeyListener(new KeyAdapter() {
    			@Override
    			public void keyReleased(KeyEvent e) {
    				boolean loadSuggestions = true;
    				saveInput();
    				switch (e.keyCode) {
    					case SWT.ARROW_DOWN:
    						int index = (table.getSelectionIndex() + 1) % table.getItemCount();
    						table.setSelection(index);
    						e.doit = false;
    						break;
    					case SWT.ARROW_UP:
    						index = table.getSelectionIndex() - 1;
    						if (index < 0) 
    							index = table.getItemCount() - 1;
    						table.setSelection(index);
    						e.doit = false;
    						break;
    					case SWT.CR:
    					case SWT.LF:
    					case 16777296: //enter in numeric keypad
    						if (popupShell.isVisible() && table.getSelectionIndex() != -1) {
    							textBox.setText(table.getSelection()[0].getText());
    						}
    						
    						loadSuggestions = false;
    						execEnterAction();
    
    						break;
    					case SWT.ESC:
    						popupShell.setVisible(false);
    						break;
    				}
    
    				//only for printable characters, load search history:
    				if (loadSuggestions && (e.keyCode < 256))
    					loadSuggestions(textBox.getText());
    				
    				log.debug("End of key listener");
    			}
    		});
    		
    		//make sure the input entered in the text box is saved and ready to use:
    		textBox.addFocusListener(new FocusAdapter() {
    			@Override
    			public void focusLost(FocusEvent e) {
    				log.debug("Focus lost by textbox of autosugg from " + tooltipMsg);
    				saveInput();
    				checkTooltipVisib();
    				handleFocusLost();
    			}
    			
    			@Override
    			public void focusGained(FocusEvent e) {
    				if (isDisposed() || getShell().isDisposed() || getShell().getDisplay().isDisposed()) 
    					return;
    				log.debug("Focus gained by textbox of autosugg from " + tooltipMsg);
    				loadSuggestions(textBox.getText());
    			}
    		});
    		textBox.addSelectionListener(new SelectionAdapter() {
    			@Override
    			public void widgetSelected(SelectionEvent e) {
    				checkTooltipVisib();
    			}
    		});
    		
    		table.addListener(SWT.DefaultSelection, new Listener() {
    			public void handleEvent(Event event) {
    				textBox.setText(table.getSelection()[0].getText());
    				execEnterAction();
    			}
    		});
    		
    		//hide the popup of suggestions if the focus is out:
    		Listener focusOutListener = new Listener() {
    			public void handleEvent(Event event) {
    				handleFocusLost();
    			}
    		};
    		table.addListener(SWT.FocusOut, focusOutListener);
    		textBox.addListener(SWT.FocusOut, focusOutListener);
    		textBoxStackPanel.addListener(SWT.FocusOut, focusOutListener);
    		popupShell.addListener(SWT.FocusOut, focusOutListener);
    		this.addListener(SWT.FocusOut, focusOutListener);
    
    		getShell().addListener(SWT.Move, new Listener() {
    			public void handleEvent(Event event) {
    				popupShell.setVisible(false);
    				checkTooltipVisib();
    			}
    		});
    		
    		checkTooltipVisib();
    	}
    	
    	private void handleFocusLost() {
    		/* async is needed to wait until focus reaches its new Control */
    		if (isDisposed() || getShell().isDisposed() || getShell().getDisplay().isDisposed()) 
    			return;
    		getShell().getDisplay().asyncExec(new Runnable() {
    			public void run() {
    				log.debug("Running handleFocusLost for " + tooltipMsg);
    				if (isDisposed() || getShell().isDisposed() || getShell().getDisplay().isDisposed()) 
    					return;
    				Control control = getShell().getDisplay().getFocusControl();
    				log.debug("handleFocusLost for " + tooltipMsg + ": control is " + control + ";uniqueID:" + uniqueID);
    				if ((control == null) || (control.getData(POPUPVISIB) == null) || 
    					!control.getData(POPUPVISIB).toString().equals(uniqueID)) {
    					popupShell.setVisible(false);
    				}					
    			}
    		});
    	}
    	
    	/**
    	 * Determines the visibility of textbox content vs tooltip when the textbox is empty
    	 */
    	public void checkTooltipVisib() {
    		if (Utils.isNullOrEmpty(textBox.getText())) 
    			setControlVisib(tooltip, true);
    		else
    			setControlVisib(textBox, true);
    		textBoxStackPanel.layout();
    	}
    	
    	private void execEnterAction() {
    		saveInput();
    		popupShell.setVisible(false);
    		onEnterAction.exec(text);
    	}
    	
        private void loadSuggestions(String prefix) {
        	log.debug("loading suggestions for " + prefix);
    
    //		if (Utils.isNullOrEmpty(prefix))
    //			return;
        	
        	Rectangle textBounds = getShell().getDisplay().map(textBoxStackPanel, null, textBox.getBounds());
        	
    		//load suggestions:
        	List<String> suggestions = loadSuggestionAction.exec(prefix);
        	log.debug("loaded " + suggestions.size() + " suggestions");
        	
        	table.setItemCount(suggestions.size());
    		TableItem[] items = table.getItems();
    		int maxWidthOfItem = 0;
    		log.debug("Changing " + items.length + " items in TablePopup");
    		for (int i = 0; i < items.length; i++) {
    			if (i < suggestions.size()) {
    				String sugg = suggestions.get(i);
    				if (!Utils.isNullOrEmpty(sugg)) {
    					items[i].setText(sugg);
    					int w = items[i].getBounds().width;
    					if (w > maxWidthOfItem)
    						maxWidthOfItem = w;
    				}
    			}
    		}
    //		//avoid the display of horizontal scrollbar when not needed (10 is the width of the scrollbar)
    //		if ((maxWidthOfItem + 10) < textBounds.width)
    //			table.pack();
    		
    		//23 pixels is the height of 1 item in the drop down list; 
    		//always add a blank line at the end of the list to improve readability
    		int popupHeight = (suggestions.size() + 1) * 23; 
    		log.debug("popupHeight for [" + this.tooltipMsg + "]:" + popupHeight);
    		if (popupHeight <= 46)
    			popupHeight = 46; 
    	
    		//set a cap to the maximum height of the popup (17 lines):
    		if (popupHeight > 391) {
    			popupHeight = 391;
    			table.getVerticalBar().setVisible(true);
    		} else {
    			//avoid the display of horizontal scrollbar when not needed (10 is the width of the scrollbar)
    			if ((maxWidthOfItem + 10) < textBounds.width)
    				table.pack();
    			table.getVerticalBar().setVisible(false);
    		}
    		
    		log.debug("setBounds popup:" + textBounds.x + ";" + (textBounds.y + textBounds.height + 4) + ";" + 
    					textBounds.width + ";" + popupHeight);
    		popupShell.setBounds(textBounds.x, textBounds.y + textBounds.height + 4, textBounds.width, popupHeight);
    		popupShell.setVisible(true);		
        }
        
    	private void setControlVisib(Control c, boolean visible) {
    		if (c == null)
    			return;
    		
    		if (visible) 
    			textboxLayout.topControl = c;
    	}
    	
    	private void saveInput() {
    		text = textBox.getText();
    		if (text == null)
    			text = "";
    		text = text.trim();
    	}
    	
    	/**
    	 * Returns the content of the textbox
    	 */
    	public String getText() {
    		return text;
    	}
    	
    	/**
    	 * Sets the content of the textbox
    	 */
    	public void setText(String text) {
    		this.text = text;
    		textBox.setText(text);
    		setControlVisib(textBox, true);
    	}
    	
    	/**
    	 * Hides the popup of suggestions
    	 */
    	public void hideSuggestions() {
    		popupShell.setVisible(false);
    	}
    	
    	@Override
    	public void dispose() {
    		if (popupShell != null) {
    			hideSuggestions();
    			popupShell.dispose();
    		}
    
    		super.dispose();
    	}
    }

    public by cghersi modified Jun 20, 2014  5791  18  6  1

    AutoComplete Combobox for Java Swing GUI

    This class is able to display an autocomplete Combobox using Swing components. Thanks to Brandon Buck: http://www.java2s.com/Code/Java/Swing-Components/AutoCompleteComboBox2.htm
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.geom.Rectangle2D;
    import java.util.ArrayList;
    import java.util.Collections;
    
    import javax.swing.JComboBox;
    import javax.swing.JTextField;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.plaf.basic.BasicComboBoxEditor;
    
    /**
     * This class uses AutoCompleteComboBoxEditor and AutoCompleteTextField to
     * offer and Auto Completion to typed text based on the Objects added to the
     * ComboBox.
     * ** IMPORTANT **
     * Since this is a text-based utility any Object added to this ComboBox (even
     * those that you create) MUST, I repeat MUST have a valid toString method that
     * returns the portion text representation of your
     * @author Brandon Buck
     * @version 1.0
     */
    public class AutoCompleteComboBox<E> extends JComboBox {
        private AutoCompleteTextField editorComp;
    
        public AutoCompleteComboBox() {
            super();
            AutoCompleteComboBoxEditor cbe = new AutoCompleteComboBoxEditor();
            this.editorComp = (AutoCompleteTextField)(cbe.getEditorComponent());
            this.setEditor(cbe);
            this.setEditable(true);
        }
    
        @Override
        public void addItem(Object anObject) {
            super.addItem(anObject);
            editorComp.addPossibility(anObject.toString());
        }
    
        @Override
        public void removeAllItems() {
            super.removeAllItems();
            editorComp.removeAllPossibilities();
        }
        
        public AutoCompleteTextField getEditorComponent() {
            return editorComp;
        }
    
        @Override
        public void removeItemAt(int index) {
            E anObject = getItemAt(index);
            super.removeItemAt(index);
            editorComp.removePossibility(anObject.toString());
        }
    
        @Override
        public E getItemAt(int index) {
            return (E)super.getItemAt(index);
        }
    
        @Override
        public E getSelectedItem() {
            return (E)super.getSelectedItem();
        }
    }
    /**
     * A JTextField that will display a whole word as the user types a portion of
     * it. A better example would be, as the user types the first letter in the
     * word "text" the AutoCompleteTextField will display the letter "t" in the
     * components current foreground color and display the rest of the word "ext"
     * in the specified incomplete color (default is Color.GRAY.brighter()). The
     * displayed text changes as the user types "e" so now getText() would return
     * the string "te" and the incomplete portion displayed by the editor will be
     * "xt." If Enter is pressed while an incomplete word is being processes, then
     * the AutoCompleteTextField will replace what he user has typed with the
     * completed word and consider itself "finished," and if Enter is pressed a
     * second time, then it will fire a KeyEvent normally.
     * @author Brandon Buck
     * @version 1.0
     */
     class AutoCompleteTextField extends JTextField implements KeyListener,
                DocumentListener {
        private ArrayList<String> possibilities;
        private int currentGuess;
        private Color incompleteColor;
        private boolean areGuessing;
        private boolean caseSensitive;
    
        /**
         * Constructs a new AutoCompleteTextField with the 5 columns by default and
         * no case sensitivity on comparisons of guesses to entered text.
         */
        public AutoCompleteTextField() {
            this(5, false);
        }
    
        /**
         * Constructs a new AutoCompleteTextField with the specified number of
         * columns with no case sensitivity when comparing the current guess to the
         * text entered.
         * @param columns The number of columns you wish for the width of this AutoCompleteTextField.
         */
        public AutoCompleteTextField(int columns) {
            this(columns, false);
        }
    
        /**
         * Creates a new AutoCompleteTextField with the given number of columns in
         * width and the setting for case sensitivity when comparing the current
         * guess to the entered text.
         * @param columns The number of columns of text for this component.
         * @param caseSensitive <code>true</code> or <code>false</code> depending on if you want comparisons to be case sensitive or not.
         */
        public AutoCompleteTextField(int columns, boolean caseSensitive) {
            super.setColumns(columns);
            this.possibilities = new ArrayList<String>();
            this.incompleteColor = Color.GRAY.brighter();
            this.currentGuess = -1;
            this.areGuessing = false;
            this.caseSensitive = caseSensitive;
            this.addKeyListener(this);
            this.getDocument().addDocumentListener(this);
        }
    
        /** Add a new possibility to the list of possibilities.
         * Add a new possibility to the list of possibilities for the
         * AutoCommpleteTextField to process.
         * @param possibility The new possibility to add.
         */
        public void addPossibility(String possibility) {
            this.possibilities.add(possibility);
            Collections.sort(possibilities);
        }
    
        /** Removes a possibility from the list of possibilities.
         * Removes the given possibility from the list of possibilities so that it
         * will no longer be matched.
         * @param possibility The possibility to remove.
         */
        public void removePossibility(String possibility) {
            this.possibilities.remove(possibility);
        }
    
        /** Removes all possibilities in the list.
         * Removes every possibility in the list and starts over with an empty list
         * ready for new possibilities to be added.
         */
        public void removeAllPossibilities() {
            this.possibilities = new ArrayList<String>();
        }
    
        /** Sets the color to draw the incomplete guess in.
         * This sets the color that the incomplete guess text is drawn in.
         * @param incompleteColor The new color to draw the incomplete guess with.
         */
        public void setIncompleteColor(Color incompleteColor) {
            this.incompleteColor = incompleteColor;
        }
    
        /** Returns the current guess from the list of possibilities.
         * Returns the string at the location of the current guess in the list of 
         * possibilities.
         * @return The current guess as a String.
         */
        private String getCurrentGuess() {
            if (this.currentGuess != -1)
                return this.possibilities.get(this.currentGuess);
    
            return this.getText();
        }
    
        /**
         * Changes the current case sensitive setting to the given setting.
         * @param caseSensitive <code>true</code> or <code>false</code> depending on if you want comparisons to be case sensitive or not.
         */
        public void setCaseSensitive(boolean caseSensitive) {
            this.caseSensitive = caseSensitive;
        }
    
        private void findCurrentGuess() {
            String entered = this.getText();
            if (!this.caseSensitive)
                entered = entered.toLowerCase();
    
            for (int i = 0; i < this.possibilities.size(); i++) {
                currentGuess = -1;
    
                String possibility = this.possibilities.get(i);
                if (!this.caseSensitive)
                    possibility = possibility.toLowerCase();
                if (possibility.startsWith(entered)) {
                    this.currentGuess = i;
                    break;
                }
            }
        }
    
        @Override
        public void setText(String text) {
            super.setText(text);
            this.areGuessing = false;
            this.currentGuess = -1;
        }
    
        @Override
        public void paintComponent(Graphics g) {
            String guess = this.getCurrentGuess();
            String drawGuess = guess;
    
            super.paintComponent(g);
            String entered = this.getText();
            Rectangle2D enteredBounds = g.getFontMetrics().getStringBounds(entered, g);
    
            if (!(this.caseSensitive)) {
                entered = entered.toLowerCase();
                guess = guess.toLowerCase();
            }
            
            if (!(guess.startsWith(entered)))
                this.areGuessing = false;
    
            if (entered != null && !(entered.equals("")) 
                    && this.areGuessing) {
                String subGuess = drawGuess.substring(entered.length(), drawGuess.length());
                Rectangle2D subGuessBounds = g.getFontMetrics().getStringBounds(drawGuess, g);
    
                int centeredY = ((getHeight() / 2) + (int)(subGuessBounds.getHeight() / 2));
    
                g.setColor(this.incompleteColor);
                g.drawString(subGuess + "   press ENTER to send or \u2192 to fill", (int)(enteredBounds.getWidth()) + 2, centeredY - 2);
            }
        }
    
        public void keyTyped(KeyEvent e) { }
    
        public void keyPressed(KeyEvent e) { 
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                if (this.areGuessing) {
                    this.setText(this.getCurrentGuess());
                    this.areGuessing = false;
                }
            }
    
            if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                if (this.areGuessing) {
                    this.setText(this.getCurrentGuess());
                    this.areGuessing = false;
                    e.consume();
                }
            }
        }
        
        public void keyReleased(KeyEvent e) { }
    
        public void insertUpdate(DocumentEvent e) {
            String temp = this.getText();
    
            if (temp.length() == 1)
                this.areGuessing = true;
    
            if (this.areGuessing)
                this.findCurrentGuess();
    
        }
    
        public void removeUpdate(DocumentEvent e) {
            String temp = this.getText();
    
            if (!(this.areGuessing))
                this.areGuessing = true;
    
            if (temp.length() == 0)
                this.areGuessing = false;
            else if (this.areGuessing) {
                this.findCurrentGuess();
            }
        }
    
        public void changedUpdate(DocumentEvent e) { }
    }
    
    
     class AutoCompleteComboBoxEditor extends BasicComboBoxEditor {
          public AutoCompleteComboBoxEditor() {
              editor = createEditorComponent();
          }
    
          @Override
          protected AutoCompleteTextField createEditorComponent() {
              AutoCompleteTextField acEditor = new AutoCompleteTextField(9);
              acEditor.setBorder(null);
              return acEditor;
          }
      }

    public by msdn modified Jan 12, 2015  104338  0  5  0

    CreateComboBoxWithSecurityQuestions: Returns a <see cref="ComboBox" /> object whose <see cref="ComboBox.ItemsSource" /> property is initialized with the resource strings defined in <see cref="SecurityQuestions" />.

    Returns a object whose property is initialized with the resource strings defined in .
    /// <summary>
    /// Returns a <see cref="ComboBox" /> object whose <see cref="ComboBox.ItemsSource" /> property
    /// is initialized with the resource strings defined in <see cref="SecurityQuestions" />.
    /// </summary>
    private static ComboBox CreateComboBoxWithSecurityQuestions()
    {
        // Use reflection to grab all the localized security questions
        IEnumerable<string> availableQuestions = from propertyInfo in typeof(SecurityQuestions).GetProperties()
                                                 where propertyInfo.PropertyType.Equals(typeof(string))
                                                 select (string)propertyInfo.GetValue(null, null);
    
        // Create and initialize the ComboBox object
        ComboBox comboBox = new ComboBox();
        comboBox.ItemsSource = availableQuestions;
        return comboBox;
    }

    public by msdn modified Jan 9, 2015  95268  0  6  0

    CreateComboBoxWithSecurityQuestions

    Returns a object whose property is initialized with the resource strings defined in
    /// <returns>
    ///   Returns a <see cref="ComboBox" /> object whose <see cref="ComboBox.ItemsSource" /> property
    ///   is initialized with the resource strings defined in <see cref="SecurityQuestions" />
    /// </returns>
    private static ComboBox CreateComboBoxWithSecurityQuestions()
    {
        // Use reflection to grab all the localized security questions
        IEnumerable<string> availableQuestions = from propertyInfo in typeof(SecurityQuestions).GetProperties()
                                                 where propertyInfo.PropertyType.Equals(typeof(string))
                                                 select (string)propertyInfo.GetValue(null, null);
    
        // Create and initialize the ComboBox object
        ComboBox comboBox = new ComboBox();
        comboBox.ItemsSource = availableQuestions;
        return comboBox;
    }

    external by Github modified Dec 24, 2014  171  1  2  0

    Get and clear values from a combobox

    Get and clear values from a combobox: GetandClearCmbBox.controller.js
    sap.ui.controller("sap.ui.app.demoProject.view.Master", {
    	
    	handleGetCmbBoxValue : function (evt) {
    		getCoreById = sap.ui.getCore().byId;
    		
    		var cmbBoxSelectedValue = getCoreById('Master--cmbBox').getSelectedKey();
    	},
    
    	handleClearCmbBoxValue : function (evt){
    		getCoreById = sap.ui.getCore().byId;
    		
    		var cmbBoxSelectedValue = getCoreById('Master--cmbBox').setSelectedKey("");
    	}
    });
    
    

    external by Github modified Dec 24, 2014  80  1  1  0

    oData filters to a comboBox

    oData filters to a comboBox: ODataCombobox.controller.js
    sap.ui.controller("sap.ui.app.demoProject.view.Master", {
    	
    	onInit : function (evt) {
    		var url = "proxy/http/<odata_url>/sap/opu/odata/sap/<odata_url_end>/";
    		var oModel = new sap.ui.model.odata.ODataModel(url, true, "username", "password");
    		this.getView().setModel(oModel);
    
    		var myfilters = [];
    
    		var FilterOperator = sap.ui.model.FilterOperator;
    		var filter1 = new sap.ui.model.Filter("<field_name>", FilterOperator.EQ, "<filter_value>");
    		myfilters.push(filter1);
    
    		var mylist = this.getView().byId("<combo_box_variable_name>");
    		var mybinding = mylist.getBinding("items");
    		mybinding.filter(myfilters);
    	}
    });
    
    

    external by toby modified Apr 14, 2015  57  1  1  0

    Add a collection of strings to a VB.NET ComboBox

    Add a collection of strings to a VB.NET ComboBox: FillComboBox
    Function FillComboBox(cb As Control, cc As Collection) As Boolean
        Dim cbc As ComboBox = CType(cb, ComboBox)
        If cc.Count = 0 Then
            Return False
        End If
        For Each cn In cc
            cbc.Items.Add(cn)
        Next
        Return True
    End Function
    
    
    

    external by David y Goliat modified Oct 8, 2016  57  0  1  0

    Hover over a JavaFX Label to reveal a ComboBox to change the label's text.

    Hover over a JavaFX Label to reveal a ComboBox to change the label's text.: Hoverboard.java
    import javafx.application.Application;
    import javafx.geometry.*;
    import javafx.scene.Scene;
    import javafx.scene.control.*;
    import javafx.scene.layout.*;
    import javafx.stage.Stage;
    
    public class Hoverboard extends Application {
    
        public class TextChooser extends StackPane {
            private Label label = new Label();
            private ComboBox<String> combo = new ComboBox<>();
    
            public TextChooser(String... options) {
                StackPane.setAlignment(label, Pos.CENTER_LEFT);
                StackPane.setAlignment(combo, Pos.CENTER_LEFT);
    
                label.textProperty().bind(
                    combo.getSelectionModel().selectedItemProperty()
                );
                label.visibleProperty().bind(
                    combo.visibleProperty().not()
                );
                label.setPadding(new Insets(0, 0, 0, 9));
    
                combo.getItems().setAll(options);
                combo.getSelectionModel().select(0);
                combo.setVisible(false);
    
                label.setOnMouseEntered(event -> combo.setVisible(true));
                combo.showingProperty().addListener(observable -> {
                    if (!combo.isShowing()) {
                        combo.setVisible(false);
                    }
                });
                combo.setOnMouseExited(event -> {
                    if (!combo.isShowing()) {
                        combo.setVisible(false);
                    }
                });
    
                getChildren().setAll(label, combo);
            }
        }
    
        @Override
        public void start(Stage stage) throws Exception {
            TextChooser textChooser = new TextChooser(
                "xyzzy", "frobozz", "foobar"
            );
    
            VBox layout = new VBox(textChooser);
            layout.setPadding(new Insets(10));
    
            stage.setScene(new Scene(layout));
            stage.show();
        }
    
        public static void main(String[] args) {
            launch(Hoverboard.class);
        }
    
    }
    
    

    external by jerome2 modified Jul 15, 2015  45  0  1  0

    try to show the categorie list of choice in a select combobox collection... from partial view from "photos" area model/controller

    try to show the categorie list of choice in a select combobox collection... from partial view from "photos" area model/controller: gistfile1.txt
    # my _form.haml view call as partial from "edit.haml or new.haml" (first call inside div class "associations" for try to do it...
    
    = simple_form_for(@photo) do |f|
      - if @photo.errors.any?
        %div#error_explanation
          %h2
            = pluralize(@photo.errors.count, "error")
            prohibited this photo from being saved:
          %ul
            - @photo.errors.full_messages.each do |message|
              %li= message
      .row
        .col-md-4
          = f.input :photo, as: :file, label: "Add an image", class: "upload", :input_html => { onchange: "readURL(this);" }
          = f.hidden_field :retained_photo
          - if @photo.photo
            = image_tag(@photo.photo.thumb('140x140!').url, alt: @photo.title, class: 'imgprev')
          - else
            %img.imgprev{:src => '#', :alt => 'preview'}
          .associations
            = f.association :travail, collection: Wconcern.all, 
                                                    label_method: categories, 
                                                    label: "Categorie",
                                                    prompt: true
            - if @wconcern.travails?
              .cat_article= f.association :travail, collection: Wconcern.all, 
                                                    label_method: :concern, 
                                                    label: "Type concern",
                                                    selected: concerned_id_selected(f.object),
                                                    prompt: true
              .art_title= f.association :travail, label: "Article title"
            - if @wconcern.voyages?
              .cat_article= f.association :voyage, collection: Vconcern.all, 
                                                    label_method: :concern, 
                                                    label: "Type concern",
                                                    selected: concerned_id_selected(f.object),
                                                    prompt: true
              .art_title= f.association :voyage, label: "Article title"
            -else
              .cat_article
              .art_title
        .col-md-8
          .field
            = f.input :title
          .field
            = f.input :description, as: :text, :input_html => { :class => "ckeditor ", :id => "description" }
          .actions
            - if @photo.id
              = f.button :magic_submit, cancel: photo_path(@photo)
            - else
              = f.button :magic_submit, cancel: photos_path
    
    #the wconcern.rb model:
    class Wconcern < ActiveRecord::Base
      extend Dragonfly::Model
      dragonfly_accessor :image
      
      has_many :travails
      
      enum categorie: [ :no_one, :travails, :voyages ]
      
      validates :concern, presence: true,
                        length: {minimum: 3, maximum: 16}
                      
    end
    
    
    

    external by Sebastian Müller modified Mar 22, 2015  34  0  1  0

    WP8.1 combobox bug

    WP8.1 combobox bug: gistfile1.txt
    Description of the bug:
    I aim to replicate the WP maps floor selector in my app. Everything works fine when I set the first item as the default item. When selecting another item as the default one, it breaks the Combobox.
    
    Expected behavior: "1" in the combobox is selectable
    Actual behavior: "1" cannot be selected
    
    Sample solution: http://1drv.ms/1LJvgh4
    
    Maybe related to https://social.msdn.microsoft.com/Forums/en-US/eb53680d-ead2-4900-b51e-ca3ac060cedd/possible-bug-first-item-in-a-combobox-containing-12-items-is-unselectable ?
    
    
    • Public Snippets
    • Channels Snippets