Events & Booleans

I have a problem with booleans. I am using an event structure within a while loop. This while loop has image acquistion going on. The event structure has two events which are triggered by value changed event using boolean controls. The first of the events gets executed fine when I use the boolean. but after the first is done the second event does not recognize the change in the value of the boolean. If I stop the program and directly press the button for the second event then the event runs. I would like to know what is causing this problem

Check the following image, notice the "new value" at the left border of the event case is wired to the while loop. It works on my machine. When the "Tracking" control wired to the while loop, I exprienced the same problem you had, but with the new method, it wored flawlessly. I even changed the boolean constant to a control just to test the "learning", "tracking", "stop tracking" events many times.
Joe
Attachments:
Snap1.gif ‏11 KB

Similar Messages

  • Event driven programmin​g examples

    I want to create one static event (Boolean value change type), which when occur should register one dynamic event(Boolean value change type) in it. Thus until static boolean value doesn't change, dynamic event cannot be registered.Can anyone give a example code for this?

    Search in the Example Finder for the example Dynamically register for Events.
    Then all you have to do is put the registration of the dynamic event inside the event case for the static event.

  • Dispatched Event not being caught

    I have the following custom event:
    package
    import flash.events.Event;
    public class TestCustomEvent extends Event
    public static const EVENT_NAME:String = "TestCustom";
    public var _message:String;
    public function TestCustomEvent(message:String)
    super(EVENT_NAME,true,false);
    this._message = message;
    public override function clone():Event
    return new TestCustomEvent(_message);
    public override function toString():String
    return formatToString("TestCustomEvent", "type", "bubbles",
    "cancelable", "eventPhase", "_message");
    which I am trying to dispatch from the following class:
    package
    import flash.events.EventDispatcher;
    import flash.events.IEventDispatcher;
    import flash.events.Event;
    public class TestDispatch implements IEventDispatcher
    private var dispatcher:EventDispatcher;
    public function TestDispatch()
    dispatcher = new EventDispatcher(this);
    public function RaiseEvent():void
    var ev:TestCustomEvent = new TestCustomEvent("catch this");
    this.dispatchEvent(ev);
    public function addEventListener(type:String,
    listener:Function, useCapture:Boolean = false, priority:int = 0,
    useWeakReference:Boolean = false):void{
    dispatcher.addEventListener(type, listener, useCapture,
    priority);
    public function dispatchEvent(evt:Event):Boolean{
    return dispatcher.dispatchEvent(evt);
    public function hasEventListener(type:String):Boolean{
    return dispatcher.hasEventListener(type);
    public function removeEventListener(type:String,
    listener:Function, useCapture:Boolean = false):void{
    dispatcher.removeEventListener(type, listener, useCapture);
    public function willTrigger(type:String):Boolean {
    return dispatcher.willTrigger(type);
    but in my application the event doesn't get caught:
    <?xml version="1.0"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    creationComplete="init()" initialize="addListeners()">
    <mx:Script>
    <![CDATA[
    private function addListeners():void
    this.addEventListener( TestCustomEvent.EVENT_NAME,
    onEventCaught );
    private function init():void
    var t:TestDispatch = new TestDispatch();
    t.RaiseEvent();
    public function onEventCaught(event:TestCustomEvent):void
    trace("caught");
    ]]>
    </mx:Script>
    </mx:Application>
    Not sure why event is not being caught.
    Thanks,
    EE

    I updated my code a little:
    //Using a sprite so it should be part of the diplay list now.
    package
    import flash.display.Sprite;
    public class TestClass2 extends Sprite
    public function TestClass2()
    super();
    public function RaiseEvent():void
    var ev:TestCustomEvent = new TestCustomEvent("catch this");
    this.dispatchEvent(ev);
    <?xml version="1.0"?>
    <mx:Application xmlns:mx="
    http://www.adobe.com/2006/mxml"
    creationComplete="init()" initialize="addListeners()"
    xmlns:local="*">
    <mx:Script>
    <![CDATA[
    private function addListeners():void
    this.addEventListener( TestCustomEvent.EVENT_NAME,
    onEventCaught );
    private function init():void
    tc2.RaiseEvent();
    public function onEventCaught(event:TestCustomEvent):void
    trace("caught");
    ]]>
    </mx:Script>
    <local:TestClass2 id="tc2" width="100" height="50" />
    </mx:Application>
    But event still not being caught.

  • FPGA event Structure

    Hi,
    Iam working on DC motor...... iam using NI 9505....... iam using example code of labview {(Position Control (closed loop)- under compact RIO}......
    every thing is fine............ now i want to add control LEDs which has to control the speed of the motor......every led represents some values......there are 66 leds.... i thought i can use event structure so that when ever an event(boolean led ) occurs that event will suplly the value of posotion setpoint to motor.........
    i have added event outsde, inside, with, without while loop...evry thing i tried.......but iam not getting......i wan to know where iam doing wrong..... to understand better  i have attached two images front panel and block diagram......
    please help me out of this problem...........
    Attachments:
    front panel.jpg ‏325 KB
    block diagram1.jpg ‏269 KB
    block diagram 2.jpg ‏233 KB

    HI,
    Here are the Complete Detials.........
    1> position setpoint is not an indicator........ its a control
    2>  for one rotation of motor is 360 degree---- now i want to rotate motor for 360 degree in 66 times...... and i want to indicate the value....... so i divided 360 by 66 which is 5.45......
     3>  Now i calculated the motor ratio........ digitaly to rotate motor, it requires 1230.5 which is position set point..........
              to rotate motor at 0 degree we need position set point at 0
              to rotate motor at 360 degree we need position set point at 1230.5
    4> i implemented this  logic outside using 4 LEDs and its values is given( please go through 360 degree implement.vi)
    5> i want to implement the same logic in this positon control (closed loop).vi
            but its not taking the event strucutre.......
    6> i have attached the vi....... there will broken wires since there is no fpga target..........
    7> i have attached compelte source code for position control project........ here in this project i want to add 66 leds which will control the motor for one rotation with respect               
               above steps
     Please let me know if u need any more info on this.......please go through above snap shots for inserting the LED structure....
    Thank you
    Attachments:
    360 degree implement.vi ‏26 KB
    Position Control.vi ‏205 KB
    Position Control.zip ‏517 KB

  • Event Structure - Lock Event: Does it Queue ?

    I had couple of question related to this post in other posts but I thought I'd use a new one since it might be more relevant (others were related to local variables, and VI file sizes)
    I have this event structure running about 10 different tasks. For some I would like to lock the panel when it runs. I used "Lock panel ..." but during the run, if you click on any boolean and menu ... for some reason it queues the task and performs it after the event is complete ... is there any way I can lock the event and not have any event queued ? Thnks !
    Kudos always welcome for helpful posts

    If you were to change the value of the Block Panel Event boolean using a local variable it wouldn't fire an event so I'm not sure that would be the way to go.  I had intended that just to be an example control.
    I have further modified the example to show how a custom user event can be programatically fired to signal that the front panel should be "unlocked" and that new events should be added to the event queue.  In the new example you will see that while the LED is flashing no events are queued.  Once the LED is done flashing it communicates to the event structure via a user event.
    It may also be possible to change the value of the "locked?" boolean without requiring an event to do so.  I didn't explore this option but it may be a valid approach.
    Also please remember that any example I have posted here is not meant to be incorporated into an application - I am merely attempting to demonstrate ideas and concepts.  It will be more beneficial for you to examine and understand how I programmed a certain behavior and then use those concepts to create your own application than to try to make my code fit into your application.
    Regards,
    ~ Simon
    Attachments:
    lock event 2-1.vi ‏75 KB

  • How to tackle the dataflow problem when Value Change event always triggers after another GUI event

    We know that Value change event always triggers after another GUI event. Eg, the user modifies string control, the user clicks on a boolean control. Then event boolean clicked is triggered before event string control value change.
    Now suppose somehow the GUI event that must happen to subsequently trigger the Value change event can potentially affect the data that Value change event is supposed to work on. How can we tackle this problem ?
    For example, in a mockup application that the grand purpose is to have user entered values in a textbox logged to a file (no missing information is accepted, and there is a boolean to determine how the information is logged).
    There are 2 controls, boolean A when clicked (mouse down) will load random number in text box B. Text box B is designed with event structure VALUE change which saves whatever values user enters into text box B to a log file.
    There are 3 problems when instead of clicking anywhere on the front panel after modifying text box B, the user ends up clicking on boolean control A.
    1. Event mouse down on Boolean control A will execute first, modifying text box B content before the user entered values in B get saved.
    2. The value of boolean A can potentially affect how textbox B is loggged.
    3. The value of boolean A affects how the file is logged and this is indeterminate. Somehow when running this VI with no Highlighting, the textbox B Value change event executes -before- boolean A value is updated (F to T). When running this VI with Highlighting, the boolean A value is updated (F to T) (because we click on it) -before- textbox B value change event occurs. Why is it like this ?
    Now the situation I made up seems non-sense, but I believe it resembles one way or another a problem that you might run into. How would you solve this problem elegantly ?
     

    You can set the string control to "update while typing".
    Are you sure appending the log to itself is reasonable? Wouldn't it grow without bounds if the users keeps entering strings or pressing the ingore button?
    Why isn't the "constant" a diagram constant instead of a control. Is the user allowed to change it?
    To reset just write empty strings or a false to local variables of the controls (renit to defaults" seems a bit heavy handed).
    All you probably need is a single event case for "ignore:value change" and "String" value changed", no need for the local variable..
    Also add a stop button and an event for it.
    You don't need the timeout event.
     

  • How to change color of selected label from list of labels?

    My Problem is that I have a list of labels. RowHeaderRenderer is a row header renderer for Jtable which is rendering list items and (labels).getListTableHeader() is a method to get the list. When we click on the label this code is executed:
    getListTableHeader().addMouseListener(new MouseAdapter()
    public void mouseReleased(MouseEvent e)
    if (e.getClickCount() >= 1)
    int index = getListTableHeader().locationToIndex(e.getPoint());
    try
    if (((ae_AlertEventInfo)theAlerts.values().toArray()[index]).ackRequiredFlag)
    AcknowledgeEvent ackEvent = new AcknowledgeEvent(
    this, (ae_AlertEventInfo)theAlerts.values().toArray()[index]);
    fireAcknowledgeEvent(ackEvent);
    ((HeaderListModel)listModel).setElementAt(ACK, index);
    catch(Exception ex) {;}
    Upon mouse click color of the label should be changed. For some period of time ie. Upto completion of fireAcknowledgeEvent(ackEvent);
    This statement is calling this method:
    public void handleAcknowledgeEvent(final AcknowledgeEvent event)
    boolean ackOk = false;
    int seqId = ((ae_AlertEventInfo)event.getAlertInfo()).sequenceId;
    if (((ae_AlertEventInfo)event.getAlertInfo()).ackRequiredFlag)
    try
    // perform call to inform server about acknowledgement.
    ackOk = serviceAdapter.acknowledge(seqId,
    theLogicalPosition, theUserName);
    catch(AdapterException aex)
    Log.error(getClass(), "handleAcknowledgeEvent()",
    "Error while calling serviceAdapter.acknowledge()", aex);
    ExceptionHandler.handleException(aex);
    else
    // Acknowledge not required...
    ackOk = true;
    //theQueue.buttonAcknowledge.setEnabled(false);
    final AlertEventQueue myQueue = theQueue;
    if (ackOk)
    Object popupObj = null;
    synchronized (mutex)
    if( hasBeenDismissed ) { return; }
    // mark alert event as acknowledged (simply reset ack req flag)
    ae_AlertEventInfo info;
    Iterator i = theAlerts.values().iterator();
    while (i.hasNext())
    info = (ae_AlertEventInfo) i.next();
    if (info.sequenceId == seqId)
    // even if ack wasn't required, doesn't hurt to set it
    // to false again. But it is important to prevent the
    // audible from playing again.
    info.ackRequiredFlag = false;
    info.alreadyPlayed = true;
    // internally uses the vector index so
    // process the queue acknowledge update within
    // the synchronize block.
    final ae_AlertEventInfo myAlertEventInfo = event.getAlertInfo();
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    myQueue.acknowledge(myAlertEventInfo);
    myQueue.updateAcknowledgeButtonState();
    // here we should stop playing sound
    // if it is playing for this alert.
    int seqId1;
    if (theTonePlayer != null)
    seqId1 = theTonePlayer.getSequenceId();
    if (seqId1 == seqId)
    if (! theTonePlayer.isStopped())
    theTonePlayer.stopPlaying();
    theTonePlayer = null;
    // get reference to popup to be dismissed...
    // The dismiss must take place outside of
    // the mutex... otherwise threads potentially
    // hang (user hits "ok" and is waiting for the
    // mutex which is currently held by processing
    // for a "move to summary" transition message.
    // if the "dismiss" call in the transition
    // message were done within the mutex, it might
    // hang on the dispose method because the popup
    // is waiting for the mutex...
    // So call popup.dismiss() outside the mutex
    // in all cases.
    if(event.getSource() instanceof AlertEventPopup)
    popupObj = (AlertEventPopup)event.getSource();
    else
    popupObj = thePopups.get(event.getAlertInfo());
    thePopups.remove(event.getAlertInfo());
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    // search vector elements to determine icon color in main frame
    String color = getColor();
    fireUpdateEvent(new UpdateEvent(this, blinking, color));
    // Call dismiss outside of the mutex.
    if (popupObj !=null)
    if(popupObj instanceof AlertEventPopup)
    ((AlertEventPopup)popupObj).setModal(false);
    ((AlertEventPopup)popupObj).setVisible(false); // xyzzy
    ((AlertEventPopup)popupObj).dismiss();
    else
    // update feedback... ack failed
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    myQueue.setInformationMessage("Acknowledge failed to reach server... try again");
    return;
    Code for RowHeaderRenderer is:
    class RowHeaderRenderer extends JLabel implements ListCellRenderer
    JTable theTable = null;
    ImageIcon image = null;
    RowHeaderRenderer(JTable table)
    image = new ImageIcon(AlertEventQueue.class.getResource("images" + "/" + "alert.gif"));
    theTable = table;
    JTableHeader header = table.getTableHeader();
    setOpaque(true);
    setHorizontalAlignment(LEFT);
    setForeground(header.getForeground());
    setBackground(header.getBackground());
    setFont(header.getFont());
    public Component getListCellRendererComponent( JList list, Object value,
    int index, boolean isSelected, boolean cellHasFocus)
    int level = 0;
    try
    level = Integer.parseInt(value.toString());
    catch(Exception e)
    level = 0;
    if (((ae_AlertEventInfo)theAlerts.values().toArray()[index]).ackRequiredFlag)
    setBorder(UIManager.getBorder("TableHeader.cellBorder"));
    this.setHorizontalAlignment(JLabel.CENTER);
    this.setVerticalAlignment(JLabel.CENTER);
    setIcon(image);
    else
    setBorder(BorderFactory.createLineBorder(Color.gray));
    setText("");
    setIcon(null);
    return this;
    I tried but when i am clicking a particular label, the color of all labels in the List is being changed. So can you please assist me in changing color of only the label that is selected and the color must disappear after completion of Upto completion of fireAcknowledgeEvent(ackEvent);

    im a bit confused with the post so hopefully this will help you, if not then let me know.
    I think the problem is that in your renderer your saying
    setBackground(header.getBackground());which is setting the backgound of the renderer rather than the selected item, please see an example below, I created a very simple program where it adds JLabels to a list and the renderer changes the colour of the selected item, please note the isSelected boolean.
    Object "value" is the currentObject its rendering, obviously you may need to test if its a JLabel before casting it but for this example I kept it simple.
    populating the list
    public void populateList(){
            DefaultListModel model = new DefaultListModel();
            for (int i=0;i<10;i++){
                JLabel newLabel = new JLabel(String.valueOf(i));
                newLabel.setOpaque(true);
                model.addElement(newLabel);           
            this.jListExample.setModel(model);
            this.jListExample.setCellRenderer(new RowHeaderRenderer());
        }the renderer
    class RowHeaderRenderer extends JLabel implements ListCellRenderer
        JTable theTable = null;
        public Component getListCellRendererComponent(JList list, Object value,
                                                      int index, boolean isSelected, boolean cellHasFocus){
            JLabel aLabel = (JLabel)value;
            if (isSelected){
                aLabel.setBackground(Color.RED);
            }else{
                aLabel.setBackground(Color.GRAY);
            return aLabel;       
    }

  • Relationship between a Spark DropDownList's dataProvider and selectedItem

    I'm working on an existing project and have come across a somewhat complicated issue regarding a Spark DropDownList's (actually, a custom component inheriting from it) displayed item not changing when its dataProvider is updated.
    Here's the code for the custom TitleWindow component containing the custom DropDownList:
    <?xml version="1.0" encoding="utf-8"?>
    <components:RFTitleWindow xmlns:fx="http://ns.adobe.com/mxml/2009"
                              xmlns:s="library://ns.adobe.com/flex/spark"
                              xmlns:mx="library://ns.adobe.com/flex/mx"
                              xmlns:components="components.*"
                              xmlns:rfform="rfform.*"
                              width="550" height="450"
                              title="{currentState} Site Equipment"
                              cancelButton="{btnCancel}"
                              defaultButton="{btnSave}"
                              initialFocus="{rftName}"
                              creationComplete="init()" close="cancelEdit()">
      <fx:Script>
        <![CDATA[
          import events.SiteEquipmentEvent;
          import events.SiteEquipmentTypeEvent;
          import mx.collections.ArrayList;
          import mx.controls.Menu;
          import mx.core.FlexGlobals;
          import mx.core.UIComponent;
          import mx.events.MenuEvent;
          import mx.managers.PopUpManager;
          import mx.validators.ValidationResult;
          import mx.validators.Validator;
          import spark.events.IndexChangeEvent;
          private const TYPES:Array = ["A", "B", "C", "D"];
          [Bindable] [Embed(source="../assets/images/circle_red_x.gif")] private var icoRedX:Class;
          [Bindable] private var siteEquipment:SiteEquipment;
          private var validators:Array;
          private var typePopUp:Menu;
          public static function open(item:SiteEquipment):SiteEquipmentEdit
            var s:SiteEquipmentEdit = new SiteEquipmentEdit();
            s.siteEquipment = item;
            PopUpManager.addPopUp(s, DisplayObject(FlexGlobals.topLevelApplication), true);
            PopUpManager.centerPopUp(s);
            return s;
          private function init():void
            initTypePopUp();
            if (siteEquipment.id == SiteEquipment.NEW_ID)
              currentState = "New";
            else
              currentState = "Edit";
              validateAll();
              if (!rftName.enabled)
                rfcmbType.setFocus();
            siteEquipment.addEventListener(SiteEquipmentEvent.SITE_EQUIPMENT_SAVE, saveComplete);
          override public function dispose(event:Event = null):void
            super.dispose();
            siteEquipment.removeEventListener(SiteEquipmentEvent.SITE_EQUIPMENT_SAVE, saveComplete);
            typePopUp.removeEventListener("itemClick", typePopUp_click);
            siteEquipment.dispose();
            icoRedX = null;
            siteEquipment = null;
            validators = null;
            typePopUp = null;
            removeChildren();
          private function cancelEdit():void
            siteEquipment.cancelEdit();
          private function saveForm():void
            var newValue:SiteEquipment = new SiteEquipment();
            newValue.id = siteEquipment.id;
            newValue.locid = siteEquipment.locid;
            newValue.name = rftName.trimmedText;
            siteEquipment.save(newValue);
          private function saveComplete(event:Event):void
            dispose();
          private function typePopUp_click(event:MenuEvent):void
            switch(event.item)
              case "Edit Selected Type":
                SiteEquipmentType(rfcmbType.selectedItem).showEditForm();
                break;
              case "Create A New Type":
                new SiteEquipmentType().showEditForm(type_created, null, type_removeListeners);
                break;
          private function type_created(event:SiteEquipmentTypeEvent = null):void
            type_removeListeners(event);
            rfcmbType.selectedItem = event.siteEquipmentType;
          private function type_removeListeners(event:Event):void
            var s:SiteEquipmentType = SiteEquipmentType(event.target);
            s.removeEventListener(SiteEquipmentTypeEvent.SITE_EQUIPMENT_TYPE_CREATE, type_created);
            s.removeEventListener(SiteEquipmentType.SITE_EQUIPMENT_TYPE_CANCEL, type_removeListeners);
          private function initTypePopUp():void
            typePopUp = Menu.createMenu(puType, ['Edit Selected Type', 'Create A New Type']);
            typePopUp.addEventListener("itemClick", typePopUp_click);
          private function popupTypeOptions():void
            var p:Point = puType.localToGlobal(new Point(0, puType.height + 5));
            typePopUp.show(p.x, p.y);
          private function validateAll():void
            var isValid:Boolean;
            for each (var validator:Validator in validators)
              isValid = true;
              for each (var result:ValidationResult in validator.validate().results)
                if (result.isError)
                  isValid = false;
                  break;
              UIComponent(validator.source).styleName = "valid_" + isValid.toString();
          private function rfcmbType_changeHandler(event:IndexChangeEvent):void
            if (TYPES.indexOf(SiteEquipmentType(RFDropDownList(event.target).selectedItem).name) > -1)
              rftName.text = "Blah";
              rftName.enabled = false;
            else
              rftName.enabled = true;
        ]]>
      </fx:Script>
      <fx:Declarations>
        <!-- Place non-visual elements (e.g., services, value objects) here -->
        <s:DateTimeFormatter id="mdy"
                             dateTimePattern="MM/dd/yyyy"/>
      </fx:Declarations>
      <components:states>
        <s:State name="Edit"/>
        <s:State name="New"/>
      </components:states>
      <rfform:RFForm width="100%" height="100%"
                     saveButton="{btnSave}"
                     validators="{new ArrayList([valQuantity, valHeight])}">
        <rfform:RFFormItem label="Type"
                           width="100%">
          <s:HGroup width="100%">
            <rfform:RFDropDownList id="rfcmbType"
                                   width="100%"
                                   originalValue="{siteEquipment.model.eqType}"
                                   dataProvider="{SiteEquipmentType.all}"
                                   change="rfcmbType_changeHandler(event)"/>
            <rfform:RFButton id="puType"
                             icon="@Embed(source='/Shared/src/assets/images/settings.png')"
                             width="30"
                             click="popupTypeOptions()"/>
          </s:HGroup>
        </rfform:RFFormItem>
      </rfform:RFForm>
    </components:RFTitleWindow>
    I've omitted a little bit of code, so please ask if you need anything that I didn't include.
    In regards to the RFDropDownList, originalValue is saved so that when a new selection is made, the new selection can be compared to the original value.  Setting originalValue sets the RFDropDownList's selectedItem to originalValue.
    When this window is first opened, a new instance of SiteEquipment is created.  Unless the equipment is new, the SiteEquipment instance sets the SiteEquipmentType to whatever has already been saved, using this line:
    eqType = SiteEquipmentType.selectFromObject(item.SITE_EQUIPMENT_TYPE);
    And here's the code from the SiteEquipmentType class:
    package components
      import common.UpdateStatus;
      import events.SiteEquipmentTypeEvent;
      import scripts.MyUtility;
      import flash.events.Event;
      import flash.events.EventDispatcher;
      import flash.utils.setTimeout;
      import mx.collections.ArrayCollection;
      import mx.collections.Sort;
      import mx.collections.SortField;
      import mx.controls.Alert;
      import mx.rpc.events.ResultEvent;
      import mx.utils.ObjectProxy;
      [Event(name="cacheChanged", type="flash.events.Event")]
      [Event(name="SITE_EQUIPMENT_TYPE_CREATE", type="events.SiteEquipmentTypeEvent")]
      [Event(name="SITE_EQUIPMENT_TYPE_EDIT", type="events.SiteEquipmentTypeEvent")]
      [Event(name="SITE_EQUIPMENT_TYPE_CANCEL", type="flash.events.Event")]
      public class SiteEquipmentType extends ObjectProxy
        public static const NEW_ID:int = -1;
        public static const SITE_EQUIPMENT_TYPE_CANCEL:String = "siteEquipmentTypeCancel";
        [Bindable]
        public var id:int = NEW_ID;
        [DefaultProperty]
        [Bindable]
        public var name:String = "";
        private static var dict:Object = new Object();
        private static var getAllServiceCalled:Boolean = false;
        private static var eventDispatcher:EventDispatcher = new EventDispatcher();
        private var updateStatus:UpdateStatus = UpdateStatus.COMPLETE;
        public function SiteEquipmentType(item:Object = null, keepInCache:Boolean = true)
          if (item == null)
            return;
          else if (item is int)
            id = int(item);
            refreshFromDb();
          else
            updateFromResult(item);
          if (keepInCache)
            addToCache(this);
        private static var _all:ArrayCollection = new ArrayCollection();
        public static function get all():ArrayCollection
          if (!getAllServiceCalled)
            getAllServiceCalled = true;
            MyUtility.httpPost("/page.aspx", {request:"SITE_EQUIPMENT_TYPE"}, getAll_result);
            var s:Sort = new Sort();
            s.fields = [new SortField("name", true)];
            _all.sort = s;
          return _all;
        public static function addEventListener(type:String, listener:Function):void
          eventDispatcher.addEventListener(type, listener);
        public static function removeEventListener(type:String, listener:Function):void
          eventDispatcher.removeEventListener(type, listener);
        public static function dispatchEvent(event:Event):Boolean
          return eventDispatcher.dispatchEvent(event);
        private static function addToCache(item:SiteEquipmentType):void
          removeFromCache(item.id);
          dict[item.id] = item;
          _all.addItem(item);
          dispatchEvent(new Event("cacheChanged"));
        private static function removeFromCache(id:int):void
          var item:SiteEquipmentType = dict[id];
          if (item)
            delete dict[id];
            _all.removeItemAt(_all.getItemIndex(item));
        public static function selectById(id:int):SiteEquipmentType
          if (dict[id])
            return dict[id];
          return new SiteEquipmentType(id);
        public static function selectFromObject(obj:Object):SiteEquipmentType
          var selected:SiteEquipmentType;
          var objId:int = obj.SITE_EQUIPMENT_TYPE_ID;
          if (dict[objId])
            selected = dict[objId];
            selected.updateFromResult(obj);
          else
            selected = new SiteEquipmentType(obj);
          return selected;
        private function updateFromResult(item:Object):void
          if (item)
            id = item.SITE_EQUIPMENT_TYPE_ID;
            name = item.SITE_EQUIPMENT_TYPE_NAME;
        private function toRequestObject():Object
          var o:Object = new Object();
          o.SITE_EQUIPMENT_TYPE_ID = id;
          o.SITE_EQUIPMENT_TYPE_NAME = name;
          return o;
        public function copy():SiteEquipmentType
          return new SiteEquipmentType(this.toRequestObject());
        public function save(value:SiteEquipmentType):void
          if (updateStatus == UpdateStatus.PENDING)
            Alert.show("Site Equipment Type is pending an update.", "Pending Update");
            return;
          else if (updateStatus == UpdateStatus.ERROR)
            Alert.show("There is a problem with this Site Equipment Type, and it cannot be saved. Please close the window.", "Save Failure");
            return;
          var request:Object;
          if (id == NEW_ID)
            if (value)
              request = value.toRequestObject();
            else
              request = toRequestObject();
            request._COMMAND = "INSERT";
          else
            if (value)
              request = MyUtility.objectDiff(this.toRequestObject(), value.toRequestObject());
              if (!request)
                dispatchEvent(new SiteEquipmentTypeEvent(SiteEquipmentTypeEvent.SITE_EQUIPMENT_TYPE_CREATE, this));
                return;
            else
              request = toRequestObject();
            request._COMMAND = "UPDATE";
            request._SITE_EQUIPMENT_TYPE_ID = id;
          delete request.SITE_EQUIPMENT_TYPE_ID;
          updateStatus = UpdateStatus.PENDING;
          MyUtility.httpPost("/updatetable.aspx?_SCHEMA=dbo&_TABLENAME=SITE_EQUIPMENT_TYPE&_RETURNRECORD=1", request, httpSave_result);
        public function toString():String
          return name;
        public function refreshFromDb():void
          if (updateStatus != UpdateStatus.PENDING)
            updateStatus = UpdateStatus.PENDING;
            MyUtility.httpPost("/page.aspx", {id:id, request:"Site_Equipment_Type"}, httpSelect_result);
        public function showEditForm(onCreate:Function = null, onEdit:Function = null, onCancel:Function = null):void
          if (id == 0)
            Alert.show("Edits are not allowed on this Site Equipment Type.", "Not Allowed");
            return;
          if (onCreate != null)
            addEventListener(SiteEquipmentTypeEvent.SITE_EQUIPMENT_TYPE_CREATE, onCreate);
          if (onEdit != null)
            addEventListener(SiteEquipmentTypeEvent.SITE_EQUIPMENT_TYPE_EDIT, onEdit);
          if (onCancel != null)
            addEventListener(SITE_EQUIPMENT_TYPE_CANCEL, onCancel);
          if (updateStatus == UpdateStatus.PENDING)
            setTimeout(showEditForm, 500);
          else if (updateStatus == UpdateStatus.COMPLETE)
            SiteEquipmentTypeEdit.open(this);
        public function cancelEdit():void
          dispatchEvent(new Event(SITE_EQUIPMENT_TYPE_CANCEL));
        private static function getAll_result(event:ResultEvent):void
          if (event.result.ROOT)
            if (event.result.ROOT.ERROR)
              Alert.show(event.result.ROOT.ERROR, "Error");
            else
              for each (var o:Object in MyUtility.ToArrayCollection(event.result.ROOT.SITE_EQUIPMENT_TYPE))
                var i:SiteEquipmentType = dict[o.SITE_EQUIPMENT_TYPE_ID];
                // If the Site Equipment Type is already in the cache, update it based on the XML returned
                if (i)
                  i.updateFromResult(o);
                  // Otherwise, create a new one from the XML returned
                else
                  i = new SiteEquipmentType(o);
              _all.refresh();
        private function httpSelect_result(event:ResultEvent):void
          if (event.result.ROOT)
            if (event.result.ROOT.ERROR)
              Alert.show(event.result.ROOT.ERROR, "Error");
              updateStatus = UpdateStatus.ERROR;
            else
              updateFromResult(event.result.ROOT.SITE_EQUIPMENT_TYPE);
              updateStatus = UpdateStatus.COMPLETE;
          else
            updateStatus = UpdateStatus.ERROR;
        private function httpSave_result(event:ResultEvent):void
          if (event.result.ROOT.ERROR)
            Alert.show(event.result.ROOT.ERROR, "Error");
            updateStatus = UpdateStatus.ERROR;
          else
            try
              updateStatus = UpdateStatus.COMPLETE;
              if (id == NEW_ID)
                id = event.result.ROOT.RESULTS.IDENTITY;
                addToCache(this);
                updateFromResult(event.result.ROOT["DBO.SITE_EQUIPMENT_TYPE"]);
                dispatchEvent(new SiteEquipmentTypeEvent(SiteEquipmentTypeEvent.SITE_EQUIPMENT_TYPE_CREATE, this));
              else
                updateFromResult(event.result.ROOT["DBO.SITE_EQUIPMENT_TYPE"]);
                dispatchEvent(new SiteEquipmentTypeEvent(SiteEquipmentTypeEvent.SITE_EQUIPMENT_TYPE_EDIT, this));
                SiteEquipmentType.dispatchEvent(new SiteEquipmentTypeEvent(SiteEquipmentTypeEvent.SITE_EQUIPMENT_TYPE_EDIT, this));
            catch(ex:Error)
              Alert.show(ex.message, "Error");
              updateStatus = UpdateStatus.ERROR;
    So the "_all" ArrayCollection serves as a cache of all of the different site equipment types.  When the edit window is first opened and a new instance of SiteEquipment is created, the SiteEquipmentType of the current SiteEquipment is added to _all and becomes the only SiteEquipmentType within _all.
    At this point, the DropDownList has the correct item selected.  The problem occurs when the result comes in from getting all of the SiteEquipmentTypes.  The contents of _all are flushed, and each SiteEquipmentType is added in.  Once this happens, the DropDownList will have nothing for selectedItem.
    I know this is quite complex, but any help would be greatly appreciated.

    Ok, I have this figured out now.  First, though, I'll point out that this worked fine when using MX components and the Halo theme; the problem only appeared after switching over to Spark components and the Spark theme.  Anyway, since this class functions as a singleton (as best I understand them), I added a boolean variable to the SiteEquipmentType class representing whether or not the results from the HTTPService call had come back and been inserted into _all.  So in the TitleWindow's init method, I only populated the DropDownList's originalValue (which in turn sets the selectedItem) if that variable is true.  The first time an instance of the TitleWindow component is opened, though, this variable will initially be false.  So back in the SiteEquipmentType class, I have it dispatch an event right after setting the variable to true, and the TitleWindow componet will add a listener for this event if the variable is originally false.  If anyone needs further explanation, please ask.

  • Optimizing a program (experts with a lot of time)

    The following code is most of the code for a sale program. This is something i have been working on for a while now and it's almost finished. It does work, and with no errors that I have found so far, but it seems too complicated and long. I am asking that some of you more experienced programmers take a look at it and give me some advice or tips. It's quite a bit of code, so you don't have to look at all of it, just whatever you see.
    This is the super class. It will soon be a full Log In for cashiers but right now it is just has two buttons for running the other two classes. It contains the open and save file methods that the others use to open the inventory file.
    /** Java core packages*/
    import java.util.*;
    import java.text.*;
    import java.awt.*;
    import java.awt.event.*;
    /** Java extension packages*/
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import java.io.*;
    /** This program is used to calculate the sale price
    * of selected items and update the inventory with
    * each sale. It opens and saves into a file "inventory.dat".
    * @author Davin Green
    public class LogIn extends JFrame
        /** JTextField objects for the text fields that are used in these programs.*/
        public JTextField jTextField1, jTextField2, jTextField3,
                           jTextField4, jTextField5, jTextField6;
        /** JButton objects for the buttons that are used in these programs.*/
        public JButton jButton1, jButton2, jButton3, jButton4,
                        jButton5, jButton6, jButton7;
        /** JScrollPane object for the scrolling pane that is used in this program.*/
        public JScrollPane jScrollPane1, jScrollPane2;
        /** Label objects for the labels that are used in these programs.*/
        public Label label1, label2, label3, label4,
                      label5, label6, label7;
        /** Vector objects for the three vectors that are used in these programs.*/
        public Vector id, qty, price, saleItems, saleItemsQty;
        /** JList object for the list of Items from vector id used in this program.*/
        public JList jList1;
        private double salePrice;
        /** Document objects for the three text fields that are used in this program.*/
        public Document jText1, jText2, jText3;
        /** DeciamlFormat object used to format display of money.*/
        private DecimalFormat toMoney;
        /** ObjectInputStream object for later inputing a stream.*/
        private ObjectInputStream objectInput;
        /** ObjectOutputStream object for later outputing a stream.*/
        private ObjectOutputStream objectOutput;
        private static LogIn window;
        public static void main( String args[] )
          window = new LogIn();
          window.setSize(450, 400);
          window.show();
        public LogIn()
            /** Get JFrames content pane and set layout to null.*/
            Container container = getContentPane();
            container.setLayout( new FlowLayout() );
            jButton1 = new JButton();
            jButton1.setText("Inventory Editor");
            container.add(jButton1);
            jButton2 = new JButton();
            jButton2.setText("Make Sale");
            container.add(jButton2);
          jButton1.addActionListener(
           new ActionListener()
             public void actionPerformed( ActionEvent event )
               Inventory inventory = new Inventory();
               inventory.runInventory();
               window.hide();
               window = null;
          jButton2.addActionListener(
           new ActionListener()
             public void actionPerformed( ActionEvent event )
               Computer computer = new Computer();
               computer.runComputer();
               window.hide();
               window = null;
        public LogIn( String title )
          super( title );
        /** The openFile() method opens inventory.dat and saves it's information into three vectors.*/
        public void openFile() throws IOException, ClassNotFoundException
          Item item;
          toMoney = new DecimalFormat( "0.00" );
          id = new Vector();
          qty = new Vector();
          price = new Vector();
         try {
              int i = 0;
              /** Opens file inventory.dat and saves data into buffer.*/
              try {
                objectInput = new ObjectInputStream( new FileInputStream( "C:/inventory.dat" ) );
              catch ( FileNotFoundException fnfException )
                objectOutput = new ObjectOutputStream( new FileOutputStream( "C:/inventory.dat" ) );
                objectOutput.close();
                objectInput = new ObjectInputStream( new FileInputStream( "C:/inventory.dat" ) );
                JOptionPane.showMessageDialog( null, "Inventory file has been created.", "File Created", JOptionPane.INFORMATION_MESSAGE );
              while ( true )
                /** Reads one item object from inventory.dat.*/
                item = ( Item ) objectInput.readObject();
                String idString = item.getID();
                String qtyString = "" + item.getQty();
                String priceString = "" + toMoney.format (item.getPrice());
                id.add( i, idString );
                qty.add( i, qtyString );
                price.add( i, priceString );
                i++;
          /** Closes file when end of file is reached.*/
          catch ( EOFException eofException )
             objectInput.close();
        /** The Method exitForm() sets what to do when window is closed.*/
        public void saveFile() throws IOException
         /** Makes file inventory.dat.*/
         objectOutput = new ObjectOutputStream( new FileOutputStream( "C:/inventory.dat" ));
         /** Saves three vectors as objects of the Item class into inventory.dat.*/
         for ( int i = 0; i < id.size(); i++ )
         String idString = (String)id.get(i);
         int qtyInt = Integer.parseInt( (String)qty.get(i) );
         double priceDouble = Double.parseDouble( (String)price.get(i) );
         Item item = new Item( idString, qtyInt, priceDouble );
         objectOutput.writeObject( item );
         /** Closes inventory.dat.*/
         objectOutput.close();
    }This is the computer class. It is used to calculate sale prices and print the reciept for each sale. It does everything it's supposed to except update the inventory, which I just haven't written the code for yet.
    /** Java core packages*/
    import java.util.*;
    import java.text.*;
    import java.awt.*;
    import java.awt.event.*;
    /** Java extension packages*/
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import java.io.*;
    /** This program is used to calculate the sale price
    * of selected items and update the inventory with
    * each sale. It opens and saves into a file "inventory.dat".
    * @author Davin Green
    public class Computer extends LogIn
        private double salePrice;
        private JTextArea jTextArea1;
        private Choice choice1;
        private JSeparator jSeparator1;
        private static Computer window;
        /** Default constructor.*/
        public Computer()
          super("Sale Program");
          try{
            try {
              openFile();
              createGUI();
              registerCompEventHandlers();
              salePrice = 0.0;
            catch ( ClassNotFoundException e )
          catch ( IOException e )
        /** The createGUI() methods creates and displays GUI components in the JFrame.*/
        private void createGUI()
            jList1 = new JList();
            saleItems = new Vector();
            saleItemsQty = new Vector();
            /** Get JFrames content pane and set layout to null.*/
            Container container = getContentPane();
            container.setLayout(null);
            choice1 = new Choice();
            makeChoiceMenu();
            container.add(choice1);
            choice1.setBounds(40, 50, 130, 20);
            jButton1 = new JButton();
            jButton1.setText("Add Item");
            container.add(jButton1);
            jButton1.setBounds(270, 50, 130, 20);
            jButton2 = new JButton();
            jButton2.setText("Remove Item");
            container.add(jButton2);
            jButton2.setBounds(270, 80, 130, 20);
            jButton2.setEnabled( false );
            jButton3 = new JButton();
            jButton3.setText("Print Reciept");
            container.add(jButton3);
            jButton3.setBounds(270, 110, 130, 20);
            jButton3.setEnabled( false );
            jButton4 = new JButton();
            jButton4.setText("New Sale");
            container.add(jButton4);
            jButton4.setBounds(270, 140, 130, 20);
            jButton4.setEnabled( false );
            jButton5 = new JButton();
            jButton5.setText("Change Cashier");
            container.add(jButton5);
            jButton5.setBounds(410, 240, 130, 20);
            jButton6 = new JButton();
            jButton6.setText("Edit Inventory");
            container.add(jButton6);
            jButton6.setBounds(410, 270, 130, 20);
            jButton7 = new JButton();
            jButton7.setText("Edit Qty");
            container.add(jButton7);
            jButton7.setBounds(100, 80, 100, 20);
            jButton7.setEnabled( false );
            jScrollPane1 = new JScrollPane();
            jTextArea1 = new JTextArea();
            container.add(jScrollPane1);
            jScrollPane1.setBounds(10, 190, 390, 100);
            jScrollPane2 = new JScrollPane();
            jScrollPane2.getViewport().add( jList1 );
            container.add(jScrollPane2);
            jScrollPane2.setBounds(410, 40, 130, 190);
            jSeparator1 = new JSeparator();
            container.add(jSeparator1);
            jSeparator1.setBounds(10, 40, 390, 10);
            jTextField1 = new JTextField();
            jTextField1.setEditable(false);
            jTextField1.setText("Cashier Name");
            container.add(jTextField1);
            jTextField1.setBounds(60, 10, 170, 20);
            jTextField2 = new JTextField();
            jTextField2.setEditable(false);
            jTextField2.setBounds(240, 10, 80, 20);
            jTextField3 = new JTextField();
            jTextField3.setEditable(false);
            DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.SHORT);
            jTextField3.setText(dateFormat.format(new Date()));
            container.add(jTextField3);
            jTextField3.setBounds(330, 10, 70, 20);
            jTextField4 = new JTextField();
            jTextField4.setText("");
            container.add(jTextField4);
            jTextField4.setBounds(60, 80, 30, 20);
            jText1 = jTextField4.getDocument();
            jTextField5 = new JTextField();
            jTextField5.setText("$0.00");
            container.add(jTextField5);
            jTextField5.setBounds(100, 140, 100, 20);
            jTextField6 = new JTextField();
            jTextField6.setEditable(false);
            jTextField6.setText("$0.00");
            container.add(jTextField6);
            jTextField6.setBounds(100, 110, 100, 20);
            label1 = new Label();
            label1.setText("Cashier");
            container.add(label1);
            label1.setBounds(10, 10, 48, 20);
            label2 = new Label();
            label2.setText("Item");
            container.add(label2);
            label2.setBounds(10, 50, 28, 20);
            label3 = new Label();
            label3.setText("Selected Item");
            container.add(label3);
            label3.setBounds(410, 20, 90, 20);
            label4 = new Label();
            label4.setText("Reciept");
            container.add(label4);
            label4.setBounds(10, 170, 50, 20);
            label5 = new Label();
            label5.setText("Quantity");
            container.add(label5);
            label5.setBounds(10, 80, 50, 20);
            label6 = new Label();
            label6.setText("Amount Paid");
            container.add(label6);
            label6.setBounds(10, 140, 80, 20);
            label7 = new Label();
            label7.setText("Sale Price");
            container.add(label7);
            label7.setBounds(10, 110, 60, 20);
            pack();
        /** The method registerEventHandlers() sets what each GUI object does.*/
        private void registerCompEventHandlers()
          ActionListener al = new ActionListener(){
                DateFormat fmt = DateFormat.getTimeInstance(DateFormat.SHORT);
                public void actionPerformed(ActionEvent evt) {
                    jTextField2.setText(fmt.format(new Date()));
            new javax.swing.Timer(1000, al).start();
            getContentPane().add(jTextField2);
            SwingUtilities.invokeLater(new Runnable(){
                public void run() {
          /** Sets program to call method exitForm() when window is closed.*/
          addWindowListener( new WindowAdapter()
                               public void windowClosing(WindowEvent evt)
                                 try {
                                   saveFile();
                                   System.exit(0);
                                 catch ( IOException ioException )
          /** Tells what to do when an item is selected on the drop down menu.*/
          final ItemListener choiceListener;
          choice1.addItemListener(
           choiceListener = new ItemListener()
             public void itemStateChanged( ItemEvent event )
               boolean itemNotExist = true;
               for ( int i = 0; i < saleItems.size(); i++ )
                 if ( choice1.getSelectedItem() == (String)saleItems.get( i ) )
                   itemNotExist = false;
                   jList1.setSelectedIndex( i );
                   jTextField4.setText( (String)saleItemsQty.get( i ) );
               if ( itemNotExist == true )
                 jTextField4.setText( "" );
               jButton1.setEnabled( itemNotExist );
               jButton7.setEnabled( false );
          /** When an item is selected, the items information is
           * displayed in the corresponding text field.*/
          jList1.addListSelectionListener(
           new ListSelectionListener()
             public void valueChanged( ListSelectionEvent event )
              if ( event.getSource() == jList1 && !event.getValueIsAdjusting() )
               int selection = 0;
               String selectionQty;
               try {
                 for ( int i = 0; i < choice1.getItemCount(); i++ )
                   if ( choice1.getItem(i) == jList1.getSelectedValue() )
                     selection = i;
                 selectionQty = (String)saleItemsQty.get( jList1.getSelectedIndex() );
                 choice1.select( selection );
               catch ( ArrayIndexOutOfBoundsException aoobException )
                selectionQty = "";
               jTextField4.setText( selectionQty );
               jButton1.setEnabled( false );
               jButton2.setEnabled( true );
               jButton3.setEnabled( true );
               jButton4.setEnabled( true );
               jButton7.setEnabled( false );
          /** Listens to jTextField and detects changes. */
          jText1.addDocumentListener(
            new DocumentListener()
              public void changedUpdate(DocumentEvent e)
                if ( saleItems.size() > 0 )
                  for ( int i = 0; i < saleItems.size(); i++ )
                    if ( choice1.getSelectedItem() == (String)saleItems.get( i ) )
                      jButton1.setEnabled( false );
                      if ( jTextField4.getText() != saleItemsQty.get( i ) )
                        jButton7.setEnabled( true );
                      else
                        jButton7.setEnabled( false );
                else
                  jButton1.setEnabled( true );
                  jButton7.setEnabled( false );
              public void insertUpdate(DocumentEvent e)
                if ( saleItems.size() > 0 )
                  for ( int i = 0; i < saleItems.size(); i++ )
                    if ( choice1.getSelectedItem() == (String)saleItems.get( i ) )
                      jButton1.setEnabled( false );
                      if ( jTextField4.getText() != saleItemsQty.get( i ) )
                        jButton7.setEnabled( true );
                      else
                        jButton7.setEnabled( false );
                else
                  jButton1.setEnabled( true );
                  jButton7.setEnabled( false );
              public void removeUpdate(DocumentEvent e)
                if ( saleItems.size() > 0 )
                  for ( int i = 0; i < saleItems.size(); i++ )
                    if ( choice1.getSelectedItem() == (String)saleItems.get( i ) )
                      jButton1.setEnabled( false );
                      if ( jTextField4.getText() != saleItemsQty.get( i ) )
                        jButton7.setEnabled( true );
                      else
                        jButton7.setEnabled( false );
                else
                  jButton1.setEnabled( true );
                  jButton7.setEnabled( false );
          /** When "Add Item" button is clicked, a new element
           *  is added to each vector.*/
          jButton1.addActionListener(
           new ActionListener()
             public void actionPerformed( ActionEvent event )
               String quantity = jTextField4.getText();
               jTextField4.setText( "" );
                try{
                 for ( int i = 0; i < id.size(); i++ )
                  if ( (String)id.get(i) == choice1.getSelectedItem() )
                    salePrice += ( Double.parseDouble( (String)price.get(i) ) * Double.parseDouble( quantity ) );
                 String newPrice = "$" + salePrice;
                 saleItems.add( choice1.getSelectedItem() );
                 saleItemsQty.add( quantity );
                 jList1.setListData( saleItems );
                 jScrollPane2.revalidate();
                 jScrollPane2.repaint();
                 jTextField6.setText( newPrice );
                 jButton1.setEnabled( false );
                catch ( NumberFormatException num )
                  JOptionPane.showMessageDialog( null, "Please enter a valid quantity!", "Error", JOptionPane.ERROR_MESSAGE );
                jList1.setSelectedIndex( saleItems.size() - 1 );
          /** When "Remove" button is clicked, the selected item is removed
           * from all vectors.*/
          jButton2.addActionListener(
           new ActionListener()
             public void actionPerformed( ActionEvent event )
               try {
               int selection = jList1.getSelectedIndex();
                 for ( int i = 0; i < id.size(); i++ )
                  if ( (String)id.get(i) == choice1.getSelectedItem() )
                   salePrice -= ( Double.parseDouble( (String)price.get(i) ) * Double.parseDouble( (String)saleItemsQty.get( selection )  ) );
                 String newPrice = "$" + salePrice;
                 saleItems.removeElementAt( selection );
                 saleItemsQty.removeElementAt( selection );
                 jList1.setListData( saleItems );
                 jScrollPane2.revalidate();
                 jScrollPane2.repaint();
                 jTextField6.setText( newPrice );
                 if( selection >= id.size() )
                  selection = id.size() - 1;
                 jList1.setSelectedIndex( selection );
               catch ( ArrayIndexOutOfBoundsException exception )
                 JOptionPane.showMessageDialog( null, "Please select an item to remove!", "Error", JOptionPane.ERROR_MESSAGE );
               if ( saleItems.size() == 0 )
                 jButton2.setEnabled( false );
               else
                 jButton2.setEnabled( true );
          /** When "Set Qty" button is clicked, the quantity of
           * the selected item is changed to the integer in
           * the qty text field.*/
          jButton7.addActionListener(
           new ActionListener()
             public void actionPerformed( ActionEvent event )
               int selection = jList1.getSelectedIndex();
               String newQty = jTextField4.getText();
               try {
                 int numbertest = Integer.parseInt( newQty );
                 for ( int i = 0; i < id.size(); i++ )
                  if ( (String)id.get(i) == choice1.getSelectedItem() )
                   salePrice -= ( Double.parseDouble( (String)price.get(i) ) * Double.parseDouble( (String)saleItemsQty.get( selection )  ) );
                   salePrice += ( Double.parseDouble( (String)price.get(i) ) * Double.parseDouble( newQty ) );
                 String newPrice = "$" + salePrice;
                 saleItems.set( selection, choice1.getSelectedItem() );
                 saleItemsQty.set( selection, newQty );
                 jScrollPane2.revalidate();
                 jScrollPane2.repaint();
                 jTextField6.setText( newPrice );
                 jButton7.setEnabled( false );
               catch ( NumberFormatException badinput )
                 JOptionPane.showMessageDialog( null, "Please enter an integer!", "Error", JOptionPane.ERROR_MESSAGE );
          /** When "Print Reciept" button is clicked, the price of
           * the selected item is changed to the double in
           * the price text field.*/
          jButton3.addActionListener(
           new ActionListener()
             public void actionPerformed( ActionEvent event )
               try{
               String reciept = "\tStore Name";
               String items = "";
               String temp = jTextField5.getText();
               String amountPaidString = "";
               double amountPaid = 0.0;
               double change;
               for ( int i = 1; i < temp.length(); i++ )
                 char a = temp.charAt(0);
                 char b = temp.charAt(i);
                 if ( a == '$' )
                   amountPaidString += b;
                 else
                   amountPaidString = "Error";
               amountPaid = Double.parseDouble( amountPaidString );
               if (amountPaid >= salePrice)
               change = amountPaid - salePrice;
               reciept += "\nDate: " + jTextField3.getText()
                 + "\t\tTime: " + jTextField2.getText()
                 + "\nCashier: " + jTextField1.getText()
                 + "\n\n\tItems:";
               for ( int i = 0; i < saleItems.size(); i++ )
                 items += "\n" + saleItems.get( i ) + "\t\t$";
                 for ( int h = 0; h < id.size(); h++ )
                  if ( (String)id.get(h) == (String)saleItems.get( i ) )
                    items += ( Double.parseDouble( (String)price.get(h) ) * Double.parseDouble( (String)saleItemsQty.get(h) ) );
               reciept += items + "\n\nTOTAL:\t$" + salePrice
                 + "\nAmount Paid:\t$" + amountPaid
                 + "\nChange:\t$" + change; 
                 jTextArea1.setText( reciept );
                 jScrollPane1.getViewport().add( jTextArea1 );
                 jScrollPane1.revalidate();
                 jScrollPane1.repaint();
                 jButton1.setEnabled( false );
                 jButton2.setEnabled( false );
                 jButton3.setEnabled( false );
                 jButton7.setEnabled( false );
                 jTextField4.setEditable( false );
                 jTextField5.setEditable( false );
                 choice1.removeItemListener( choiceListener );
               else
                 JOptionPane.showMessageDialog( null, "Amount Paid is not enough!", "Error", JOptionPane.ERROR_MESSAGE );
               catch ( NumberFormatException badinput )
                 JOptionPane.showMessageDialog( null, "Please enter a valid amount paid!", "Error", JOptionPane.ERROR_MESSAGE );
          jButton4.addActionListener(
           new ActionListener()
             public void actionPerformed( ActionEvent event )
               int select = 3;
               select = JOptionPane.showConfirmDialog( null, "Are you sure you want quit this sale?" );
               if (select == 0)
                 String[] run = {"xxx","yyy"};
                 window.hide();
                 main( run );
          jButton5.addActionListener(
           new ActionListener()
             public void actionPerformed( ActionEvent event )
               /* Code for what to do when "Change Cashier" button is clicked*/ /*
          jButton6.addActionListener(
           new ActionListener()
             public void actionPerformed( ActionEvent event )
               Inventory inventory = new Inventory();
               try{
               saveFile();
               catch ( IOException e )
               window.hide();
               inventory.runInventory();
               window = null;
        private void makeChoiceMenu()
          for ( int i = 0; i < id.size(); i++ )
            choice1.add( (String)id.get( i ) );
        /** The main method.*/
        public static void runComputer()
            window = new Computer();
            window.setSize(555, 335);
            window.show();
    }This is the inventory class. It's used to make and edit the items in the inventory and then save them into the inventory file.
    /** Java core packages*/
    import java.util.*;
    import java.text.*;
    import java.awt.*;
    import java.awt.event.*;
    /** Java extension packages*/
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import java.io.*;
    /** This program displays the inventory of a store and
    * allows user to edit each items name, quantity, and
    * price. It opens and saves into a file "inventory.dat".
    * @author Davin Green
    public class Inventory extends LogIn
        private static Inventory window;
        /** Default constructor.*/
        public Inventory()
          super("Inventory Editor");
          try{
            try{
            openFile();
            createInvGUI();
            registerInvEventHandlers();
            catch ( IOException e )
          catch ( ClassNotFoundException e )
        /** The createGUI() methods creates and displays GUI components in the JFrame.*/
        private void createInvGUI() throws IOException
            /** Get JFrames content pane and set layout to null.*/
            Container container = getContentPane();
            container.setLayout(null);
            /** List of items displayed in scrolling pane.*/
            jList1 = new JList( id );
            /** Put JList into the scrolling pane, add scrolling pane
             * to content pane, and set position and size.*/
            jScrollPane1 = new JScrollPane();
            jScrollPane1.getViewport().add( jList1 );
            container.add(jScrollPane1);
            jScrollPane1.setBounds(0, 0, 210, 370);
            /** Button for adding a new item.*/
            jButton1 = new JButton();
            jButton1.setText("Add Item");
            container.add(jButton1);
            jButton1.setBounds(240, 10, 90, 30);
            /** Button for deleting a selected item.*/
            jButton2 = new JButton();
            jButton2.setText("Delete");
            container.add(jButton2);
            jButton2.setBounds(290, 50, 90, 30);
            /** Button for setting the quantity of an item.*/
            jButton3 = new JButton();
            jButton3.setText("Set Qty");
            container.add(jButton3);
            jButton3.setBounds(240, 100, 90, 30);
            /** Button for setting the price of an item.*/
            jButton4 = new JButton();
            jButton4.setText("Set Price");
            container.add(jButton4);
            jButton4.setBounds(240, 150, 90, 30);
            /** Text field for inputing and displaying the id (name) of an item.*/
            jTextField1 = new JTextField();
            container.add(jTextField1);
            jTextField1.setBounds(340, 10, 93, 30);
            jText1 = jTextField1.getDocument();
            /** Text field for inputing and displaying the quantity of an item.*/
            jTextField2 = new JTextField();
            container.add(jTextField2);
            jTextField2.setBounds(370, 100, 43, 30);
            jText2 = jTextField2.getDocument();
            /** Text field for inputing and displaying the price of an item.*/
            jTextField3 = new JTextField();
            container.add(jTextField3);
            jTextField3.setBounds(370, 150, 43, 30);
            jText3 = jTextField3.getDocument();
            /** Displays "Qty" before the quantity text field.*/
            label1 = new Label();
            label1.setText("Qty");
            container.add(label1);
            label1.setBounds(350, 100, 20, 20);
            /** Displays "Price" before the price text field.*/
            label2 = new Label();
            label2.setText("Price");
            container.add(label2);
            label2.setBounds(340, 150, 30, 20);
            /** Button to change cashier (return to cashier log-in panel).*/
            jButton5 = new JButton();
            jButton5.setText("Change Cashier");
            container.add(jButton5);
            jButton5.setBounds(260, 270, 130, 30);
            /** Button to make sell (open make sell panel).*/
            jButton6 = new JButton();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    

    /** JTextField objects for the text fields that are used in these programs.*/
    public JTextField jTextField1, jTextField2, jTextField3,
                    jTextField4, jTextField5, jTextField6;Your variable names don't mean anything.
    So the person who has to maintain this program when you leave has a difficult task.
    If there was some indication that the operator would key in (say) a quantity, that would
    make it easier. You might name it "quantityText" in that case, or something like that.

  • The package failed to load due to error 0xC0011008

    I am trying to run a SSIS Package from SQL Server BI Studio. I receive the error "The package failed to load due to error 0xC0011008".  SQL Server 2008 R2 installed (32bit Win 7), along with Integration Services.  The Package connects
    to a SQL Server DB.
    Here is the full error taken from consol in BI Studio:
    SSIS package "CreateDynSSIS_DB_RunDynSSiSDB.dtsx" starting.
    Error: 0x1 at ST_Gen_Pkg_Src_SqlServ: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> Microsoft.SqlServer.Dts.Runtime.DtsRuntimeException: The package failed to load due to error 0xC0011008
    "Error loading from XML. No further detailed error information can be specified for this problem because no Events object was passed where detailed error information can be stored.". This occurs when CPackage::LoadFromXML fails.
     ---> System.Runtime.InteropServices.COMException (0xC0011008): The package failed to load due to error 0xC0011008 "Error loading from XML. No further detailed error information can be specified for this problem because no Events object was
    passed where detailed error information can be stored.". This occurs when CPackage::LoadFromXML fails.
       at Microsoft.SqlServer.Dts.Runtime.Wrapper.ApplicationClass.LoadPackage(String FileName, Boolean loadNeutral, IDTSEvents100 pEvents)
       at Microsoft.SqlServer.Dts.Runtime.Application.LoadPackage(String fileName, IDTSEvents events, Boolean loadNeutral)
       --- End of inner exception stack trace ---
       at ST_0f39f89613ca43e9a6660953aa72fa2c.csproj.ScriptMain.Main()
       --- End of inner exception stack trace ---
       at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig,       MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
       at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
       at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, CultureInfo culture)
       at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()
    Task failed: ST_Gen_Pkg_Src_SqlServ
    Warning: 0x80019002 at CreateDynSSIS_DB_RunDynSSiSDB: SSIS Warning Code DTS_W_MAXIMUMERRORCOUNTREACHED.  The Execution method succeeded, but the number of errors raised (1) reached the maximum allowed (1); resulting in failure. This occurs when the
    number of errors reaches the number specified in MaximumErrorCount. Change the MaximumErrorCount or fix the errors.
    SSIS package "CreateDynSSIS_DB_RunDynSSiSDB.dtsx" finished: Failure.
    The error is thrown at this line:
    DynamicPackage = app.LoadPackage(DynamicPackagePath, null);
    Any help would be great! I've done a bit of Googling on the topic already.. and nothing has worked so far.

    Hi,
    Reason for the error: Old
    version of the DTEXEC is picked up by SQL Server instead of the new one. 
    Refer this link for more info
    THE PACKAGE FAILED TO LOAD DUE TO ERROR 0XC0011008
    Hope this info Helps

  • 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;
        }

  • How can I test if an URL is valid in Actionscript 3.0 ?

    Hy, everyone!
    I`m trying to make a function that tests to see if an URL is
    valid and return true if it is, false otherwise, so that I can use
    it in an 'if' statement.
    The way I try to do it is by using two event listeners for
    the 'contentLoaderInfo' proprety of a Loader: one for Event.OPEN(if
    this event is dispatched, then I know the URL is valid) and one for
    IOErrorEvent.IO_ERROR(if this event is dispatched, then I know the
    URL is not valid).
    But the problem is that by using the event handler functions,
    I leave the main URL tester function, and am unable to return a
    value from it. The way I thought of to get around this problem was
    to set a returnValue variable, to which to assign the return value
    of the two event handler functions and then just go 'return
    returnValue;'. But I don`t know how to return a value from a event
    handler function, and even if I did I still couldn`t do it that
    way, because it takes some time to dispatch those events and the
    'returnValue' variable would be undefined by the time I try to
    return it.
    I hope you understood what I tryed to explain above... Here`s
    some code to ilustrate this better(it`s not valid, it`s just so you
    understand my problem):
    private function testUrl(url:String):void {
    var returnValue:Boolean;
    var loader:Loader = new Loader();
    returnValue =
    loader.contentLoaderInfo.addEventListener(Event.OPEN, onGoodUrl);
    // This is a global variable to which I assign the value of
    'loader' so that I can close it from onGoodUrl
    _testLoader = loader;
    returnValue =
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,
    onBadUrl);
    loader.load(new URLRequest(url));
    // Even if I knew how to make an event handler that returns a
    value, I`d still have to wait for the loading to start, and I
    couldn`t return the value here:
    return returnValue;
    private function onGoodUrl(event:Event):Boolean {
    _testLoader.close();
    return true;
    private function onBadUrl(event:IOErrorEvent):Boolean {
    return false;
    You know any way to go around this problem? Or, for that
    matter, do you know any other way to test for a valid URL?
    Thank you for your time!

    You need to test httpStatus of the URLLoader. Streaming
    content undergoes a specific process when coming into Flash. The
    only issue with httpStatus is that it does not work for every
    browser....mostly Linux based systems and lesser programs on the
    evolutionary food chain. I have not experienced problems with IE or
    NS/FF on Vista at this point.
    1. Send Request
    2. Receive HTTP Status (HTTPStatusEvent.HTTP_STATUS)
    3a. Status Good - Begin Load (Event.OPEN)
    3b. Status Bad - 404 or Protected Filed
    (IOErrorEvent.IO_ERROR)
    4. Receive File - Downloading (ProgressEvent.PROGRESS)
    5. Download Complete (Event.COMPLETE)

  • Where is the database connection for a mobile site?

    I have a Flash mobile site that I didn't create, but need to edit. On clicking the submit button it checks that the login & password are in a SQL database. The problem is, I can't find the method that runs a query on the database or where the database is even connected. I've tried searching through the code for words like "SQL", "database", and "connection" without success. I stepped through the code where I find a call to method "super", but then it goes back to the original method and then the user is logged in. Can someone explain where the call to the database is?
    Other things I'd like to know are: Where is the SQL Connection? In the main (non-mobile site), there is a web.config with a line that says
    <add name="TPConnectionString1"  connectionString="DataSource=xxx.xx.xxx.xx,xxxx\sqlexpress;Initial Catalog=TP;Persist Security  Info=True;User ID=xxxxx" providerName="System.Data.SqlClient"/>
    Where (what file: ex. web.config, xyz.as, etc.) would a similar line in the mobile code be?
    What does super(type, bubbles, cancelable) do?
    Here's the method for the submit button: LoginView.mxml
            private function btnclicked():void{  techController.username = txtUsername.text;  techController.password = txtPassword.text;  var evt:TechEvent = new TechEvent(TechEvent.LOGIN_USER);  this.dispatchEvent(evt);  }
    Here's the TechEvent function that is called: TechEvent.as
        public function TechEvent(type: String, bubbles:Boolean=true, cancelable:Boolean=false)  {  super(type, bubbles, cancelable);  }
    Here's the dispatchEvent method: UIComponent.as
    override public function dispatchEvent(event:Event):Boolean  {  if (dispatchEventHook != null)  dispatchEventHook(event, this);    return super.dispatchEvent(event);  }

    You are looking for an event handler for the TechEvent.LOGIN_USER event.
    Coding style looks similar to a SWIZ style framework, in which case, the event handlers could be defined using metadata [EventHandler] or [Mediate] tags, but could just be a plain simple .addEventListener(TectEvent.LOGIN_USER,fn); declaration earlier on.
    Either way, this is what has happened:
    1. User enters uname and password, then clicks button
    2. Button click handler populates the techController with relevant values then dispatches an event to let the world know it has done so
    3. The event handler checks the techController and makes the login call
    4. Some time later, the server will respond and trigger another event that the app can respond to
    G

  • Problem with filestree strange behavior

    i'm creating a tree which shows w directory with containing subfolders and files, and displays checbox with corresponding filename and size, everything is ok but when i click on checkbox, and then once again select it the sign to corresponding chechbox changes,why:
    package source.view;
    import java.awt.Dimension;
    import java.io.IOException;
    import java.io.StringReader;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import org.apache.xerces.parsers.SAXParser;
    import org.xml.sax.ContentHandler;
    import org.xml.sax.SAXException;
    import org.xml.sax.XMLReader;
    import org.xml.sax.InputSource;
    public class TreeImplementation extends JPanel {
         private static final long serialVersionUID = 1L;
         private DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
         private JTree tree;
         public void generateDataStructure(String structure){
              ContentHandler contentHandler = new XmlParser(root);
              try{
                   XMLReader parser = new SAXParser();
                   parser.setContentHandler(contentHandler);
                   parser.parse(new InputSource(new StringReader(structure)));
              }catch(IOException ioe){
                   ioe.printStackTrace();
              }catch(SAXException saxe){
                   saxe.printStackTrace();
         public TreeImplementation(String structure){
              //this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.setSize(1100, 1100);
              JButton downloadButton = new JButton("Download Files");
              generateDataStructure(structure);
              tree = new JTree(root);
              downloadButton.addActionListener(new ButtonListener(root,this));
              CheckBoxNodeRender renderer = new CheckBoxNodeRender();
              tree.setCellRenderer(renderer);
              tree.setCellEditor(new CheckBoxNodeEditor(tree));
              tree.setEditable(true);
              JScrollPane treeScroll = new JScrollPane(tree);
              treeScroll.setPreferredSize(new Dimension(300, 400));
              //treeScroll.add(tree);
              this.add(treeScroll);
              this.add(downloadButton);
              this.setVisible(true);
    package source.view;
    import java.awt.Component;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.awt.event.MouseEvent;
    import java.util.EventObject;
    import javax.swing.AbstractCellEditor;
    import javax.swing.JCheckBox;
    import javax.swing.JTree;
    import javax.swing.event.ChangeEvent;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreeCellEditor;
    import javax.swing.tree.TreePath;
    public class CheckBoxNodeEditor extends AbstractCellEditor implements TreeCellEditor {
         private static final long serialVersionUID = 1L;
         CheckBoxNodeRender renderer = new CheckBoxNodeRender();
         ChangeEvent event = null;
         JTree tree;
         public CheckBoxNodeEditor(JTree tree){
              this.tree = tree;
         public Object getCellEditorValue(){
              MyCheckbox checbox = renderer.getLeafRender();
              ResourceInfo resource  = new ResourceInfo(checbox.getText(), checbox.isSelected(),checbox.getDataSize());
              return resource;
         public boolean isCellEditable(EventObject event){
              boolean returnValue = false;
              if(event instanceof MouseEvent){
                   MouseEvent mouseEvent = (MouseEvent)event;
                   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;
                             Object myObject = treeNode.getUserObject();
                             returnValue = ((treeNode.isLeaf() && (myObject instanceof ResourceInfo)));
              return returnValue;
         public Component getTreeCellEditorComponent(JTree tree,Object value,boolean selected,
                   boolean expanded, boolean leaf,int row){
                   Component component = renderer.getTreeCellRendererComponent(tree, value, selected,
                             expanded, leaf, row, true);
                   ItemListener itemListner = new ItemListener() {
                        @Override
                        public void itemStateChanged(ItemEvent e) {
                             if(stopCellEditing()){
                                  fireEditingStopped();
                   if(component instanceof JCheckBox ){
                        ((JCheckBox) component).addItemListener(itemListner);
                   return component;
    package source.view;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Font;
    import javax.swing.JCheckBox;
    import javax.swing.JTree;
    import javax.swing.UIManager;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.TreeCellRenderer;
    public class CheckBoxNodeRender implements TreeCellRenderer {
         private MyCheckbox leafRender = new MyCheckbox();
         private DefaultTreeCellRenderer nonLeafRender = new DefaultTreeCellRenderer();
         private Color selectionForeground,selectionBackground,textForeground,
                             textBackground;
         protected MyCheckbox getLeafRender(){
              return this.leafRender;
         public CheckBoxNodeRender(){
              Font fontValue = UIManager.getFont("Tree.font");
              if(fontValue !=null){
                   leafRender.setFont(fontValue);
              Boolean booleanValue = (Boolean)UIManager.get("Tree.drawsFocusBorderAroundIcon");
              leafRender.setFocusPainted((booleanValue!=null)&&(booleanValue.booleanValue()));
              selectionForeground = UIManager.getColor("Tree.selectionForeground");
              selectionBackground = UIManager.getColor("Tree.selectionBackground");
              textForeground = UIManager.getColor("Text.textForeground");
              textBackground = UIManager.getColor("Tree.textBackground");
         public Component getTreeCellRendererComponent(JTree tree,Object value,
                   boolean selected,boolean expanded,boolean leaf,int row,boolean hasFocus){
              Component returnValue;
              if(leaf){
                   String stringValue = tree.convertValueToText(value, selected, expanded, leaf, row, false);
                   leafRender.setText(stringValue);
                   leafRender.setSelected(false);
                   if(selected){
                        leafRender.setForeground(selectionForeground);
                        leafRender.setBackground(selectionBackground);
                   }else{
                        leafRender.setForeground(textForeground);
                        leafRender.setBackground(textBackground);
                   if((value !=null) && (value instanceof DefaultMutableTreeNode)){
                        Object myObject = ((DefaultMutableTreeNode) value).getUserObject();
                        if(myObject instanceof ResourceInfo){
                             ResourceInfo node = (ResourceInfo)myObject;
                             leafRender.setText(node.resourceView());
                             leafRender.setDataSize(node.getResourceSize());
                             leafRender.setSelected((node.isSelected()));
                   returnValue = leafRender;
              }else{
                   returnValue = nonLeafRender.getTreeCellRendererComponent(tree, value, selected, expanded, leaf,
                             row, hasFocus);
              return returnValue;
    }

    It doesn't appear that you save the check selection state anywhere, so therefore your renderer (not the cell editor's renderer) doesn't know when a cell should be rendered as checked.
    The following is an example of check list, but note that it doesn't use the cell editor routine. Instead it is dependent on:
    [http://code.google.com/p/aephyr/source/browse/trunk/src/aephyr/swing/RolloverSupport.java]
    In fact, the following code's sole existence was to test that class in some type of scenario that would actually be useful. Note that the check selection model is differentiated from the normal selection model - that is necessary unless you do some rewiring of the InputMap/ActionMap so that it doesn't behave funky. Also note that for JTree, TreeSelectionModel will have to be used... and if you happen to decide to use the RolloverSupport way, RolloverSupprt.Tree in replace of RolloverSupport.List... The only real benefit of using RolloverSupport for this is that it seamlessly gives the component cell rollover feedback as long as the UI of JCheckBox paints differently upon rollover.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.util.*;
    import aephyr.swing.RolloverSupport;
    public class RolloverSupportCheckList implements Runnable, ItemListener, ActionListener {
            public static void main(String[] args) {
                    EventQueue.invokeLater(new RolloverSupportCheckList());
            public void run() {
                    list = new JList(java.lang.annotation.ElementType.values());
                    checkSelection = new DefaultListSelectionModel();
                    list.registerKeyboardAction(this, "Toggle Check Selection",
                                    KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), JComponent.WHEN_FOCUSED);
                    list.setCellRenderer(new Renderer());
                    Renderer rollover = new Renderer();
                    rollover.addItemListener(this);
                    rolloverSupport = new RolloverSupport.List(list, rollover);
                    JFrame frame = new JFrame();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new JScrollPane(list), BorderLayout.CENTER);
                    frame.setSize(200, 500);
                    frame.setVisible(true);
            JList list;
            ListSelectionModel checkSelection;
            RolloverSupport.List rolloverSupport;
            boolean ignoreSelectionChange = false;
            class Renderer extends JCheckBox implements ListCellRenderer {
                    Renderer() {
                            setFocusPainted(false);
                    @Override
                    public Component getListCellRendererComponent(JList list, Object value,
                                    int index, boolean isSelected, boolean cellHasFocus) {
                            setText(value == null ? "" : value.toString());
                            ignoreSelectionChange = true;
                            setSelected(checkSelection.isSelectedIndex(index));
                            ignoreSelectionChange = false;
                            setBackground(isSelected ? list.getSelectionBackground() : list.getBackground());
                            return this;
                    protected void processMouseEvent(MouseEvent e) {
                            if ((e.getModifiers() & (InputEvent.CTRL_MASK | InputEvent.SHIFT_MASK)) != 0) {
                                    list.dispatchEvent(SwingUtilities.convertMouseEvent(e.getComponent(), e, list));
                            } else {
                                    super.processMouseEvent(e);
            @Override
            public void itemStateChanged(ItemEvent e) {
                    if (ignoreSelectionChange)
                            return;
                    int index = rolloverSupport.getRolloverIndex();
                    if (e.getStateChange() == ItemEvent.SELECTED) {
                            checkSelection.addSelectionInterval(index, index);
                    } else {
                            checkSelection.removeSelectionInterval(index, index);
                    list.requestFocusInWindow();
            @Override
            public void actionPerformed(ActionEvent e) {
                    String cmd = e.getActionCommand();
                    if (cmd == "Toggle Check Selection") {
                            ListSelectionModel sel = list.getSelectionModel();
                            int max = sel.getMaxSelectionIndex();
                            if (max < 0)
                                    return;
                            int min = sel.getMinSelectionIndex();
                            for (int i=min; i<=max; i++) {
                                    if (sel.isSelectedIndex(i)) {
                                            if (checkSelection.isSelectedIndex(i)) {
                                                    checkSelection.removeSelectionInterval(i, i);
                                            } else {
                                                    checkSelection.addSelectionInterval(i, i);
                            Rectangle r = list.getCellBounds(min, max);
                            if (r != null)
                                    list.repaint(r);
                            int index = rolloverSupport.getRolloverIndex();
                            if (index >= min && index <= max)
                                    rolloverSupport.validate();
    }

  • "Hangman" wont work properly

    import java.awt.*;
    import java.awt.event.*;
    public class Hangman
      /* Extracts letters from the current woriginalCharArray and puts them in a character array */
      private static char[] wordChange (String originalCharArray)
        char[] temp;
          temp = new char[originalCharArray.length ()];
        for (int i = 0; i < originalCharArray.length (); i++)
         temp[i] = originalCharArray.charAt (i);
        return temp;
      /* Handles the 'Guess' button */
      private static class ActionHandler implements ActionListener
        public void actionPerformed (ActionEvent event)
          boolean changeWord;     // If true, change to next word
          boolean correctCheck;     // If false, decrease maxGuessCounter
          char guessedChar;          // Character entered by user
          // Check to see if it's the last word, and quit if it is
          if (index > 4)
           outputLabel.setText ("Game over");
           outputGuess.setText ("Your score is: " + points);
          guessedChar = (textField.getText ()).charAt (0);     // Reads character
          /* Resets boolean variables */
          changeWord = false;
          correctCheck = false;
          /* Checks if the guessed character exists in the Word, adds to points counter */
          for (int i = 0; i < originalCharArray.length; i++)
           if (guessedChar == originalCharArray)
         guessedCharArray[i] = guessedChar;
         correctCheck = true;
         points++;
    /* If false, decrease maxGuessCounter */
    if (correctCheck != true)
         maxGuessCounter--;
    /* Reset the values, to avoid concatenation */
    outputLabelWord = "";
    spacelessOutputWord = "";
    /* Go through array, and set the outputLabelWord to the guessedCharArray (e.g. set all the correctly guessed chars in a String, so you can display it */
    for (int i = 0; i < guessedCharArray.length; i++)
         outputLabelWord = outputLabelWord + " " + guessedCharArray[i];
         spacelessOutputWord = spacelessOutputWord + guessedCharArray[i];
    /* If the word is correctly guessed, or the maximum amount of guesses have been exhausted, change the word */
    if (spacelessOutputWord.equals (wordList[index]) || maxGuessCounter < 1)
         maxGuessCounter = 5;
         index++;
         originalCharArray = new char[wordList[index].length ()];
         originalCharArray = wordChange (wordList[index]);     // Extract characters from the word, enter them in a character array
         guessedCharArray = new char[originalCharArray.length];
         /* Reset the guessed character array */
         for (int i = 0; i < originalCharArray.length; i++)
         guessedCharArray[i] = '_';
         for (int i = 0; i < guessedCharArray.length; i++)
         guessCharString = guessCharString + " " + guessedCharArray[i];
         outputLabel.setText (guessCharString);
         changeWord = true;
    if (changeWord == false)
         outputLabel.setText (outputLabelWord);
    outputGuess.setText ("" + maxGuessCounter);
    /* Declare variables */
    private static int points = 0;
    private static int index;
    private static int maxGuessCounter;
    private static String spacelessOutputWord = "";
    private static String outputLabelWord = "";
    private static String word = " ";
    private static String guessCharString = "";
    private static Label outputLabel;
    private static Label outputGuess;
    private static TextField textField;
    private static Frame display;
    /* Declare arrays */
    private static char[] originalCharArray;
    private static char[] guessedCharArray;
    private static String[] wordList = { "h", "he", "hel", "hell", "hello" };
    public static void main (String[]args)
    textField = new TextField ("", 10);
    maxGuessCounter = 5;
    //Frame
    display = new Frame ();
    display.setLayout (new GridLayout (3, 2));
    index = 0;
    //Button stuff
    Button guess;
    ActionHandler action;
    guess = new Button ("Guess");
    outputGuess = new Label ("5");
    outputLabel = new Label (word);
    originalCharArray = new char[wordList[index].length ()];
    originalCharArray = wordChange (wordList[index]);
    guessedCharArray = new char[originalCharArray.length];
    // Initializes the outputLabel
    for (int i = 0; i < guessedCharArray.length; i++)
         guessedCharArray[i] = '_';
    for (int i = 0; i < guessedCharArray.length; i++)
         guessCharString = guessCharString + " " + guessedCharArray[i];
    outputLabel.setText (guessCharString);
    guess.setActionCommand ("guess");     // Name the button event
    action = new ActionHandler ();     // Instantiate listener
    guess.addActionListener (action);     // Register the listener
    //What to display on screen
    display.add (outputLabel);
    display.add (new Label (""));
    display.add (textField);
    display.add (guess);
    display.add (outputGuess);
    display.pack ();
    display.show ();
    display.addWindowListener (new WindowAdapter ()
    public void windowClosing (WindowEvent event)
    display.dispose ();
    System.exit (0);}
    Problems:
    1) Doesn't work well, when it comes to the last word. It requires an additional click, after the wrong guess, in order to show the game over thing.
    2) Gives an error message:
    java.lang.ArrayIndexOutOfBoundsException
    at Hangman$ActionHandler.actionPerformed(Hangman.java:85)
    at java.awt.Button.processActionEvent(Button.java:381)
    at java.awt.Button.processEvent(Button.java:350)
    at java.awt.Component.dispatchEventImpl(Component.java:3526)
    at java.awt.Component.dispatchEvent(Component.java:3367)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:445)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:191)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:144)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:130)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:98)
    when there.
    3) Doesn't set to correct number of "_"'s (i.e equal to the word) when you guess the right word; only after you have entered the first number does it set the number of "_"'s correctly, namely the same amount as characters in the word.

    Also another weird thing I noticed. Check this part of the code:
      private static char[] wordChange (String originalCharArray)  {    char[] temp;      temp = new char[originalCharArray.length ()];    for (int i = 0; i < originalCharArray.length (); i++)      {     temp<i> = originalCharArray.charAt (i);      }    return temp;  }When I change the length() to length, it doesnt work, although it shouldnt be length(). How come? I thought length() is for strings, and length is for arrays.

Maybe you are looking for

  • New to Java and I guess a scope question.

    Hello and thank you for taking the time to read this. I am not a real programmer, everything I have ever done was a total hack, or written without a full understanding of how I was doing it. One thing about Java is that you might have like 20 classes

  • Still photos imported to imovie change to solid green

    i'm using all the newest versions of iLife and Aperture (as of 11/13/13)... i use iMovie to make slideshows from my photography because i like the controls better than in Aperture or iPhoto... however, since upgrading to Mavericks and all of the new

  • Best Practices for data storage in portal database

    Hi, I need to store some stuctured data which is related to portal only. This data may grow data by data and may huge amount some point of time. Iam thinking which is the best way to handle it like maintanance point of view. i think i can store it in

  • Unit prie column disabled while doing miscellaneous issue.

    Hi, I'm doing miscellaneous issue on an item. but while doing the entry, the unit price column is disabled from entering the value. What could have gone wrong? But for some items the field was enabled to enter the unit price value. Both the items are

  • OBIEE Query

    Hi All, Can anybody help me on below question? 1. Does OBIEE Support for representation as a Tree Map? I have already gone through below site for squarified-treemap. http://hiteshbiblog.blogspot.com/2010/06/squarified-treemap-for-obiee-dashboard.html