CombBox itemMatchingFunction

I have extended a ComboBox for 2 major reasons, specialized skinning and to provide for custom item matching.  I'm having a problem with the itemMatchingFunction.  I can see the function being invoked and the appropriate items included and excluded from the resultant vector.  But what is being displayed is still the entire list if items in the data provider.  Any comments, questions or suggestions would be appreciated!
Thanks,
Brenda
  Here are some snippets of my code:
        public function FilteredComboBox() {
            super();
            this.openOnInput = true;
            this.itemMatchingFunction = matchingFunction;
        public function matchingFunction(cb:ComboBox, text:String):Vector.<int> {
            var results:Vector.<int> = new Vector.<int>;
            var item:String;
            var entered:String = text.toLowerCase();
            var itemIdx:int;
            for(var idx:int = 0; idx < cb.dataProvider.length; idx++) {
                item = cb.dataProvider.getItemAt(idx) as String;
                item = item.toLowerCase();
                itemIdx = item.indexOf(entered);
                if(item.indexOf(entered) > -1) {
                    results.push(idx);
            return results;

Try the below sample code for the scenario required. This might be helpful.
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600">
    <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <fx:Script>
        <![CDATA[
            import mx.collections.ArrayCollection;
            import spark.events.IndexChangeEvent;
            import spark.events.TextOperationEvent;
            [Bindable]
            private var arrC:ArrayCollection = new ArrayCollection([{label:'Ronak'},{label:'Virat'},{label:'Ronaksdfsdfsf'},{label:'Ronaksdf sdf'},{label:'Ronak'},{label:'Ronak'},{label:'Ronak'},{label:'Ronak'},{label:'Ronak'},{lab el:'Ronak'},{label:'Ronak'}]);
            private var flag:Boolean = true;
            protected function cb_changeHandler():void
                if(flag == true)
                    cb.textInput.addEventListener(TextOperationEvent.CHANGE,changeHandler);
                    flag = false;
                // TODO Auto-generated method stub
            private function changeHandler(e:*):void
                cb.textInput.removeEventListener(TextOperationEvent.CHANGE,changeHandler);
                arrC.filterFunction = doFilter;
                arrC.refresh();
                flag = true;
            private function doFilter(item:Object):Boolean
                if(String(item.label).toLowerCase().indexOf(cb.textInput.text.slice(0,cb.textInput.select ionAnchorPosition).toLowerCase())>-1)
                    return true;
                return false;
        ]]>
    </fx:Script>
    <s:ComboBox id="cb" dataProvider="{arrC}"  updateComplete="cb_changeHandler()"/>
</s:Application>

Similar Messages

  • Jtree Node with JComboBox don't work properly in Windows Vista!

    Hi people!
    i create a Jtree component and create a special node, that is a <strong>JPanel with a JLabel + JCombobox</strong>!
    Only the direct childs of root have this special node.
    A can put this work properly in Windows XP, like the picture:
    [XP Image|http://feupload.fe.up.pt/get/jcgd0rY5p9PoFPG]
    And in Windows Vista the same code appear like this:
    [Vista Image|http://feupload.fe.up.pt/get/Ylajl6hlCUFc0xe]
    <strong>Hence, in Vista something append behind the JLabel and show something wyerd!</strong>
    I can't understant this and if someone can help i appreciate!
    The TreeNodeRender class is :
    public class MetaDataTreeNodeRenderer implements TreeCellRenderer {
        private JLabel tip = new JLabel();
        private JPanel panel = new JPanel();   
        private JComboBox dataMartsRenderer = new JComboBox();
        private DefaultTreeCellRenderer nonEditableNodeRenderer = new DefaultTreeCellRenderer();
        private HashMap<String, String> valueSaver = null;
        public MetaDataTreeNodeRenderer(Component treeContainer, HashMap<String, String> valueSaver, String[] valuesComboBox) {
            this.valueSaver = valueSaver;
            int width = (int)treeContainer.getPreferredSize().getWidth();
            panel.setLayout(new GridBagLayout());
            java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
            panel.setMaximumSize(new Dimension(width, 15));
            panel.setBackground(new Color(255, 255, 255, 0));
            dataMartsRenderer = new JComboBox(valuesComboBox);
            gridBagConstraints.gridx = 0;
            gridBagConstraints.gridy = 0;
            panel.add(tip, gridBagConstraints);
            gridBagConstraints.gridx = 1;
            panel.add(dataMartsRenderer, gridBagConstraints);
            tip.setLabelFor(dataMartsRenderer);       
        public JComboBox getEditableNodeRenderer() {
            return dataMartsRenderer;
        public String getTipText(){
            return this.tip.getText();
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                boolean expanded, boolean leaf, int row, boolean hasFocus) {
            Component returnValue = null;
            DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)value;
            DefaultMutableTreeNode currentNodeFather = (DefaultMutableTreeNode)currentNode.getParent();
            if(currentNodeFather != null && currentNodeFather.isRoot()){//se o meu pai &eacute; a raiz, ent&atilde;o eu sou um datamart
                                                                        //se sou um datamart, ent&atilde;o sou edit&aacute;vel.
                String dataMart = (String)currentNode.getUserObject();
                String dataMartValue = this.valueSaver.get(dataMart);
                tip.setText(dataMart);
                if(dataMartValue != null) {
                    dataMartsRenderer.setSelectedItem(dataMartValue);
                returnValue = panel;
            }else{//sou um n&oacute; n&atilde;o edit&aacute;vel.
                 returnValue = nonEditableNodeRenderer.getTreeCellRendererComponent(tree,
                         value, selected, expanded, leaf, row, hasFocus);
            return returnValue;
    }The TreeNodeEditor class is :
    public class MetaDataTreeNodeEditor extends AbstractCellEditor implements TreeCellEditor {
        MetaDataTreeNodeRenderer renderer = null;
        JTree tree;
        //Where i save all JComboBox values ( name of label, selected item in combobox), for all combbox
        HashMap<String, String> valueSaver = null;
        public MetaDataTreeNodeEditor(JTree tree, Component treeContainer, HashMap<String, String> valueSaver, String[] valuesComboBox) {
            this.tree = tree;
            this.renderer = new MetaDataTreeNodeRenderer(treeContainer, valueSaver, valuesComboBox);
            this.valueSaver = valueSaver;
        public Object getCellEditorValue() {
            JComboBox comboBox = renderer.getEditableNodeRenderer();
            String dataMart = renderer.getTipText();
            this.valueSaver.put(dataMart, (String)comboBox.getSelectedItem() );
            return dataMart;
        @Override
        public boolean isCellEditable(EventObject event) {
            boolean returnValue = false;
            if (event instanceof MouseEvent) {
                MouseEvent mouseEvent = (MouseEvent) event;
                if (mouseEvent.getClickCount() > 1) {
                    TreePath path = tree.getPathForLocation(mouseEvent.getX(), mouseEvent.getY());
                    if (path != null) {
                        Object node = path.getLastPathComponent();
                        if ((node != null) && (node instanceof DefaultMutableTreeNode)) {
                            DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node;
                            if ( treeNode.getParent() != null && ((DefaultMutableTreeNode) treeNode.getParent()).isRoot()) {
                                returnValue = true;
                            } else {
                                returnValue = false;
            return returnValue;
        public Component getTreeCellEditorComponent(final JTree tree, final Object value, boolean selected,
                boolean expanded, boolean leaf, int row) {
            Component editor = renderer.getTreeCellRendererComponent(tree, value, true, expanded, leaf,
                    row, true);
            ActionListener actionListener = new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    if (stopCellEditing()) {
                        fireEditingStopped();
            if (editor instanceof JPanel) {
                Object component = ((JPanel) editor).getComponent(1);
                JComboBox field = (JComboBox) component;
                field.addActionListener(actionListener);
            return editor;
        }

    Hi people!
    i create a Jtree component and create a special node, that is a <strong>JPanel with a JLabel + JCombobox</strong>!
    Only the direct childs of root have this special node.
    A can put this work properly in Windows XP, like the picture:
    [XP Image|http://feupload.fe.up.pt/get/jcgd0rY5p9PoFPG]
    And in Windows Vista the same code appear like this:
    [Vista Image|http://feupload.fe.up.pt/get/Ylajl6hlCUFc0xe]
    <strong>Hence, in Vista something append behind the JLabel and show something wyerd!</strong>
    I can't understant this and if someone can help i appreciate!
    The TreeNodeRender class is :
    public class MetaDataTreeNodeRenderer implements TreeCellRenderer {
        private JLabel tip = new JLabel();
        private JPanel panel = new JPanel();   
        private JComboBox dataMartsRenderer = new JComboBox();
        private DefaultTreeCellRenderer nonEditableNodeRenderer = new DefaultTreeCellRenderer();
        private HashMap<String, String> valueSaver = null;
        public MetaDataTreeNodeRenderer(Component treeContainer, HashMap<String, String> valueSaver, String[] valuesComboBox) {
            this.valueSaver = valueSaver;
            int width = (int)treeContainer.getPreferredSize().getWidth();
            panel.setLayout(new GridBagLayout());
            java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
            panel.setMaximumSize(new Dimension(width, 15));
            panel.setBackground(new Color(255, 255, 255, 0));
            dataMartsRenderer = new JComboBox(valuesComboBox);
            gridBagConstraints.gridx = 0;
            gridBagConstraints.gridy = 0;
            panel.add(tip, gridBagConstraints);
            gridBagConstraints.gridx = 1;
            panel.add(dataMartsRenderer, gridBagConstraints);
            tip.setLabelFor(dataMartsRenderer);       
        public JComboBox getEditableNodeRenderer() {
            return dataMartsRenderer;
        public String getTipText(){
            return this.tip.getText();
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                boolean expanded, boolean leaf, int row, boolean hasFocus) {
            Component returnValue = null;
            DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)value;
            DefaultMutableTreeNode currentNodeFather = (DefaultMutableTreeNode)currentNode.getParent();
            if(currentNodeFather != null && currentNodeFather.isRoot()){//se o meu pai &eacute; a raiz, ent&atilde;o eu sou um datamart
                                                                        //se sou um datamart, ent&atilde;o sou edit&aacute;vel.
                String dataMart = (String)currentNode.getUserObject();
                String dataMartValue = this.valueSaver.get(dataMart);
                tip.setText(dataMart);
                if(dataMartValue != null) {
                    dataMartsRenderer.setSelectedItem(dataMartValue);
                returnValue = panel;
            }else{//sou um n&oacute; n&atilde;o edit&aacute;vel.
                 returnValue = nonEditableNodeRenderer.getTreeCellRendererComponent(tree,
                         value, selected, expanded, leaf, row, hasFocus);
            return returnValue;
    }The TreeNodeEditor class is :
    public class MetaDataTreeNodeEditor extends AbstractCellEditor implements TreeCellEditor {
        MetaDataTreeNodeRenderer renderer = null;
        JTree tree;
        //Where i save all JComboBox values ( name of label, selected item in combobox), for all combbox
        HashMap<String, String> valueSaver = null;
        public MetaDataTreeNodeEditor(JTree tree, Component treeContainer, HashMap<String, String> valueSaver, String[] valuesComboBox) {
            this.tree = tree;
            this.renderer = new MetaDataTreeNodeRenderer(treeContainer, valueSaver, valuesComboBox);
            this.valueSaver = valueSaver;
        public Object getCellEditorValue() {
            JComboBox comboBox = renderer.getEditableNodeRenderer();
            String dataMart = renderer.getTipText();
            this.valueSaver.put(dataMart, (String)comboBox.getSelectedItem() );
            return dataMart;
        @Override
        public boolean isCellEditable(EventObject event) {
            boolean returnValue = false;
            if (event instanceof MouseEvent) {
                MouseEvent mouseEvent = (MouseEvent) event;
                if (mouseEvent.getClickCount() > 1) {
                    TreePath path = tree.getPathForLocation(mouseEvent.getX(), mouseEvent.getY());
                    if (path != null) {
                        Object node = path.getLastPathComponent();
                        if ((node != null) && (node instanceof DefaultMutableTreeNode)) {
                            DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node;
                            if ( treeNode.getParent() != null && ((DefaultMutableTreeNode) treeNode.getParent()).isRoot()) {
                                returnValue = true;
                            } else {
                                returnValue = false;
            return returnValue;
        public Component getTreeCellEditorComponent(final JTree tree, final Object value, boolean selected,
                boolean expanded, boolean leaf, int row) {
            Component editor = renderer.getTreeCellRendererComponent(tree, value, true, expanded, leaf,
                    row, true);
            ActionListener actionListener = new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                    if (stopCellEditing()) {
                        fireEditingStopped();
            if (editor instanceof JPanel) {
                Object component = ((JPanel) editor).getComponent(1);
                JComboBox field = (JComboBox) component;
                field.addActionListener(actionListener);
            return editor;
        }

  • JComboBox Cell Editor in JTable

    I've scouered the forums for an answer to my question, and while
    finding other valuable advice, I have yet to find an answer to my
    question. But first, a little description:
    I have a JTable consisting of 5 columns:
    col1= standard Object cell editor
    col2= JComboBox cell editor
    col3= JComboBox cell editor, values dependent on col2
    col4= JComboBox cell editor, values dependent on col3
    col5= JComboBox cell editor, values dependent on col4
    Data structure looks like this:
    col1= company object, containing vector of values for col2
    col2= lease object, containing vector of values for col3
    col3= well object, containing vector of values for col4
    col4= pump object, containing vector of values for col5
    col5= simply displayed.
    I have a JButton that adds a new row to the table via dialog, then menu
    options to add entries to the comboboxes/vectors. The kicker here is
    that everything is fine up until I've added a pump, and click the cell
    to view the entry. In my cellEditor class, I have a 'getSelected()'
    method that returns 'combobox.getSelectedIndex()'. When 'edittingStopped()'
    is thrown for any cell in this column, I get a null pointer in my
    getSelectedIndex() method of the lease combobox - only in this pump
    column. Even the part column works correctly. Code snips:
    public class MyApplication ... {
      private TableColumn leaseColumn;
      private TableColumn wellColumn;
      private TableColumn pumpColumn;
      private TableColumn partColumn;
      private LeaseDropDown leaseDropDown;
      private WellDropDown wellDropDown;
      private PumpDropDown pumpDropDown;
      private PartDropDown partDropDown;
      private int currentLease = 0;
      private int currentWell = 0;
      private int currentPump = 0;
      public MyApplication() {
        leaseColumn = pumpshopTable.getColumnModel().getColumn(1);
        leaseDropDown = new LeaseDropDown(companies);
        leaseColumn.setCellEditor(leaseDropDown);
        DefaultTableCellRenderer leaseRenderer =
          new DefaultTableCellRenderer();
        leaseRenderer.setToolTipText("Click for leases");
        leaseColumn.setCellRenderer(leaseRenderer);
        //... same for lease, well, pump, part ...
        leaseDropDown.addCellEditorListener(new CellEditorListener() {
          public void editingCanceled(ChangeEvent e) {
          } // end editingCanceled method
          public void editingStopped(ChangeEvent e) {
            updateCells();
          } // end editingStopped method
        }); // end addCellEditorListener inner class
        //.... same inner class for well, pump, part ...
      } // end MyApplication constructor
      public void updateCells() {
        currentLease = leaseDropDown.getSelectedLease();
        //... get current well, pump, part ...
        leaseDropDown = new LeaseDropDown(companies); // companies=Vector,col1
        leaseColumn.setCellEditor(leaseDropDown);
        //... same for lease, well, pump and part columns ...
      } // end updateCells method
    } // end MyApplication class
    public class LeaseDropDown extends AbstractCellEditor
        implements TableCellEditor {
      private Vector companiesVector;
      private JComboBox leaseList;
      public LeaseDropDown(Vector cVector) {
        companiesVector = cVector;     
      } // end LeaseDropDown constructor
      public Component getTableCellEditorComponent(JTable table,
          Object value, boolean isSelected, int rowIndex, int vColIndex) {
        Company thisCompany = (Company) companiesVector.get(rowIndex);
        Vector leasesVector = (Vector) thisCompany.getLeases();
        leaseList = new JComboBox(leasesVector);
        return leaseList;
      } // end getTableCellEditorComponent method
      public Object getCellEditorValue() {
        return leaseList.getSelectedItem();
      } // end getCellEditorValue method
      public int getSelectedLease() {
        JOptionPane.showInputDialog("Selected lease is: " +
          leaseList.getSelectedIndex());
        return leaseList.getSelectedIndex();          
      } // end getSelectedLease method
    } // end LeaseDropDown class... LeaseDropDown can be extrapolated to well, pump, and part,
    handing well the selected lease, handing pump the selected
    lease and well, handing part the selected lease, well and pump.
    I guess my question is how do I get the selected comboboxitem (I'd
    settle for the entire combobox if there's no other way) to fill in the
    next column? Why does the way I have it now work for the first 2 combobox
    columns and not the third?

    I'll try to provide more details.
    I use a JComboBox implementation as a cell in a JTable. The CombBox is editable . This is what I get when I try to type in something.
    java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    at java.awt.Component.getLocationOnScreen_NoTreeLock(Component.java:1507)
    at java.awt.Component.getLocationOnScreen(Component.java:1481)
    at javax.swing.JPopupMenu.show(JPopupMenu.java:921)
    at javax.swing.plaf.basic.BasicComboPopup.show(BasicComboPopup.java:177)
    at javax.swing.plaf.basic.BasicComboBoxUI.setPopupVisible(BasicComboBoxUI.java:927)
    at javax.swing.JComboBox.setPopupVisible(JComboBox.java:790)
    at javax.swing.JComboBox.showPopup(JComboBox.java:775)
    I read some related bugs on the sun site but I am not sure if this is a bug and if it is then has it been fixed or work-around provided.
    any insights ??

  • HTMLLoader problem with comboBox

    hi guys
    I'm trying to loader pdf file using XML to retrieve the URL  and I have CombBox to list all the files ,and I need to load another file every time I change the silder for the CombBox
    the problem is the pdf file load only first time and dosent  change if I select another one from the list, I dont know what the the probelm I tried manything like removeChild and I tried to use container but no change, only first time the file loaded
    this is the code
    cb_list.addEventListener(
    SliderEvent.CHANGE,changehandler);
    function changehandler(e:Event):void {
        var sort1:String=cb_list.value;
        var id:String = myXML.tip.(title == sort1)[email protected]();
         //trace(id)
        var slectedtip = myXML.tip.(title == sort1).fulltip.text();
        tit_label.text=myXML.tip.(@ID == id).title .text();
        date_label.text=myXML.tip.(@ID == id).date.text();
        full_tip.text=myXML.tip.(@ID == id).fulltip.text();
         var flashfileURL = myXML.tip.(@ID == id).picURL.text();
        swfURL.text=flashfileURL;
        var url:String = new String();
        url= myXML.tip.(@ID == id).picURL.text().toXMLString();
        var requestpdf:URLRequest=new URLRequest(url);
         var container:Sprite = new Sprite();
        var pdf = new HTMLLoader();
        pdf.height=stage.stageHeight-150;
        pdf.width=stage.stageWidth-270;
        pdf.y=100;
        pdf.x=260;
        pdf.load(requestpdf);
           pdf.addEventListener(Event.COMPLETE, completeHandler);
        function completeHandler(event:Event):void {
            addChild(pdf);

    [problem with combobox comes infront of popup window|http://forum.java.sun.com/thread.jspa?threadID=5291468]

  • ComboBox inside an ItemRenderer keeps going back to initial selectedIndex

    Hi,
         Thanks for taking a minute to help me solve this problem. I have the following component, what I want to do, is to save the selectedIndex on the data.selectedIndice variable. I have no trouble with that. The variable saves the correct new selected Index number, but the problem is that, for instance, if the initial selectedIndex was 0, and the user selects the third item of the ComboBox, the ComboBox will go back to selecting the 0 index (the new one was 3) even though that the seleccion.selectedIndex shows that 3 is selected (that's why data.selectedIndice saves 3)
    <mx:HorizontalList
            bottom="0"
            backgroundAlpha="0.0"
            id="catalogoOpciones"
            columnCount="3"
            height="80"
            hideEffect="{esconderse}"
            horizontalScrollPolicy="on"
            selectable="false"
            showEffect="{mostrarse}"
            width="100%">
            <mx:itemRenderer>
               <mx:Component>
                   <mx:VBox  height="100%" verticalGap="0" horizontalAlign="center" creationComplete="init()">
                       <mx:Label id="titulo" text="{data.nombre}"  textAlign="center" styleName="nombreOpcionDetallePlato" />
                       <mx:ComboBox id="seleccion" dataProvider="{data.opciones}" labelField="label"                          labelFunction="funcionLabelComboBox"  styleName="comboOpcionDetallePlato" change="changeHandler(event)" />
                        <mx:Script>
                            <![CDATA[
                                import menucomponents.clases.OpcionesEvent;
                                import mx.events.ListEvent;
                                import mx.controls.Alert;                                                       
                                public function init():void {
                                public function changeHandler(event:ListEvent):void {        
                                       Alert.show(seleccion.selectedIndex.toString);               //this shows the correct new index selected                                                             data.selectedIndice = seleccion.selectedIndex;               //at the beginning data.selectedIndice was 0, and when I                                                                                                                          change the selectedIdex, data.selectedIndice saves  1                             }                                                                                             correct value, but the ComboBox shows on the screen that                                                                                                                          the selected item is the first one (index 0) and not the                                                                                                                          second one (index 1) AS IT'S SUPPOSED TO                           
                                public function funcionLabelComboBox(item:Object):String {
                                        return item.label + ", $" + item.precio;
                            ]]>
                        </mx:Script>
                    </mx:VBox>               
                </mx:Component>
           </mx:itemRenderer>
        </mx:HorizontalList>
    Thanks for the help
    Sebastián Toro O

    selectedIndice is public. What's funny is that if I don't use the selectedIndex="{data.selectedIndice}" and I comment the line:
    data.selectedIndice = seleccion.selectedIndex
    Then the CombBox works just fine. It doesn't go back to the initial selectedIndex. I´m going to solve this using Events and an external Array (Array.length = ComboBox.dataProvider.length) to save the selectedIndex, it's a very un-elegant solution but i think it's going to work. Also I might add, that if I send an Event and catch it outside the List, and try to modify the data.selectedIndice, from the particular ComboBox that I changed, the ComboBox still changes automatically it's selectedIndex.
    Thanks for your help.
    If some day you think how to solve this, I would really appreciate if you post it here.
    Sebastián Toro O.

  • QUICK MAX DUKE DOLLARS!!!

    Project.java is a simple drawing program.
    Modify the program to draw not only circles, but rectangles,
    filled circles, filled rectanges and lines. Modify the program
    so the user can change the color of a shape and clear the
    drawing.
    Use proper object orient techniques in making your modifications.
    There is some code that is in the sample program that could
    be improved. Make any modifications that you feel are necessary
    to improve the code. The code simple shows you how to perform
    the drawing operations.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    * This is a simply drawing program which lets the user draw basic shapes
    * (lines, ovals and rectangles). This program currently only lets the
    * user draw ovals, and the only color displayed is black.
    * The drawing program uses rubberbanding so that the user can see the
    * shape as they drag it. When the use clicks down on the mouse it
    * sets the starting, or anchor, point for the drawing. When they release
    * the button the shape is drawn. As the user holds down the button and
    * drags the mouse, the shape is constantly displayed.
    public class Project extends Panel
    Panel controlPanel; // Contains for controls to determine shape and color
    ScrollPane drawPane; // A scrollable drawing pane
    Label shapeLabel; // A label for the shape drop down list
    Label colorLabel; // a label for the color drop down list
    Choice shapeChoice; // Drop down list (combbox) for selecting the shape
    Choice colorChoice; // drop down lsit for selecting the color
    Button clearButton; // For clearing the drawing canvas
    Color currentColor = Color.black; // The current color used to draw shapes
    DrawCanvas drawCanvas; // a Canva on which we draw the shapes
    Vector shapes; // A vector to hold all of the shapes
    protected String []shapeTypes = {"circle", "rectangle", "filled circle",
    "filled rectangle", "line" };
    protected String []colors = {"red", "blue", "green", "yellow", "orange",
    "white", "black", "gray", "dark gray", "light gray",
    "cyan", "magenta", "pink"};
    Point anchorPoint; // The anchor point
    Point endPoint; // The point where the mouse was released
    Point stretchPoint; // The point where the user dragged the mouse to
    Point lastPoint; // The previous drag point
    boolean firstTime = true; // first time drawing this shape?
    * Add GUI components
    public Project()
    // GridBagLayout is the most powerful and difficult to
    // use Layout manager
    // The layout manager determines were components are placed on
    // the screen. There is no need to modify it in any way.
    GridBagLayout gbl = new GridBagLayout();
    GridBagConstraints gc = new GridBagConstraints();
    // Create the control panel
    setLayout(gbl);
    controlPanel = new Panel();
    setConstraints(controlPanel, gbl, gc, 0, 0,
    GridBagConstraints.REMAINDER, 1, 0, 0,
    GridBagConstraints.CENTER,
    GridBagConstraints.NONE,
    0, 0, 0, 0);
    add(controlPanel, gc);
    shapeLabel = new Label("Shape"); // The Label for the shape drop down list
    controlPanel.add(shapeLabel);
    shapeChoice = new Choice(); // The dropdown list
    controlPanel.add(shapeChoice);
    colorLabel = new Label("Color"); // The label or the color drop down list
    controlPanel.add(colorLabel);
    colorChoice = new Choice(); // The drop down list
    controlPanel.add(colorChoice);
    clearButton = new Button("Clear"); // the clear button
    controlPanel.add(clearButton); // Doesn't do anything
    // Event handelers
    // Handle the event when the user selects a new shape
    shapeChoice.addItemListener(new ShapeHandler());
    // Event when user selects new color
    colorChoice.addItemListener(new ColorHandler());
    // Event when user click clear button
    clearButton.addActionListener(new ClearHandler());
    //Create the drawing area
    drawPane = new ScrollPane();
    setConstraints(drawPane, gbl, gc, 0, 1,
    GridBagConstraints.REMAINDER, 1, 1, 1,
    GridBagConstraints.CENTER,
    GridBagConstraints.BOTH,
    5, 0, 5, 0);
    add(drawPane, gc);
    drawPane.setSize(300,300);
    drawCanvas = new DrawCanvas(400,400);
    drawPane.add(drawCanvas);
    initShapes(); // initialize the shape choice control
    initColors(); // initialzie the color choice control
    shapes = new Vector();
    // Convenience method for GridBagLayout
    private void setConstraints(
    Component comp,
    GridBagLayout gbl,
    GridBagConstraints gc,
    int gridx,
    int gridy,
    int gridwidth,
    int gridheight,
    int weightx,
    int weighty,
    int anchor,
    int fill,
    int top,
    int left,
    int bottom,
    int right)
    gc.gridx = gridx;
    gc.gridy = gridy;
    gc.gridwidth = gridwidth;
    gc.gridheight = gridheight;
    gc.weightx = weightx;
    gc.weighty = weighty;
    gc.anchor = anchor;
    gc.fill = fill;
    gc.insets = new Insets(top, left, bottom, right);
    gbl.setConstraints(comp, gc);
    // Initialize the shape control
    private void initShapes()
    for(int i = 0; i < shapeTypes.length; i++){
    shapeChoice.add(shapeTypes);
    // Initialzie the color control
    private void initColors()
    for(int i = 0; i < colors.length; i++){
    colorChoice.add(colors);
    * Handle the shape selection
    * This doesn't currently do anything
    public class ShapeHandler implements ItemListener
    public void itemStateChanged(ItemEvent e)
    // Use get index method to get the index of the chosen shape
    // shapeType = shapeChoice.getSelectedItem();
    * Handle the color seclection
    * This doesn't do anything either
    public class ColorHandler implements ItemListener
    public void itemStateChanged(ItemEvent e)
    String color = colorChoice.getSelectedItem();
    System.out.println("Selected color " + color);
    // Handle the clear button
    // This doesn't do anything
    public class ClearHandler implements ActionListener
    public void actionPerformed(ActionEvent e)
    * A canvas to draw on
    public class DrawCanvas extends Component
    int width; // The Width of the Canvas
    int height; // The Height of the Canvas
    /** Create an area to draw on
    *@param width - the width of the drawing area
    *@param height - the height of the drawing area
    public DrawCanvas(int width, int height)
    // Handle mouse press and release events
    addMouseListener(new MouseHandler());
    // handle mouse drag events
    addMouseMotionListener(new MouseDragHandler());
    this.width = width;
    this.height = height;
    * Draw all of the shapes
    * Not very efficient
    public void paint(Graphics g)
    for (Enumeration e = shapes.elements() ; e.hasMoreElements() ;)
    Circle c = (Circle )e.nextElement();
    System.out.println("drawing Circle " + c.toString());
    c.draw(g);
    * Let everyone know what the preferred size of the drawing
    * canvas is
    public Dimension getPreferredSize()
    return new Dimension(width, height);
    * Used with rubberbanding. The way to erase a shape is
    * to draw it again in XOR mode.
    private void eraseLast(Graphics g)
    int x, y;
    int width, height;
    if (anchorPoint == null || lastPoint == null)
    return;
    // The draw methods assume that the width and height are
    // not negative so we do the following caculations to
    // insure that they are not
    if (anchorPoint.x < lastPoint.x)
    x = anchorPoint.x;
    else
    x = lastPoint.x;
    if (anchorPoint.y < lastPoint.y)
    y = anchorPoint.y;
    else
    y = lastPoint.y;
    width = Math.abs(lastPoint.x - anchorPoint.x);
    height = Math.abs(lastPoint.y - anchorPoint.y);
    // Draw the circle (or oval) at the rectagle bounded by
    // the rectange with the upper left hand corner of x,y
    // and with the specified width and height
    g.drawOval(x, y, width, height);
    // To draw a rectable
    //g.drawRect(x, y, width, height);
    // To draw a Filled Oval
    //g.fillOval(x, y, width, height);
    // To draw a Filled Rect
    //g.fillRect(x, y, width, height);
    // To draw a line
    //g.drawLine(anchorPoint.x, anchorPoint.y, lastPoint.x, lastPoint.y);
    * Do the rubber band drawing
    private void drawRubber(Graphics g)
    int x, y;
    int width, height;
    if (anchorPoint.x < stretchPoint.x)
    x = anchorPoint.x;
    else
    x = stretchPoint.x;
    if (anchorPoint.y < stretchPoint.y)
    y = anchorPoint.y;
    else
    y = stretchPoint.y;
    width = Math.abs(stretchPoint.x - anchorPoint.x);
    height = Math.abs(stretchPoint.y - anchorPoint.y);
    g.drawOval(x, y, width, height);
    * Handle the start and end of rubberbanding. At the end
    * draw the final shape
    public class MouseHandler extends MouseAdapter
    // Get the starting point
    public void mousePressed(MouseEvent e)
    anchorPoint = e.getPoint(); // Point where mouse was clickec
    firstTime = true; // The first point
    // Get the end point
    public void mouseReleased(MouseEvent e)
    endPoint = e.getPoint(); // Point where mouse was released
    Graphics g = getGraphics(); // Get the object to draw on
    g.setXORMode(getBackground()); // Set XOR mode
    eraseLast(g); // Erase the previous shape
    // Add the shape to our vector
    //Obviously you will need to do something different here
    shapes.addElement( new Circle(anchorPoint, endPoint, currentColor));
    repaint(); // Repaint the entire drawing
    g.dispose(); // Need to dispose of Graphics objects
    * Handle the rubber banding
    public class MouseDragHandler extends MouseMotionAdapter
    // Every time the mouse is moved while the mouse button is pressed
    public void mouseDragged(MouseEvent e)
    Graphics g = getGraphics();
    g.setXORMode(getBackground());
    stretchPoint = e.getPoint(); // Get the point we just dragged to
    if (firstTime == true)
    firstTime = false; // nothing to erase the first time
    else
    eraseLast(g); // Erase the last drawing
    drawRubber(g); // Draw the new one
    g.dispose(); // Anytime we do a getGraphics we must dispose of it
    lastPoint = stretchPoint; // Set the lastPoint to lastest last point
    * In real program this should extend Shape or implement a Shape
    * interface and it should be in it's own file
    * Note that even though this is called Circle, it is really an oval
    public class Circle
    int x, y; // X and Y cooridinates of bounding rectangle (upper left)
    int width, height; // width and height of bounding rectangle
    Point p2; // opposite corner of bounding retangle
    Color color; // color of circle
    public Circle(Point p1, Point p2, Color color)
    // The width and height cannot be negative.
    // x and y must always be the upper left corner
    if ( p1.x < p2.x)
    x = p1.x;
    else
    x = p2.x;
    if (p1.y < p2.y)
    y = p1.y;
    else
    y = p2.y;
    width = Math.abs( p2.x - p1.x);
    height = Math.abs(p2.y - p1.y);
    this.color = color;
    * This method is called automatically by repaint and whenever the
    * window needs to be redrawn
    public void draw(Graphics g)
    Color c = g.getColor(); // Save the current color
    g.setColor(color); // Set the color to draw the circle
    g.drawOval(x, y, width, height); // draw the circle
    g.setColor(c); // set the color back to what is was before
    * a toString method is a convienent way of
    * displaying the attributes of a class
    public String toString()
    return "Circle " + color + width + height;
    * Main method creates a Frame and adds in our drawing control
    public static void main(String []args)
    // Create the main window
    Frame frame = new Frame();
    // add a listener to close the window properly
    frame.addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
    System.exit(0); // simply exit
    // Create our control
    Project panel = new Project();
    // add it to our window
    frame.add(panel, BorderLayout.CENTER);
    // size our window to 640 by 480 pixels
    frame.setSize(640, 480);
    // display our window
    frame.setVisible(true);
    }

    Sure, I'll do it, no problem... Anything to help a fellow hard working computer science student... I'm just curious what college you attend. Could you tell me? I promise I'll get you the code then.

  • Display arabic language problem

    Hi ,
    i use netbeans 6.9.1 to create a java application .
    i have a textbox ,combobox and button and data base table. while i run my program from netbeans i can insert into text
    box arabic word then click add to store word into data base table and combobox.
    while i run my program from cmd or by double click jar i can write arabic word into text box , but when i click button . it adds ????????? into combbox
    running from netbeans
    write : محمد
    display : محمد
    running as standalone application
    write :محمد
    display :؟؟؟؟؟؟؟؟؟؟
    Thanks

    user7314099 wrote:
    ..Cause i have 2 different situations, running from netbeans and running as normal program from cmd.Based on Kayaman's answer, I would look to dump the System.property("file.encoding") and compare them between the IDE & 'cmd'.
    If that does not solve the problem or give you some direction, you might be better off posting on the NetBeans Forums. Many people here do not use NetBeans, and a lot of those that do choose not to discuss IDEs on these forums.

  • Changing variable with combobox selection - simple problem!

    Hi there,
    I have a search field when you click on search.
    I want to make it so i can change which field in a datagrid
    you search for depending on the choice in the Combbox. I'm not sure
    how to set the object name correctly depending on the combobox
    selection.
    I tried it like this, to no avail
    private var acOrder:ArrayCollection
    private var currentOrder:Object;
    ///////////////this is incorrect. What should i use instead
    of Object?//////
    private var whichArray:Object
    private function makeid():void
    whichArray = "orderid"
    private function makeemail():void
    whichArray = "email"
    private function filterByOrderid(item:Object):Boolean
    if (item.(whichArray) == filterTxt.text)
    ////I want this result to either be if (item.orderid ==
    filterTxt.text)
    ///or if (item.orderid == filterTxt.email)
    return true;
    else
    return false;
    private function doFilter():void
    if (filterTxt.text.length == 0)
    acOrder.filterFunction = null
    else
    acOrder.filterFunction = filterByOrderid;
    acOrder.refresh()
    i think answer is very simple. i just need to pass the name
    of the item inside the object correctly
    thanks very much for any help

    Hi,
    Try declaring whichArray as String and try this
    item[whichArray] instead of item.(whichArray).
    Hope this helps.

  • Selecting data from a drop down menu

    Hey all
    I am trying to create a golf leaderboard. It reads from a text file, then generates the playing pairs. These pairs are then output in a drop down menu. I want now to be able to fill in scores for the pair that is selected, and for it to be added to the scoreboard. Is there a way of doing this??
    If you need anymore info or code, just let me know.
    Thanks to everyone in advance.
    WhippingBoy

    i'm doing this in swing. Currently, i am displaying the leaderboard in a textarea. Theni have got a CombBox to display te pairs. Thid is the box i want to retrieve the info from. I have two text areas to enter the scores in, one for each palyer in the pair. I want to be able to recognise which players score is being modified by getting the info from the combo box
    thanks for looking at my problem.
    whippingboy

  • JComboBox as cell in JTable

    I use a JComboBox implementation as a cell in a JTable. The CombBox is editable . This is what I get when I try to type in something.
    java.awt.IllegalComponentStateException: component must be showing on the screen to determine its location
    at java.awt.Component.getLocationOnScreen_NoTreeLock(Component.java:1507)
    at java.awt.Component.getLocationOnScreen(Component.java:1481)
    at javax.swing.JPopupMenu.show(JPopupMenu.java:921)
    at javax.swing.plaf.basic.BasicComboPopup.show(BasicComboPopup.java:177)
    at javax.swing.plaf.basic.BasicComboBoxUI.setPopupVisible(BasicComboBoxUI.java:927)
    at javax.swing.JComboBox.setPopupVisible(JComboBox.java:790)
    at javax.swing.JComboBox.showPopup(JComboBox.java:775)
    I read some related bugs on the sun site but I am not sure if this is a bug and if it is then has it been fixed or work-around provided.
    any insights ??

    Hi,
    for an example implementation look here:
    http://archive.devx.com/sourcebank/details.asp?resourc
    eNum=1034693
    L.P.I had gone through this page much earlier than this post . I already have my own CellEditor but still the problem persists .
    Anyways I have managed to tweak the stopCellEditing() method and found out a workaround. I think it has to do more with the way I have implemented Auto-Complete feature rather than anything else so it wouldnt help if I post my solution.

  • How can I change the combobox border?

    I dragged a combbox component from ctrl+F7 to my stage. It
    has rounded border and I wanna change this to rectangle borders.
    Also, I wanna reduce the height of each item. Could you please
    help? I'm using Flash CS3

    Jeff,
    Printing has definitely gotten worse with Numbers 3.0.  Apple published a list of items they are addressing here:
    http://support.apple.com/kb/HT6049
    You can continue to use the previous version which is located in the folder "/Applications/iWork '09"
    The only way I know to "fix" this problem is to print to PDF directly to Preview, then crop (using the rectangular selection tool and the menu item "Tools > Crop") and print again.

  • JcomboBox list size is wrong if using PopupMenuListener

    Just wondering if someone else has already implmented the workaround for this bug and would be able to tell me if it was very difficult to get going.
    Basically, if you use PopupMenuListeners to populate a combo-box list dynamically when the user selects the combo, the size of the list which gets presented to the user is based on the number of entries the combo previously had, not teh size of the new list.
    http://developer.java.sun.com/developer/bugParade/bugs/4743225.html
    We were hoping that this would get fixed in v1.5, but customers are complaining so much, its getting to the point where we will have to code a work-around. Just wondering how nasty it is to do.

    Basically, if you use PopupMenuListeners to populate a combo-box list dynamically ...I guess I don't fully understand what you are attempting to do, so I guess the next question is why are you using a PopupMenuListener to dynamically change the contents of the comboBox? Why does clicking on the dropdown menu cause the contents do dynamically change? Usually the contents are change as a result of some other action by the user. Maybe some sample code will clarify what you are attempting do do and an alternative approach can be suggested.
    For example, this thread shows how to dynamically change the contents of a second combBox when a selection is made in the primary comboBox:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=428181

  • Is it possible to display more elements for non-LOV list item w/o Javabean?

    Since webform combobox, poplist or tlist does not have the partial search functionality like its countpart in MS ACCESS, thus, our user asks for displaying span screen hight of list element for them to avoid the 'endless' scrolling. If LOV's partial search function can port to combbox list, that will reolve the issue.
    But before that, is it possible ? Since I see no property to set that. Thanks.

    Hi,
    no, not as far as I can see it.
    Frank

Maybe you are looking for

  • How many devices can you add to icloud?

    How many devices can you add to your icloud account? 

  • Can't open a file, picture, on Ele-11?

    Can't open a photo file on Elelments 11 / Windows 7?  I've tried, >open,  tried, >file, >open, tried the open pulldown and drag a file.  I changed file format from, all formats to jpeg.?  I just can't seem to open up a photo file on to my workspace.

  • Send a message to multiple receivers from the same service

    Hi all, I registered on SAP community several months ago, I found many good hints and solutions to some of the problems encountered in XI and for which I thank you, but this is the first time I address a question to a common issue, written already ab

  • I uninstalled Muse and cannot reinstall

    I have problems with installing Muse 2014 CC, and I thought to uninstall the old version of Muse. But in the Creative Cloud app it still says Muse Up to date. How do I re-install Muse??

  • Can connect with AE but fail on connecting with internet

    For some reasons I needed to re-conflict my AE and changed the wireless name. 2 of my Mac computer and my iTouch could connect with no problem. But my PC (XP2) could connect with this AE but failed on internet with error message "limited or not conne