RemoveElements/InsertElements

Is it just me or is an abomination and a string parameter that is passed to an array index? WTF?  I hope I'm missing something fundamental for why it must be like that.  However, you can only pass parameters like '[0]' to this feature or am I simply cannot build the right of expression to insert or remove the index determined by program?

I tried different versions of '[Str (Locals.Index_to_remove)]' but I do not have the syntax just as it should.

You can use the PropertyObject Get\Set * ByOffset functions combined with PropOption_InsertElement or PropOption_RemoveElement options to specify an array element by offset. It's pretty simple, as long as you have a one-dimensional zero-based array. Remember, arrays can be multidimensional, so a simple API with a single integer for index would not work in such cases. The lookupstring for an array of a multidimensional array element is a bit more complicated than what you do (e.g. "[1] [0] [3]" ""). There is also the PropertyObject.DeleteElements () method, which takes an offset.

That said, the phrase you are looking for is:

"[' + Str (Locals.Index_to_remove) +"]. "

-Doug

Tags: NI Software

Similar Questions

  • removeElement() question

    Is there a better way to remove a jacks and more removElement()?  I add the component with addElement(), removeElement() does not actually remove the memory component, only the display.  I'm not terribly worried, unless someone load a lot of components that have many graphics, text, styles, skins and associated as files.

    Thank you.

    Hello

    After calling removeElement(), which returns IvisualElement, you can catch this object and make it null.

    Hope this helps

    Rush me

  • Adding field in the item table programmatically

    Hello.

    I'm doing a generic 'engine' for generating test reports/certificates.

    I made a custom data containing type report item, I used to do a local variables array of report called table of report item items.

    The data type contains generic areas (chain of title elements, a string of type item, etc.) and a container of the element data.

    The idea is to increment the array of items to report with report items and then fill the data container of the element with the fields of for example a Table element container.

    Either that, or just add a field in the report item with the data Table element type.

    But I can't find a way to add fields programmatically in a container.

    Anyone know if this is even possible?

    Found!

    Using from one stage of education, who points to the array of report items using the NewSubProperty method.

    Finished with the following statement:

    Parameters.Report_Element_Array.InsertElements (GetNumElements (Parameters.Report_Element_Array), 1, 0),
    Parameters.Report_Element_Array [GetNumElements (Parameters.Report_Element_Array)-1]. NewSubProperty("Element_Data",PropValType_NamedType,False,"NSE_Report_Table",0)

  • Complete the table of reference

    Hello

    What I want: complete a table that is inside a container and named function of input parameters.

    What I tried:

    I created an object reference, Locals.obj_temp, which stores the set I want to fill the inside of the container.  I seem to be able to get the number of items, define the limits of the table, insert items, etc., but I can't figure out how to put values in there actually.

    I learned today that I can use ' * ' for dereferencing the ref of the object, so I use

    InsertElements(*Locals.obj_temp,"[0]",1),

    to add an item correctly.

    But, I don't know how to make the value I want it to be, and not not not the default value zero as shown in the picture.

    for what it's worth, this is how I make the new table inside the container and obtain a reference to it.

    Parameters.UniqueFCs.NewSubProperty(Parameters.UniqueFullTable[0][Locals.m],PropValType_Number,True,"",0),
    Locals.obj_temp = Parameters.UniqueFCs.GetPropertyObject(Parameters.UniqueFullTable[0][Locals.m],0),

    I found a way to do it.

    I created a temporary table as Locals.Arr1 and clone to the container parameter I want.

    For all of you who found this thread, I have

    Locals.Arr1 //my table temp I empty at each iteration of my loop for external

    /*
    code that fills Arr1
    */
    Locals.obj_clone = Locals.Clone("Arr1",0), //create a clone of obj of Arr1
    Parameters.UniqueFCs.SetPropertyObject (Locals.name_temp, 1, Locals.obj_clone), //copy Arr1 table in my output tray (my container is called UniqueFCs)

  • Capture engine pointer to external application

    Hello

    I need a program to change a Global sequence running. Simplify, I need to change a Boolean Global with an external application (in c#). If someone has done something similar, I would like to know how.

    So far, ive tried to save the object pointer in the configuration file, through TestStand and an another c# application, but it was not good because it save it as an object com I now try to use Remote Access Services to launch a service (with the current engine) with TestStand so my application can communicate with the engine via remote access.

    I tried my client-server without TestStand and works very well, but I can't grow if I run the application server through TestStand.

    I know more ways to capture the pointer of the engine... Any idea?

    Daniel

    Probably the best thing to do would be to use a queue of TestStand or notification for transmitting data between processes. Using the step type, if you start the name of a queue with a ' *' character then the queue will be global for the entire machine. To access the queue of your external application programmatically, create an instance of the teststand engine and call GetSyncManager() on this topic with the name of your queue (i.e. it must begin with a ' *' character). Then use synchronization to TestStand API with returned Synchronization Manager Manager to get the existing queue and access. Notifications can also pass data and can be used in the same way. You can store the global variable itself by reference to the queue and get the external application using Dequeue in a TestStand object reference variable (pass false for the Microsoft.SqlServer.Management.Sdk.Sfc.ISfcCollection.RemoveElement parameter so that it remains in the queue for the life of the queue). See the teststand help file for Synchronization Manager and the queue of API information. You can create a TestStand object reference variable to store the corresponding element using Engine.NewPropertyObject (). Then once there, simply call GetValueInterface and access the value returned as a PropertyObject himself.

    Hope this helps,

    -Doug

  • Listener GPS problem

    Hi people,

    In collaboration with 4.2.1 on the 8800 Simulator.  My application is currently composed of two separate applications, app UI to obtain/view the information and a 'replication' application that communicates with our backend. I want to be able to include location on request of the user data (in the application user interface) and once it is updated, have replication app send it to the server. I have this work especially to my satisfaction, but the following problem: when I close the application user interface, any incomplete GPS please never finished. It seems that my LocationListener is not registered, or maybe the listener Thread is killed the closure of the part of the user interface. I don't expect that the instance is stored in the runtimestore and the object that is saved as the listener is always valid. Here's how I set it up:

    App of the user interface, the following is performed from a menu, click:

                GPSUpdater gps = GPSUpdaterFactory.getGPSUpdater();            gps.getGPSData(row, GPSUpdater.CHECK_IN);
    

    Replication App: (cut a lot of independent code)

    class ReplicationManagerImpl implements LocationListener{    private GPSUpdater mGPSUpdater;
    
        ReplicationManagerImpl()    {        mGPSUpdater = GPSUpdaterFactory.getGPSUpdater();        mGPSUpdater.setListener(this);    }
    
        public void locationUpdated(LocationProvider provider, Location location)    {        mGPSUpdater.newLocationReceived(location);    }
    
        public void providerStateChanged(LocationProvider provider, int newState)    {        //Not worried about this    }}
    

    GPSUpdater:

    public class GPSUpdater{    private Vector mUpdates;    private LocationProvider mProvider;    private Location mLocation;    private LocationListener mListener;    private Boolean isAcquiring;    private int mCounter;
    
        private static final int MAX_RETRIES = 10;    public static final int CHECK_IN = 0;    public static final int CONFIRM = 1;
    
        private static class UpdateData    {        private DataRow suRow;        private int updateType;        private long timeStamp;    }
    
        GPSUpdater()    {        Criteria criteria = new Criteria();        criteria.setHorizontalAccuracy(50);        criteria.setVerticalAccuracy(50);        criteria.setCostAllowed(false);        try        {            mProvider = LocationProvider.getInstance(criteria);            if (mProvider.getState() == LocationProvider.OUT_OF_SERVICE)            {                SubsystemLog.log("GPS actions not supported", EventLogger.ALWAYS_LOG);            }        }        catch (LocationException lEx)        {            SubsystemLog.log("Error creating LocationProvider in GPSUpdater: " + lEx.getMessage(), EventLogger.ERROR);        }        mUpdates = new Vector();        mLocation = null;        isAcquiring = Boolean.FALSE;        mCounter = 0;    }
    
        public void setListener(LocationListener listener)    {        mListener = listener;    }
    
        public void getGPSData(DataRow row, int updateType)    {        long timestamp = System.currentTimeMillis();        if (((mLocation != null) && (mLocation.isValid()) && (mLocation.getTimestamp() > timestamp - 60000)) || (mProvider == null) || (mProvider.getState() == LocationProvider.OUT_OF_SERVICE))        {            UpdateRow(row, updateType, timestamp);        }        else        {            UpdateData update = new UpdateData();            update.row = row;            update.updateType = updateType;            update.timeStamp = timestamp;
    
                synchronized(mUpdates)            {                mUpdates.addElement(update);            }
    
                synchronized(isAcquiring)            {                if (!isAcquiring.booleanValue())                {                    mProvider.setLocationListener(mListener, 5, 5, -1);                    isAcquiring = Boolean.TRUE;                }            }        }    }
    
        public void newLocationReceived(Location location)    {        if ((location == null) || (!location.isValid()) && (mCounter < MAX_RETRIES))        {            mCounter++;            return;        }
    
            mCounter = 0;        mLocation = location;        SubsystemLog.log("Acquired co-ordinates: " + Double.toString(location.getQualifiedCoordinates().getLatitude()) + "," + Double.toString(location.getQualifiedCoordinates().getLongitude()), EventLogger.DEBUG_INFO);
    
            Database db = DataSystemFactory.getDataSystem().openDatabase(DBSchema.NAME);        Object syncObject = db.getSyncObject();
    
            synchronized(syncObject)        {            while (mUpdates.size() > 0)            {                UpdateData update = (UpdateData)mUpdates.elementAt(0);                UpdateRow(update.row, update.updateType, update.timeStamp);                mUpdates.removeElement(update);            }        }        db.commitAndNotify();
    
            synchronized(isAcquiring)        {            provider.setLocationListener(null, -1, -1, -1);            isAcquiring = Boolean.FALSE;        }    }
    
        private void UpdateRow(DataRow suRow, int updateType, long timeStamp)    {        //wrapper class to allow persisting double values        DBDouble latitude = new DBDouble();        DBDouble longitude = new DBDouble();
    
            if (mLocation != null && mLocation.isValid())        {            latitude.setDouble(mLocation.getQualifiedCoordinates().getLatitude());            longitude.setDouble(mLocation.getQualifiedCoordinates().getLongitude());        }        else        {            latitude.setDouble(0.0);            longitude.setDouble(0.0);        }
    
            //store data here    }
    
    }
    

    GPSUpdaterFactory:

    public abstract class GPSUpdaterFactory {    private static final long ID = ;
    
        public static final GPSUpdater getGPSUpdater()    {        Object o;        GPSUpdater gpsUpdater = null;        RuntimeStore runtimeStore = RuntimeStore.getRuntimeStore();        synchronized (runtimeStore)        {            o = runtimeStore.get(ID);            if (o != null)            {                if (o instanceof GPSUpdater)                {                    gpsUpdater = (GPSUpdater)o;                }            }            if (gpsUpdater == null)            {                gpsUpdater = new GPSUpdater();                runtimeStore.put(ID, gpsUpdater);            }        }        return gpsUpdater;            }}
    

    Any suggestions are greatly appreciated.

    Thank you

    Mike

    Notice that the menu close item also called System.exit.

    In this case the application would stop receiving updates following the call of output.  To work around this problem, you can call Application.requestBackground.  This moves the application in the background, where it can continue to operate.  Once you have your final fix application can call System.exit to close itself.

  • Static Singleton instance reference gets cleaned memory!

    OK, it's one of the strangest things I've ever seen.

    I am currently working on a project where I use a singleton like this:

    public class SingletonExample {  private static SingletonExample instance; private Vector listeners; private PhoneListener phoneListener;
    
      private SingletonExample(){       listeners = new Vector();     phoneListener = new PhoneListenerImpl();  }
    
      public static synchronized SingletonExample getInstance(){        if(instance == null){         instance = new SingletonExample();        }     return instance;  }
    
      public synchronized void addListener(SomeListener listener){      if(listener != null){         synchronized(listeners){              listeners.addElement(listener);               if(listeners.size() == 1){                    Phone.addPhoneListener(phoneListener);                }         }                 } }
    
      public synchronized void removeListener(SomeListener listener){       if(listener != null){         synchronized(listeners){              if(listeners.contains(listener)){                 listeners.removeElement(listener);                }                 if(listeners.isEmpty()){                  Phone.removePhoneListener(phoneListener);             }         }                 } }
    
      private void reportListeners(){       synchronized(listeners){          int sz = listeners.size();            for(int i = 0; i < sz; i++){               final SomeListener sl = (SomeListener) listeners.elementAt(i);                new Thread(){                 public void run(){                        sl.onListenerReported();                  }             }.start();            }     } }
    
      private class PhoneListenerImpl implements PhoneListener {        public void callAdded(int arg0) {}
    
          public void callAnswered(int arg0) {}
    
           public void callConferenceCallEstablished(int arg0) {}
    
          public void callConnected(int arg0) {     }
    
           public void callDirectConnectConnected(int arg0) {}
    
         public void callDirectConnectDisconnected(int arg0) {}
    
          public void callDisconnected(int arg0) {          reportListeners();            }
    
           public void callEndedByUser(int arg0) {           reportListeners();                }
    
           public void callFailed(int arg0, int arg1) {          reportListeners();                    }
    
           public void callHeld(int callId) {}
    
         public void callIncoming(int callId) {}
    
         public void callInitiated(int callid) {}
    
            public void callRemoved(int callId) {}
    
          public void callResumed(int callId) {}
    
          public void callWaiting(int callid) {}
    
          public void conferenceCallDisconnected(int callId) {} }}
    

    (Not the best singleton, but very safe and is the one I usually use).

    Want to-be-singleton class contains a collection of the listener (I have not included SomeListener interface, but it is very simple, only an onListenerReported of the method). Also contains an instance of PhoneListener. When a call is disconnected, the class of SingletonExample should report each listener on a new Thread.

    Now the collections on static variables is subject to leaks memory, but this class is intended to contain only one or two listeners at a time, so there is not much. And as we are about to see, the static integer variable 'instance' is going to be garbage collected between "consecutive" calls to getInstance.

    Now, I have a method like this, taken from a menu action:

    public void someMethodFiredFromMenu() {  new Thread(){     public void run(){
    
              SomeListener listener = new SomeListener(){               public void onListenerReported() {                    System.out.println(">>>>>>> Call disconnected!");
    
                      //FIXME: Singleton static member is null at this point,                   // so it is constructed again!!!                  SingletonExample.getInstance().removeListener(this);
    
                      //Do other things here                                    }                                     };
    
              //First call to getInstance, static member is constructed as expected         SingletonExample.getInstance().addListener(listener);     } }.start();}
    

    If test you it on a 4.7 Simulator I (BlackBerry 9530 Simulator, v4.7.0.75) you can see that the static variable singleton (named 'instance' within class SingletonExample) is collected between calls to someMethodFiredFromMenu.

    It never happened to me before. Somehow, that there are two threads involved, the JAVA virtual machine (if we can call it ) determines that the variable is more accessible and collects, thus screwing my design.

    Interesting things:

    Make two consecutive getInstance calls in the same thread works.

    Holding a last reference to the SingletonExample within the method of the menu and its use (even in different threads) also works.

    * Note: I've changed a few names from my original code, so there are compilation errors, but at least you know what the code meant.

    It is a feature of the BlackBerry JVM and what others have stumbled on before, including me.

    The best way to summarize the problem is that a static is only a Singleton when the static object references are in the same instance of the Application.

    Another way to say it is that each instance of the Application has its own set of static variables.

    The problem here is that you code earphone is running an application, which will have a set of difference of static variables for your Application.

    Here the best way to create a Singleton in a BlackBerry

    http://supportforums.BlackBerry.com/T5/Java-development/create-a-singleton-using-the-RuntimeStore/TA...

    That said, I would recommend that you avoid treatment on the earpiece - if you can only use global event to convey the information for your Application, then it can be handled in your Application and static object is a Singleton!

    A bit off-topic and just because I'm here, but what's the point of the Thread in this treatment?

    public void someMethodFiredFromMenu() {}
    New Thread() {}
    public void run() {}

    SomeListener listener = new SomeListener() {}
    public void onListenerReported() {}
    System.out.println ("> call disconnected!");

    FIXME: Singleton static member is NULL at this point,
    Thus, it is built again!
    SingletonExample.getInstance () .removeListener (this);
    Do other things here
    }
    };

    First call to getInstance static member is built as planned
    SingletonExample.getInstance () .addListener (listener);
    }
    }. start();
    }

  • When sending sms, some no-contact. SMS and some no-contact. not get?

    Hi all

    I developed the sms application, when I send the SMS from this application, some no-contact. to sms but some no-contact. do not get.

    can someone help me?

    concerning

    Savi

    Hi all

    I solved this problem. now I can send message to anyone of this sms application.

    If anyone need this app, I'm writing this request here... This works perfectly...

    package sms.savi;

    Net.rim.device.api.ui import. *;
    Net.rim.device.api.ui.component import. *;
    Net.rim.device.api.ui.container import. *;
    Javax.microedition.io import. *;
    Import Java.util;
    import java. IO;
    Javax.wireless.messaging import. *;

    class SmsDemo extends UiApplication {}

    Constants
    // ----------------------------------------------------------------
    private static final int MAX_PHONE_NUMBER_LENGTH = 32;

    Members
    // ------------------------------------------------------------------
    Private EditField _sendText.
    Private EditField _address; A phone number for outgoing SMS messages.
    Private _status EditField.
    Private ListeningThread _listener;
    private SendThread _sender.
    private StringBuffer _statusMsgs = new StringBuffer(); Caching for
    improved
    performance

    private MessageConnection _mc;
    Private boolean _stop = false;

    _sendMenuItem private MenuItem = new MenuItem ("send", 100, 10) {}
    public void run() {}
    String text = _sendText.getText ();
    String addr = _address.getText ();

    If (text.length > 0 () & addr.length () > 0) {}
    Send (addr, text);

    }
    }
    };

    Static
    // ------------------------------------------------------------------
    private static String _openString = "sms: / /"; See connector

    information on the implementation.

    Public Shared Sub main (String [] args) {}
    Create a new instance of the application and the beginning
    the application on the thread of the event.
    SmsDemo sms = new SmsDemo();
    sms.enterEventDispatcher ();
    }

    Inner classes
    // ------------------------------------------------------------
    private class ListeningThread extends Thread {}
    synchronized Private Sub {} stop()
    _stop = true;

    try {}
    If (_mc! = null) {}
    Close the connection so that the thread will return.
    _mc. Close();
    }
    } catch (IOException e) {}
    System.Err.println (try ());
    }
    }

    public void run() {}
    try {}
    _mc = Connector.open (_openString) (MessageConnection); Closed
    by
    the
    Stop()
    method.

    for (; {
    If {(_stop)
    return;
    }

    Message m = _mc.receive ();
    receivedSmsMessage (m);
    }
    } catch (IOException e) {}
    Probably the stream has been closed.
    System.Err.println (try ());
    }
    }
    }

    /**
    * A simple abstraction of an sms message, used by the SendThread class.
    */
    private static final class SmsMessage {}
    private String _address;
    private String _msg;

    private SmsMessage (String address, String msg) {}
    _address = address;
    _msg = msg;
    }

    Private Message toMessage (mc MessageConnection) {}
    TextMessage m = (mc.newMessage) (text)
    MessageConnection.TEXT_MESSAGE, ' / / ' + _address
    + "");
    m.setPayloadText (_msg);

    return m;
    }
    }

    /**
    * A thread to handle outbound transactions.
    */
    private class SendThread extends Thread {}
    private static final int TIMEOUT = 500; MS

    Create a vector of objects SmsMessage with an initial capacity of 10.
    For this implementation, it is unlikely that more than 10 messages
    queued at a time given.
    private vector _msgs = new Vector (10);

    volatile Boolean _start private = false;

    The applications are pending.
    private synchronized {void send (address of the string, String msg)
    _start = true;
    _msgs. AddElement (new SmsMessage (address, msg));
    }

    Termination of the thread.
    synchronized Private Sub {} stop()
    _stop = true;

    try {}
    If (_mc! = null) {}
    _mc. Close();
    }
    } catch (IOException e) {}
    System.Err.println (e);
    updateStatus (try ());
    }
    }

    public void run() {}

    for (; {
    Adjustment of the wire.
    While (! _start &! _stop) {}
    Sleep for a bit so we don't spin.
    try {}
    Sleep (timeout);
    } catch (InterruptedException e) {}
    System.Err.println (try ());
    }
    }

    Exit condition.
    If {(_stop)
    return;
    }

    While (true) {}
    try {}
    SmsMessage sms = null;

    synchronized (THIS) {}
    If (! _msgs.isEmpty ()) {}
    SMS = _msgs.firstElement () (SmsMessage);

    Delete the item so that we don't send it again.
    _msgs. RemoveElement (SMS);
    } else {}
    _start = false;
    break;
    }
    }

    _mc. Send (SMS.toMessage (_mc));
    _mc. Close();
    System.Exit (0);

    } catch (IOException e) {}
    System.Err.println (e);
    updateStatus (try ());
    }
    }
    }
    }
    }

    private class SmsDemoScreen extends form {}

    Constructor
    private SmsDemoScreen() {}
    Dim str As String = "8971833590";
    String = msgStr "How are you?"
    setTitle (new LabelField ("Demo SMS", LabelField.USE_ALL_WIDTH));

    _address = new EditField ("to:", "", MAX_PHONE_NUMBER_LENGTH,)
    EditField.FILTER_PHONE);
    Add (_address);
    Add (new SeparatorField());
    _sendText = new EditField ("Message:", "");
    Add (_sendText);

    /*
    * _status = new EditField(); Add (_Status);
    */

    addMenuItem (_sendMenuItem);
    }

    /**
    Prevent save them dialog box is displayed.
    *
    * @see net.rim.device.api.ui.container.MainScreen #onSavePrompt)
    */
    public boolean onSavePrompt() {}
    Returns true;
    }

    /**
    * Close the application
    *
    * @see net.rim.device.api.ui.Screen #close)
    */
    {} public void close()
    _listener. Stop();
    _sender. Stop();
    Super.Close ();
    }
    }

    Constructor
    private SmsDemo() {}
    _listener = new ListeningThread();
    _listener. Start();

    _sender = new SendThread();
    _sender. Start();

    Screen SmsDemoScreen = new SmsDemoScreen();
    pushScreen (screen);
    }

    /**
    * Update the GUI with the data just got.
    */
    {} private void updateStatus (final String msg)
    invokeLater (new Runnable() {}
    public void run() {}
    Delete the string buffer.
    _statusMsgs.Delete (0, _statusMsgs.length ());
    _statusMsgs.Append (_Status.GetText ());
    _statusMsgs.Append ('\n');
    _statusMsgs.Append (MSG);
    _Status.SetText (_statusMsgs.ToString ());
    }
    });

    }

    /**
    * A simple formatting of received sms message.
    */
    Private Sub receivedSmsMessage (Message m) {}
    String msg_app = m.getAddress ();
    Address of string = m.getAddress ();
    String msg = null;

    If (m instanceof TextMessage) {}
    TextMessage tm = m (text);
    MSG = tm.getPayloadText ();
    }

    StringBuffer sb = new StringBuffer();
    SB. Append("Received:");
    SB. Append ('\n');
    SB. Append("destination:");
    SB. Append (Address);
    SB. Append ('\n');
    SB. Append("Data:");
    SB. Append (MSG);
    SB. Append ('\n');

    updateStatus (sb.toString ());
    }

    private send Sub (String addr, String data) {}
    _sender. Send (addr, data);
    }
    }

    Of

    Savi

  • SMS for outgoing SMS listener throws IOException immediately after the open call

    I had already created a class for sending SMS messages which worked perfectly until I added the listener. When the listener is added as soon as I start the thread throws an IOException exception who am I hurting? The only thing I can think is some kind of wire problem, please help.

    Here's the SMS & Listener class:

    private static final class SmsMessage    {        private String _address;        private String _msg;
    
            public SmsMessage(String address, String msg)        {            _address = address;            _msg = msg;        }
    
            public Message toMessage(MessageConnection mc)        {            TextMessage m = (TextMessage)mc.newMessage(MessageConnection.TEXT_MESSAGE,"sms://" + _address);            m.setPayloadText(_msg);            return m;        }    } // SmsMessage
    
       private final class SendThread extends Thread    {        private static final int TIMEOUT = 500; // ms        private Vector _msgs = new Vector(10); // Queue of 10        private volatile boolean _start = false;
    
            // queue requests        public synchronized void send(String address, String msg)        {            _start = true;            _msgs.addElement(new SmsMessage(address, msg));        }
    
            public synchronized void stop()        {            _stop = true;            try {                if ( _mc != null ){                    _mc.close();                }            } // catch (IOException e ) {                catch (Throwable t) {                t.printStackTrace();                System.exit(0);            }
    
            }
    
            public void run()        {            try {                //closed by the stop() method                _mc = (MessageConnection)Connector.open("sms://");
    
                    if (_mc != null)                {                    // set a listener to trap outgoing sms messages                    _mc.setMessageListener(new OutboundSMSListener());                }                for(;;)                {                    while( !_start && !_stop)                    {                        try {                            sleep(TIMEOUT);                        } // catch (InterruptedException e) {                            catch (Throwable t) {                                t.printStackTrace();                                System.exit(0);                            }                    }                    if ( _stop )                    {                        return;                    }
    
                        while(true)                    {                        try {                            SmsMessage sms = null;                            synchronized (this)                            {                                if ( !_msgs.isEmpty() )                                {                                    sms = (SmsMessage)_msgs.firstElement();                                    // take it out of the queue once we sent it                                    _msgs.removeElement(sms);                                }                                else                                {                                    _start = false;                                    break;                                }                            }
    
                                _mc.send(sms.toMessage(_mc));
    
                            } // catch (IOException e) {                            catch (Throwable t) {                                t.printStackTrace();                                System.exit(0);                        }                    }                }            } // catch (IOException e)              catch (Throwable t) {                t.printStackTrace();                System.exit(0);              }        }    } // SendThread
    
        private static final class OutboundSMSListener implements OutboundMessageListener    {        public void notifyIncomingMessage(MessageConnection messageconnection)        {            // we don't care about incoming sms messages right now        }
    
            public void notifyOutgoingMessage(Message message)        {            Dialog.alert("Detected An Outgoing SMS Event");        }    }
    

    Thank you. Makes sense.

  • How to remove an item that has been added from code?

    Hello

    I have a BorderContainer component personalized with 2 tags and 1 image.

    I added an instance of it to my code with addElement() request and now I can't make go away

    I am trying:

    for (var i: int = 0; i < numElements; i ++) {}

    If (getElementAt (i) map) {}

    If ((getElementAt (i) as Card).name.substr (0.6) == "cMover") {}

    removeElementAt (i);

    }

    }

    }

    He finds it because it happens to removeElementAt (i); but the component remains visible.

    I also tried removeElement (getElementAt (i)); no luck.

    What I am doing wrong?

    Thank you

    Gabor

    You may need to call

    invalidateDisplayList();

    After that you remove.

  • How not to sort datagrid column on double click

    Hello

    I'm currently building an application containing a DataGrid for the representation of data. I created a datagridheader custom in order to add an input text for the filtering of the columns (see code below).

    My goal is to hide the textinput and then display it on a double click on the header. So I would like to know how to avoid the type of this column whenever I double click. ?

    <? XML version = "1.0" encoding = "utf-8"? >

    " < = xmlns:fx s:GridItemRenderer ' http://ns.Adobe.com/MXML/2009 "

    xmlns:s = "library://ns.adobe.com/flex/spark".

    xmlns:MX = "library://ns.adobe.com/flex/mx" resize = "onColumnResize (event)" clipAndEnableScrolling = 'true' doubleClick = "managefilterField (event)" > "

    < fx:Declarations >

    <!-the default value of the sortIndicator < code > < code > property.

    It must be an IFactory for an IVisualElement.

    < p > This value is specified in a < code > < code > fx:Declaration block and can be overridden

    by a supporting statement < code > = "defaultSortIndicator" </postcode >

    in an MXML subclass. < /p >

    @langversion 3.0

    @playerversion flash 10

    @playerversion AIR 2.0

    @productversion flex 4.5

    ->

    < fx:Component id = "defaultSortIndicator" >

    < data s:Path = "M 3.5 7.0 L 0.0 0.0 7.0 0.0 L 3.5 7.0 L" implements = "spark.components.gridClasses.IGridVisualElement" >

    < fx:Script >

    <! [CDATA]

    Import spark.components.DataGrid;

    Import spark.components.Grid;

    /**

    * @private

    */

    public void prepareGridVisualElement(grid:Grid,_rowIndex:int,_columnIndex:int):void

    {

    const dataGrid:DataGrid = grid.dataGrid;

    If (! dataGrid)

    return;

    const color: uint = dataGrid.getStyle("symbolColor");

    arrowFill1.color = color;

    arrowFill2.color = color;

    }

    []] >

    < / fx:Script >

    < s:fill >

    < s:RadialGradient rotation = "90" focalPointRatio = "1" >

    <!---@private-->

    < s:GradientEntry id = "arrowFill1" color = "0" alpha = "0.6" / >

    <!---@private-->

    < s:GradientEntry id = "arrowFill2" color = "0" alpha = "0.8" / >

    < / s:RadialGradient >

    < / s:fill >

    < / s:Path >

    < / fx:Component >

    <!-displays the label of renderer property, which is the value of the column < code > < code > headerText.

    It must be an instance of a TextBase < code > < code > < code > < code > s:Label.

    < p > This Visual element is added to the < code > < code > labelDisplayGroup by of the rendering engine

    prepare() < code > < code > method.   Constraint of size/location specified by the labelDisplay

    define its location relative to the labelDisplayGroup. < /p >

    < p > This value is not specified with a < code > < code > fx:Declaration and can be overridden

    by a supporting statement < code > = "labelDisplay" < code >

    in an MXML subclass. < /p >

    @langversion 3.0

    @playerversion flash 10

    @playerversion AIR 2.0

    @productversion flex 4.5

    ->

    < s:Label id = "labelDisplay".

    Red left = "1" = "0" right = "0" top = low '0' = '0 '.

    textAlign = 'start '.

    fontWeight = "bold".

    verticalAlign = "middle".

    maxDisplayedLines = "1".

    showTruncationTip = "true" / >

    < / fx:Declarations >

    < fx:Script >

    <! [CDATA]

    Import net.awl.ismp.console.components.misc.FilterCriteria;

    Import net.awl.ismp.console.events.ColumnFilteredEvent;

    Import net.awl.ismp.console.events.ColumnResizedEvent;

    Import mx.events.ResizeEvent;

    Import spark.components.gridClasses.IGridVisualElement;

    Import mx.core.IVisualElement;

    Import spark.components.DataGrid;

    Import spark.components.GridColumnHeaderGroup;

    Import spark.components.gridClasses.GridColumn;

    Import spark.primitives.supportClasses.GraphicElement;

    variables and constants of color chrome

    DEFAULT_COLOR_VALUE:uint private static const is 0xCC;.

    DEFAULT_COLOR:uint private static const is 0xCCCCCC;.

    Private static const DEFAULT_SYMBOL_COLOR:uint = 0 x 000000;

    private static var colorTransform:ColorTransform = new ColorTransform();

    /**

    * @private

    */

    private void dispatchChangeEvent(type:String):void

    {

    If (hasEventListener (type))

    {

    dispatchEvent (new Event (type));

    }

    }

    protected function onColumnResize(event:ResizeEvent):void

    {

    dispatchEvent (new ColumnResizedEvent (ColumnResizedEvent.COLUMNRESIZED_EVT, this.width, this.column.columnInde x));

    }

    //----------------------------------

    maxDisplayedLines

    //----------------------------------

    private var _maxDisplayedLines:int = 1;

    [Bindable ("maxDisplayedLinesChanged")]

    [Inspectable (minValue = "-1")]

    /**

    This property value is used to initialize the

    * < code > < code > maxDisplayedLines property of this converter

    * < code > labelDisplay < code > element.

    *

    * @copy #maxDisplayedLines spark.components.supportClasses.TextBase

    *

    * @default 1

    *

    * @langversion 3.0

    * @playerversion flash 10

    * @playerversion AIR 1.5

    * @productversion flex 4.5

    */

    public function get maxDisplayedLines (): int

    {

    Return _maxDisplayedLines;

    }

    override the stateChanged(oldState:String,_newState:String,_recursive:Boolean):void function

    {

    trace ("status changed to:" + oldState + "to" + newState);

    super.stateChanged (oldState, newState, recursive);

    }

    /**

    * @private

    */

    public function set maxDisplayedLines(value:int):void

    {

    If (value == _maxDisplayedLines)

    return;

    _maxDisplayedLines = value;

    If (labelDisplay)

    labelDisplay.maxDisplayedLines = value;

    invalidateSize();

    invalidateDisplayList();

    dispatchChangeEvent ("maxDisplayedLinesChanged");

    }

    //----------------------------------

    sortIndicator

    //----------------------------------

    private var _sortIndicator:IFactory;

    private var sortIndicatorInstance:IVisualElement;

    [Bindable ("sortIndicatorChanged")]

    /**

    * A visual element that appears when the column is sorted.

    *

    * < p > the sortIndicator visual element is added to the < code > < code > sortIndicatorGroup

    * by this converter < code > < code > prepare() method.  Constraint of size/location

    * specified by the sortIndicator set its location relative to the sortIndicatorGroup. < /p >

    *

    * @default null

    *

    * @langversion 3.0

    * @playerversion flash 10

    * @playerversion AIR 1.5

    * @productversion flex 4.5

    */

    public function get sortIndicator (): IFactory

    {

    return (_sortIndicator)? _sortIndicator: defaultSortIndicator;

    }

    /**

    * @private

    */

    public function set sortIndicator(value:IFactory):void

    {

    trace ("setSortIndicator");

    If (_sortIndicator is value)

    return;

    _sortIndicator = value;

    If (sortIndicatorInstance)

    {

    sortIndicatorGroup.includeInLayout = false;

    sortIndicatorGroup.removeElement (sortIndicatorInstance);

    sortIndicatorInstance = null;

    }

    invalidateDisplayList();

    dispatchChangeEvent ("sortIndicatorChanged");

    }

    /**

    * @private

    * Create and add the sortIndicator to the sortIndicatorGroup and the

    * labelDisplay in the labelDisplayGroup.

    */

    override public function prepare(hasBeenRecycled:Boolean):void

    {

    trace ("ready!");

    Super.Prepare (hasBeenRecycled);

    If (labelDisplay & & labelDisplayGroup & & (labelDisplay.parent! = labelDisplayGroup))

    {

    labelDisplayGroup.removeAllElements ();

    labelDisplayGroup.addElement (labelDisplay);

    }

    trace (sortIndicator);

    trace ("sortIndicatorInstance:" + sortIndicatorInstance);

    column: GridColumn = const this.column;

    If (sortIndicator & & column & & column.grid & & column.grid.dataGrid & & column.grid.dataGrid.columnHeaderGroup)

    {

    const dataGrid:DataGrid = column.grid.dataGrid;

    const columnHeaderGroup:GridColumnHeaderGroup = dataGrid.columnHeaderGroup;

    If (columnHeaderGroup.isSortIndicatorVisible (column.columnIndex))

    {

    If (! sortIndicatorInstance)

    {

    sortIndicatorInstance = sortIndicator.newInstance ();

    sortIndicatorGroup.addElement (sortIndicatorInstance);

    chromeColorChanged = true;

    invalidateDisplayList();

    }

    Initialize the sortIndicator

    sortIndicatorInstance.visible = true;

    const gridVisualElement:IGridVisualElement = sortIndicatorInstance as IGridVisualElement;

    If (gridVisualElement)

    gridVisualElement.prepareGridVisualElement (column.grid,-1, column.columnIndex);

    sortIndicatorGroup.includeInLayout = true;

    sortIndicatorGroup.scaleY = (column.sortDescending)? 1:-1;

    }

    on the other

    {

    If (sortIndicatorInstance)

    {

    sortIndicatorGroup.removeElement (sortIndicatorInstance);

    sortIndicatorGroup.includeInLayout = false;

    sortIndicatorInstance = null;

    }

    }

    }

    }

    private var chromeColorChanged:Boolean = false;

    private var colorized: Boolean = false;

    /**

    * @private

    * Apply the chromeColor style.

    */

    override the updateDisplayList(unscaledWidth:Number,_unscaledHeight:Number):void function

    {

    trace ("update list display");

    Apply the color chrome

    If (chromeColorChanged)

    {

    var chromeColor:uint = value ("chromeColor");

    If (chromeColor! = DEFAULT_COLOR | colorized)

    {

    colorTransform.redOffset = ((chromeColor & (0xFF << 16)) > > 16)-DEFAULT_COLOR_VALUE;

    colorTransform.greenOffset = ((chromeColor & (0xFF << 8)) > > 8)-DEFAULT_COLOR_VALUE;

    colorTransform.blueOffset = (chromeColor & 0xFF) - DEFAULT_COLOR_VALUE;

    colorTransform.alphaMultiplier = alpha;

    transform.colorTransform = colorTransform;

    var exclusions: Array = [labelDisplay, sortIndicatorInstance];

    Apply reverse colorization exclusions

    If (exclusions & & exclusions.length > 0)

    {

    colorTransform.redOffset = - colorTransform.redOffset;

    colorTransform.greenOffset = - colorTransform.greenOffset;

    colorTransform.blueOffset = - colorTransform.blueOffset;

    for (var i: int = 0; i < exclusions.length; i ++)

    {

    var exclusionObject:Object = exclusions [i];

    If (exclusionObject & &)

    (exclusionObject is DisplayObject |)

    exclusionObject is GraphicElement))

    {

    colorTransform.alphaMultiplier = exclusionObject.alpha;

    exclusionObject.transform.colorTransform = colorTransform;

    }

    }

    }

    colorized = true;

    }

    chromeColorChanged = false;

    }

    super.updateDisplayList (unscaledWidth, unscaledHeight);

    }

    /**

    * @private

    */

    override public function styleChanged(styleProp:String):void

    {

    var allStyles:Boolean =! styleProp | styleProp == "styleName";

    super.styleChanged (styleProp);

    If (allStyles | styleProp == "chromeColor")

    {

    chromeColorChanged = true;

    invalidateDisplayList();

    }

    }

    protected function managefilterField(event:MouseEvent):void

    {

    trace ("double click on sortIndicator:" + this.sortIndicatorInstance);

    this.filterInput.visible =! this.filterInput.visible;

    this.filterInput.includeInLayout = this.filterInput.visible;

    this.filterSpacer.visible = this.filterInput.visible;

    this.filterSpacer.includeInLayout = this.filterInput.visible;

    if(!this.filterInput.visible)

    {

    this.filterInput.text ="";

    dispatchEvent (new ColumnFilteredEvent (ColumnFilteredEvent.COLUMNFILTERED_EVT, new FilterCriteria (this.column.dataField, this.filterInput.text)));

    }

    this.filterInput.setStyle ("borderColor", 0xFF6319);

    this.filterInput.setStyle ("focusColor", 0xFF6319);

    () this.filterInput.setStyle

    }

    protected function onTextInputSelection(event:MouseEvent):void

    {

    Event.stopImmediatePropagation;

    this.filterInput.setStyle ("borderColor", 0xFF6319);

    this.filterInput.setStyle ("focusColor", 0xFF6319);

    }

    protected function onKeyUp(event:KeyboardEvent):void

    {

    if(Event.charCode==Keyboard.Enter)

    {

    internship. Focus = null;

    }

    }

    protected function onFocusOut(event:FocusEvent):void

    {

    this.filterInput.setStyle ("borderColor", 0x00ff00);

    this.filterInput.setStyle ("focusColor", 0x70B2EE);

    dispatchEvent (new ColumnFilteredEvent (ColumnFilteredEvent.COLUMNFILTERED_EVT, new FilterCriteria (this.column.dataField, this.filterInput.text)));

    }

    []] >

    < / fx:Script >

    < s: states >

    < name s: State = "normal" / >

    < name s: State = "flat" / >

    < name s: State = "low" / >

    < / s: states >

    <!-layer 1: shadow->

    <!---@private-->

    < s:Rect id = "shadow" left = "-1" right = "-1" high = low '-1' = '-1' radiusX = "2" >

    < s:fill >

    < s:LinearGradient rotation = "90" >

    < s:GradientEntry color = "0x000000".

    Color.Down = "0xFFFFFF"

    Alpha = "0.01".

    Alpha. Down = "0" / > "

    < s:GradientEntry color = "0x000000".

    Color.Down = "0xFFFFFF"

    Alpha = "0.07"

    Alpha. Down = "0.5" / > "

    < / s:LinearGradient >

    < / s:fill >

    < / s:Rect >

    <!-layer 2: fill->

    <!---@private-->

    < s:Rect id = "fill" left = "0" right = "0" top = low "0" = "0" >

    < s:fill >

    < s:LinearGradient rotation = "90" >

    < s:GradientEntry color = "0xFFFFFF".

    Color.hovered = "0xBBBDBD"

    Color.Down = "0xAAAAAA"

    Alpha = "0.85" / >

    < s:GradientEntry color = "0xD8D8D8".

    Color.hovered = "0x9FA0A1"

    Color.Down = '0 x 929496'

    Alpha = "0.85" / >

    < / s:LinearGradient >

    < / s:fill >

    < / s:Rect >

    <!-layer 3: filling lowlight->

    <!---@private-->

    < s:Rect id = "lowlight" left = "0" right = "0" top = low "0" = "0" >

    < s:fill >

    < s:LinearGradient rotation '270' = >

    < s:GradientEntry color = "0x000000" ratio = "0,0" alpha = "0,0627" / >

    < s:GradientEntry color = "0x000000" ratio = alpha '0.48' = "0,0099" / >

    < s:GradientEntry color = "0x000000" ratio = alpha "0.48001" = "0" / >

    < / s:LinearGradient >

    < / s:fill >

    < / s:Rect >

    <!-layer 4: highlight of fill->

    <!---@private-->

    < s:Rect id = "highlight" left = "0" right = "0" top = low "0" = "0" >

    < s:fill >

    < s:LinearGradient rotation = "90" >

    < s:GradientEntry color = "0xFFFFFF".

    ratio = "0.0".

    Alpha = "0.33".

    Alpha.hovered = "0.22"

    Alpha. Down = "0.12" / >

    < s:GradientEntry color = "0xFFFFFF".

    ratio = '0.48 '.

    Alpha = "0.33".

    Alpha.hovered = "0.22"

    Alpha. Down = "0.12" / > "

    < s:GradientEntry color = "0xFFFFFF".

    ratio = "0.48001."

    Alpha = "0" / >

    < / s:LinearGradient >

    < / s:fill >

    < / s:Rect >

    <!-layer 5: race to highlight (all States except down)->

    <!---@private-->

    < s:Rect id = "highlightStroke" left = "0" right = "0" top = low '0' = '0' excludeFrom 'low' = >

    < s:stroke >

    < s:LinearGradientStroke rotation = "90" weight = "1" >

    < s:GradientEntry color = "0xFFFFFF" alpha.hovered = "0.22" / > "

    < s:GradientEntry color = "0xD8D8D8" alpha.hovered = "0.22" / > "

    < / s:LinearGradientStroke >

    < / s:stroke >

    < / s:Rect >

    <!-layer 6: highlight of the stroke (to the low State only)->

    <!---@private-->

    < s:Rect id = "hldownstroke1" left = "0" right = "0" top = low "0" = "0" includeIn = "bottom" >

    < s:stroke >

    < s:LinearGradientStroke rotation = "90" weight = "1" >

    < s:GradientEntry color = "0x000000" alpha = "0.25" ratio = "0,0" / >

    < s:GradientEntry color = "0x000000" alpha = "0.25" ratio = "0.001" / >

    < s:GradientEntry color = "0x000000" alpha = "0.07" ratio = "0,0011" / >

    < s:GradientEntry color = "0x000000" alpha = "0.07" ratio = "0,965" / >

    < s:GradientEntry color = "0x000000" alpha = "0.00" ratio = "0.9651" / >

    < / s:LinearGradientStroke >

    < / s:stroke >

    < / s:Rect >

    <!---@private-->

    < s:Rect id = "hldownstroke2" left = "1" right = "1" top down = '1' = '1' includeIn = "bottom" >

    < s:stroke >

    < s:LinearGradientStroke rotation = "90" weight = "1" >

    < s:GradientEntry color = "0x000000" alpha = "0.09" ratio = "0,0" / >

    < s:GradientEntry color = "0x000000" alpha = "0.00" ratio = "0.0001" / >

    < / s:LinearGradientStroke >

    < / s:stroke >

    < / s:Rect >

    <!-< s:Rect id = "fill" left = "0" right = "0" top = low "0" = "0" >

    < s:fill >

    < s:LinearGradient rotation = "90" >

    "< s:GradientEntry color.normal"0xf9f9f9"color.hovered =" = 0xfcfdfa ".

    Color.Down = "0xdceac2" alpha = "0.85" / > "

    "< s:GradientEntry color.normal"0xeaeaea"color.hovered =" = 0xdceac2 ".

    Color.Down = "0xd2e1b5" alpha = "0.85" / > "

    < / s:LinearGradient >

    < / s:fill >

    < / s:Rect >->

    <!-< right '7' = left s:VGroup = '7' high low = '5' = '5' gap = "6" verticalAlign = "middle" >

    < s:TextInput width = "100%" / >

    < s:HGroup width = "100%" >

    < s:Group id = "labelDisplayGroup" width = "100%" / >

    < s:Group id = includeInLayout = "false" "sortIndicatorGroup" / >

    < / s:HGroup >

    < / s:VGroup >->

    < s:VGroup verticalAlign = "middle" left = "7" = "5" top right = '7' low gap '5' = '2' = >

    "< s:TextInput id ="filterInput"width ="100% "visible ="false"includeInLayout = 'false' keyUp =" onKeyUp (event) "Focusout/focusouthandler() =" onFocusOut (event) "click ="onTextInputSelection (event)"/ >

    < s:Spacer id = "filterSpacer" visible = "false" includeInLayout = "false" height = "5" / >

    < s:HGroup width = "100%" height = "100%" verticalAlign = "middle" >

    < s:Group id = "labelDisplayGroup" width = "100%" / >

    < s:Group id = includeInLayout = "false" "sortIndicatorGroup" / >

    < / s:HGroup >

    < / s:VGroup >

    < / s:GridItemRenderer >

    You can use 'alt' or 'Ctrl' click and just check on the event to see if one of these is 'true '.

  • AbstractTreeModel

    I was told once in fishing forums it's a bad habit to call #. updateUI() #. revalidate() using abstractTableModel.

    I pulled treemodelevents however the JTree object does not seem to respond to these events without back updateUI and revalidate? Why is this?


    package Swing;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.Enumeration;
    import java.util.Observable;
    import javax.swing.*;
    import javax.swing.event.ListDataListener;
    import javax.swing.event.ListSelectionListener;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.table.*;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreeNode;
    import javax.swing.tree.TreePath;
    //import com.sun.java.swing.tree.*;
    //import com.sun.java.swing.event.*;
    import java.util.*;
    
    
    
    class TreeModelTest {
    
        public static void main(String[] args) {
            new GUI().createGui();
        }
    }
    
    class GUI  {
        private JTree tree;
        private PeopleTreeModel peopleModel = new PeopleTreeModel();
    
    
        public void createGui() {
            tree = new JTree(peopleModel);
            JPanel pane = new JPanel(new BorderLayout());
            pane.add(new JScrollPane(tree), BorderLayout.CENTER);
            pane.add(getButtonPanel(), BorderLayout.SOUTH);
    
            JFrame f = new JFrame("Abstract JTree Example");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(pane);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    
        }
    
        public JPanel getButtonPanel(){
            JPanel buttonPanel = new JPanel();
    
            JButton addPersonButton = new JButton("Add Person");
            addPersonButton.addActionListener(new ActionListener() {
    
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Adding Person");
                    peopleModel.addPerson(new Person("New Person"));
                    tree.updateUI();
                    tree.revalidate();
                }
            });
    
            JButton removePersonButton = new JButton("Remove Person");
            removePersonButton.addActionListener(new ActionListener() {
    
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Remove Person");
                    peopleModel.removePerson(0);
                    tree.updateUI();
                    tree.revalidate();
                }
            });
    
            JButton selectPersonButton = new JButton("Select Person");
            selectPersonButton.addActionListener(new ActionListener() {
    
                public void actionPerformed(ActionEvent e) {
                    System.out.println("Select Person");
                }
            });
    
            buttonPanel.add(addPersonButton);
            buttonPanel.add(removePersonButton);
            buttonPanel.add(selectPersonButton);
            return buttonPanel;
        }
    }
    
    
    
    
    
    
    
    class PeopleTreeModel extends AbstractTreeModel  implements TreeModel {
    
        private ArrayList<Person> peopleArray = new ArrayList<Person>();
    
    
        public PeopleTreeModel() {
            super();
            peopleArray.add(new Person("Chris"));
            peopleArray.add(new Person("Hary"));
            peopleArray.add(new Person("Boris"));
            peopleArray.add(new Person("lucy"));
            peopleArray.add(new Person("char"));
            this.print();
        }
    
        public void addPerson(Person person){
            peopleArray.add(person);
            //here I want to fire tree event??
            Object[] path = {"people",person.getName()};
            this.fireTreeNodesInserted(new TreeModelEvent(person.getName(),path));
    
    
        }
    
        public void removePerson(int index){
            if(index<peopleArray.size()){
                peopleArray.remove(index);
                Object[] path = {"people",this.peopleArray.get(index).getName()};
                this.fireTreeNodesInserted(new TreeModelEvent(this.peopleArray.get(index).getName(),path));
                
            }
        }
    
    
    
        public ArrayList<Person> getPeopleArray() {
            return peopleArray;
        }
    
        public void setPeopleArray(ArrayList<Person> people) {
            this.peopleArray = people;
        }
    
        public void print() {
            System.out.println("\nPrinting People Array");
            for (int i = 0; i < peopleArray.size(); i++) {
                System.out.println(peopleArray.get(i).toString());
            }
        }
    
        public Object getRoot() {
            return "people";
        }
    
        public Object getChild(Object parent, int index) {
            if(parent.toString().equals("people")){
                return this.peopleArray.get(index);
            }else{
                return null;
            }
        }
    
        public int getChildCount(Object parent) {
            if(parent.toString().equals("people")){
                System.out.println("Returning size "+this.peopleArray.size());
                return this.peopleArray.size();
            }else{
                return 0;
            }
        }
    
        public boolean isLeaf(Object node) {
            if(node.toString().equals("people")){
                return false;
            }else{
                return true;
            }
        }
    
        public void valueForPathChanged(TreePath path, Object newValue) {
            System.out.println(path + ", "+ newValue);
        }
    
        public int getIndexOfChild(Object parent, Object child) {
            return this.peopleArray.indexOf(child);
        }
    }
    
    
    
    
    
    class Person {
    
        private String name;
    
        public Person() {
            this("Chris");
        }
    
        public Person(String name) {
            super();
            this.name = name;
        }
    
        @Override
        public String toString() {
            return name;
        }
    
        public String getName() {
            return name;
        }
    
    
        public void setName(String name) {
            this.name = name;
        }
    
    }
    
    // This class takes care of the event listener lists required by TreeModel.
    // It also adds "fire" methods that call the methods in TreeModelListener.
    // Look in TreeModelSupport for all of the pertinent code.
    abstract class AbstractTreeModel extends TreeModelSupport implements TreeModel {
    }
    
    
    class TreeModelSupport {
       private Vector vector = new Vector();
    
       public void addTreeModelListener( TreeModelListener listener ) {
          if ( listener != null && !vector.contains( listener ) ) {
             vector.addElement( listener );
          }
       }
    
       public void removeTreeModelListener( TreeModelListener listener ) {
          if ( listener != null ) {
             vector.removeElement( listener );
          }
       }
    
       public void fireTreeNodesChanged( TreeModelEvent e ) {
          Enumeration listeners = vector.elements();
          while ( listeners.hasMoreElements() ) {
             TreeModelListener listener = (TreeModelListener)listeners.nextElement();
             listener.treeNodesChanged( e );
          }
       }
    
       public void fireTreeNodesInserted( TreeModelEvent e ) {
          Enumeration listeners = vector.elements();
          while ( listeners.hasMoreElements() ) {
             TreeModelListener listener = (TreeModelListener)listeners.nextElement();
             listener.treeNodesInserted( e );
          }
       }
    
       public void fireTreeNodesRemoved( TreeModelEvent e ) {
          Enumeration listeners = vector.elements();
          while ( listeners.hasMoreElements() ) {
             TreeModelListener listener = (TreeModelListener)listeners.nextElement();
             listener.treeNodesRemoved( e );
          }
       }
    
       public void fireTreeStructureChanged( TreeModelEvent e ) {
          Enumeration listeners = vector.elements();
          while ( listeners.hasMoreElements() ) {
             TreeModelListener listener = (TreeModelListener)listeners.nextElement();
             listener.treeStructureChanged( e );
          }
       }
    }

    847102 wrote:
    After a bit more research, it does not work because JTree does not implement TreeModelListener. That's why you add manually the listener IE

    This is not correct. JTree use an inner class as TreeModelListener and it works correctly for any model of tree.

    The problem is that you do not send the correct events:
    -to insert, you create a node changed event but calls the inserted node. Also the source would be better than the model of the tree.
    -to remove them, do you the same (which will obviously not work). Also it will fail with an IndexOutOfBoundsException if you delete the last one.

    I suggest you read the Javadoc for TreeModelEvent, especially the various manufacturers.

  • Spark is the substitution of the MX tab order... Probably something simple.

    Hello

    I have a large project with some legacy code that uses so a hodgepodge of spark and mx components.

    It's very well for the most part, they work side by side with only a few small problems as to remember the difference between removeChild and Microsoft.SqlServer.Management.Sdk.Sfc.ISfcCollection.RemoveElement etc..

    BUT...

    I have a complex, dynamically generated form that I should be able to tab between fields of integrated mx and time subject than I tab, no matter what I do, need me _OUT_ of the generated complex shape and plonks me in the first spark control there - usually the home button at the top left.

    This, I hasten to add, is really not a good user experience!

    I tried all the obvious things (tab activation, tab, etc.) but the spark just seems to replace everything, like say "why this dirty _old_ mx component would focus? he don't know even what to do with it? »

    So, please, does anyone have helpful advice on the integration of the mx components in the hierarchy of the development of tab?

    Thank you

    G

    hasFocusableChildren = true...

  • Leak memory causing module DataGrid column

    Hi all

    I have problems with a column of the DataGrid preventing a module to be communicated properly. I can't imagine that this is the intended behavior.

    Using this simple test case, a WindowedApplication and a mx:Module I wonder if anyone can reproduce this problem. The problem disappears if you simply comment the GridColumn Instance.

    Can anyone offer advice?

    Thank you very much

    James

    DataGridTest.mxml

    <?xml version="1.0" encoding="utf-8"?>
    <s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009" 
                           xmlns:s="library://ns.adobe.com/flex/spark" 
                           xmlns:mx="library://ns.adobe.com/flex/mx">
        <fx:Script>
            <![CDATA[
                import mx.core.IVisualElement;
                import mx.events.ModuleEvent;
                import mx.modules.IModuleInfo;
                import mx.modules.ModuleManager;
    
                private var assetModule:IModuleInfo;
                protected function load_clickHandler(event:MouseEvent):void
                {
                    assetModule = ModuleManager.getModule('DataGridTestModule.swf');
                    assetModule.addEventListener("ready", getModuleInstance);
                    assetModule.load();
                }
                public function getModuleInstance(event:ModuleEvent):void 
                {
                    var sm:DisplayObject = assetModule.factory.create() as DisplayObject;
                    sm.addEventListener("close", closeModule);
                    contentHolder.addElement(sm as IVisualElement);
                }
                private function closeModule(event:Event):void 
                {
                    event.target.removeEventListener("close", closeModule);
                    contentHolder.removeElement(event.target as IVisualElement);
                    assetModule.unload();
                    assetModule = null;
                }
            ]]>
        </fx:Script>
        <s:VGroup width="100%" height="100%">
            <s:HGroup >
                <s:Button id="load" label="Load" click="load_clickHandler(event)"/>
            </s:HGroup>
            <s:BorderContainer id="contentHolder" width="100%" height="100%"/>
        </s:VGroup>
    </s:WindowedApplication>
    

    DataGridTestModule.mxml

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Module xmlns:fx="http://ns.adobe.com/mxml/2009" 
                          xmlns:s="library://ns.adobe.com/flex/spark" 
                          xmlns:mx="library://ns.adobe.com/flex/mx" 
                          layout="absolute" xmlns:components="components.*">
        <fx:Script>
            <![CDATA[
                protected function close_clickHandler(event:MouseEvent):void
                {
                    dispatchEvent(new Event('close', true, false))
                }
            ]]>
        </fx:Script>
        <s:BorderContainer id="contacts"
                           width="100%" height="100%"
                           backgroundAlpha="0"
                           borderVisible="false">
            <s:layout>
                <s:VerticalLayout/>
            </s:layout>
            <s:Button id="close" label="Close" click="close_clickHandler(event)"/> 
            <s:DataGrid id="queries" >
                <s:columns>
                    <s:ArrayList>
                        <s:GridColumn/> <!-- Comment out this GridColumn instance to see the leak disappear -->
                    </s:ArrayList>
                </s:columns>
            </s:DataGrid>
        </s:BorderContainer>
    </mx:Module>
    

    Just declare a type varialbe GridColumn in the main application somewhere (and import GridColumn)

  • Exception of null focusManager scroller

    Are currently working on a project that needs to take one component & pop out of it is parent of the top-level application. I use a spark textAera. Initially when the textArea component is "not broken out on" the textAera works very well. However, when it is popped and a user focused then in on the text box a null object reference are thrown by the method of class focusInHandler Scroller.

    To remove and eject the component code that I use is currently:

    IVisualElementContainer (resizeComponent.parent) .removeElement (resizeComponent);

    FlexGlobals.topLevelApplication.systemManager.addChild (resizeComponent);

    where resizeComponent is the component wants to get out.

    Exception occurs when we focus, in Scroller.as:

    override the focusInHandler(event:FocusEvent):void function

    {

    super.focusInHandler (event);

    When get us the focus, make sure that the item is visible

    If (viewport & & ensureElementIsVisibleForSoftKeyboard)

    {

    var elt:IVisualElement = focusManager.getFocus (as IVisualElement); object null exception thrown here

    lastFocusedElement = elt;

    }

    }

    What I am doing wrong?

    Thank you

    Kevin

    Kevin,

    The problem is that your popup does not implement the IFocusManagerContainer interface.

    The IFocusManagerContainer implementation allows the system to assign a focus Manager to the pop-up, and this error disappears.

    Kind regards

    Haim Arazy

Maybe you are looking for

  • New device failed, HD Audio after installing updates to Win 8.1

    Hello. I have installed recent updates from Toshiba, exactly: * 06/02/14 display nVidia Windows 8.1-64 Bit 9.18.13.2660 World Wide disk *.* 06/02/14 display driver Intel Windows 8.1 - 64 Bit 10.18.10.3308 World Wide *.* 06/05/14 gas station Toshiba W

  • Move the files ipa

    Need help to understand the 'Mobile Applications' folder and files *.ipa. I'm about to upgrade my this SSD to a larger. According to Samsung SSD primary must be 20% vacuum, which is a big problem, to be able to clone the drive. Is there a way to temp

  • By default the rate of execution 15 Hz of Communication send loop

    Hi NIVS experts! The link understand engine VS, the default implementation of communication loop rate is set to 15 Hz.  I've found a way to change this default in VS.  As this Communication send loop transmits the values of layer VeriStand bridge, wh

  • In response to the commandKind - bench test/Labview UI event

    Hey guys Hey.  I have control over a UI Labview/Test Stand I want to change the attributes of function if the user is logged on or loading a sequence file.  How can I create an event that fires when the user logs in or out or a sequence is charged or

  • Windows Update drastically reduces the noise on the venue pro 8

    The last windows update has audio output so low on my venue 8 pro I csn barely hear the keyboard. All the other audio is too low, and I set it all up as high as possible. I have no confidence that Microsoft will resolve this problem. Maybe Dell can l