Dispatching events between different classes

Im trying to dispatch and event from an XML class.
dispatchEvent(new Event (XMLClass.INDEX_CHANGED));
and catch it in the display class
import AS.XMLClass;
private var _xml  = new XMLClass();
_xml.addEventListener(XMLClass.XML_LOADED, swapImage);
I know that im missing something because the application works
and the function runs but its not dispatching the event the event
or maybe it's not catching the event in the display class, even though everything else is working
and im not gettin' any errors.

that's exactly what i did.
i have 3 classes
AS.XMLClass
AS.ControlClass
AS.DisplayClass
It's like a slideshow thing.
I have a button on stage thats connected to the control class and every time you press it
it changes the index of the image in the xmlclass and everytime that the index is changed the xmlclass needs to
dispatch and event that the index has changed and the display class is going to catch the event and change the image
everything is working except the xmlclass dispatch event or the displayclass catch event
XMLCLASS
public static const INDEX_CHANGED:String = "indexChanged";
private function dataLoaded(event:Event):void{
            trace("xml file is loaded");
            data = new XML(loader.data);
            dispatchEvent(new Event(XMLClass.XML_LOADED));
            totalItems = data.images.photo.length();
            setCurrentIndex(currentIndex);
CONTROL CLASS
import AS.XMLClass;
private var _xml = new XMLClass();
public function leftButtonClicked(){
            _xml.setCurrentIndex(_xml.currentIndex = _xml.currentIndex - 1);
        public function rightButtonClicked(){
            _xml.setCurrentIndex(_xml.currentIndex = _xml.currentIndex + 1);
DISPLAY CLASS
import AS.XMLClass;
private var _xml  = new XMLClass();
_xml.addEventListener(XMLClass.XML_LOADED, swapImage);
public function swapImage(event:Event){
            trace("working....");

Similar Messages

  • Dispatching event between sessions

    Hey guys,
    I am pretty much a new bee at flex and action scripting. I
    am creating a web app, and one of the requirements is that it has a
    messaging system. Not chat session, but something similar to email.
    use case:
    user A and B are logged at two different location. But are
    unaware if other is logged in or not. User A would like to send A
    message to B, so a types up a message and sends it, the message is
    saved in the DB, and User A dispatches an event. If B is logged in
    then its is listening for an event, and hence will know there is a
    message waiting. Else when B logs in, it adds an eventListner for
    any message, and at the same time fetches all unread messages from
    the DB.
    Any idea how i can dispatch and listen for event across
    sessions?
    I know the other way would be to dispatch an event every few
    mins that Query's DB for any unread messages, but one I don't want
    to do a "busy waiting" on it, secondly if thats the only way how
    can I setup an event that is dispatched on clock tick?
    Thanks for your help.
    Jaysheel
    p.s I am using RPC and Coldfusion 8 to interact with my MYSQL
    5 DB

    The use case you've defined can easily be addressed by using
    Timer class that ticks an event after a given timespan and sendinga
    HTTPService request to the server on the tick.
    For more involved apps BlazeDS has built-in messaging
    mechanism:
    http://www.adobe.com/devnet/flex/articles/data_entry.html
    http://www.adobe.com/devnet/flex/articles/yahoomaps_collaboration.html
    ATTA

  • Handling a value between different classes

    Hi there!
    Can anyone tell me how to handle this problem?
    A value is received at a certain event, that value then needs to be stored somewhere so that two other Classes can access it and then use it.
    I hope someone can point me in the right direction.. Some outline code would help if possible?
    Thanks :)

    okie dokie:
    Comms Class handles received Packet events, if it receives a certain packet with a JID (Jabber Identifier) it then needs to store that somewhere else.
    //Some outline code
    class Comms {
    public receivedPacket( PacketEvent pe ) {
         JID getJID = pe.packetEvent;
    }ChatWindow handles simple chat to the sender of the JID so it needs to get that received JID somehow
    //Some guideline code
    class ChatWindow {
    sendPacket.add( JID );
    }EditorChat handles simple shared editing so it too needs that JID to send a packet using that JID
    //Some guideline code
    class EditorChat {
    sendPacket.add( JID );
    }My idea for doing this JID handling is completely shot now, but everything else works (thankfully)!
    Is that any good? I want to understand how a receivedPacket that contains a JID (which I've already been able to extract can then be stored somewhere else so the two classes (ChatWindow and EditorChat) can use it..?
    thanks :)

  • Sharing files and iCal events between different users (accounts) on one Mac

    Hi,
    I have a new iMac with Leopard. I have two accounts on this machine: one for myself and one for my girlfriend. I want to share files with her such as iPhoto events (so I don't have to import photos twice), iCal events (so I don't have to send her an email to synch our calendars), music from iTunes and other files.
    Does anyone know how to easily do this? I have tried the drop folder for sharing but it only appears across a network if I am logged in and won't transfer to different users.
    Daniel

    thanks, zevoneer. apparently, I gave up too early in my own search. I'm trying it now - the copy process is taking some time. Well, I had hoped to narrow the access down to only one other account but at least this should provide the access that is needed.

  • Is there a way to dispatch or bubble events between two pop-up windows?

    Hi. I was wondering if there is a way to dispatch custom
    events between two or more pop-up windows created using the
    PopUpManager?
    I understand how to pass an event from one pop-up window to
    the main application (or FrontController) by dispatching the event
    from Application.application under Cairngorm 2.0.
    However, as I understand it, that will only bubble the event
    through the Application chain of visual controls and not to the
    other pop-up windows created using the PopUpManager.
    I tried dispatching the event directly from the pop-up window
    itself, but the other pop-ups still does not seem to receive the
    event.
    It would be nice to be able to do this so that each non-modal
    pop-up can have some awareness with each other.
    Thank you very much in advance.

    If you have just 2 pop-ups you can have them each do a
    addEventListener on the other, listening for the event (custom or
    otherwise).
    If you have an unpredicatable number, then you devise
    something else. Suppose you have 3 pop-ups, p1, p2, and p3. Let's
    say you also have 1 custom event, E1. Any of those pop-ups is
    capable of dispatching an E1 event and you want all of them to
    receive it.
    Create a class that extends EventDispatcher and instantiate
    an object of that class. Each pop-up "registers" with that class,
    something like:
    controller.addEventListener( "E1", handler ); where handler
    is a function in the pop-up.
    When a pop-up wants to dispatch an E1 event, it does it
    through the controller: controller.dispatchEvent( new E1(data) );
    This will automatically dispatch that event to all the
    pop-ups, including the one that dispatched the event. So a pop-up
    will have to examine the event to see if it sent it and perhaps
    ignore it.

  • Can I share Attributes/Variables between 2 different Class Driver Sessions?

    I am designing a Simulator of Instrumentation following these steps:
    1) re-programming, re-compiling, and re-building the DLLs from the advanced class simulation drivers included in IVI Driver Toolset 2.0 using LabWindows/CVI 7.0;
    2) then i create a VI in LabVIEW 7.0 which calls an IVI Class Driver obtaining the desired simulated output data.
    My problem is that I need to share variables between different DLLs in LabVIEW.
    I want to simulate a circuit which consists of a battery and a resistor. I've got 2 instruments: a DC Power Supply and a Digital Multimeter.
    The DC Power Supply acts as the battery providing a certain voltage level, and the Multimeter measures the Voltage and the Current in the resistor.
    I've designed a VI in LabVIEW which uses 2 different sessions: one which calls the class driver IviDCPwr, and the other one which calls IviDmm.
    I wish to be able to access the attributes from "nisDCPwr.c" in the file "nisDmm.c".
    For example, to write a line like this:
    Ivi_GetAttributeViReal64 (ViSession vi, ViConstString channelName, NISDCPWR_ATTR_MEASUREMENT_BASEV, 0, &reading));
    inside the source code "nisDmm.c" of the advanced class simulation driver.
    The problem is that the only ViSession accessible from nisDmm is the handle from the Digital Multimeter, but not from DC Power Supply.
    Would this be possible? Is it "legal"?
    I've tried another approach through the declaration of external variables, but unfortunately I get a run-time error in LabVIEW.
    The only solution I've found is using auxiliary files going between, through the functions included in the Low Level I/O Library .
    Nevertheless, the solution proposed above would result much more convenient, faster and safer in my application.
    I hope everyone has understood my question, and anyone can help.
    THANK YOU VERY MUCH FOR YOUR TIME!!!

    Doesn't anyone have an answer?
    Or any proposal?
    Or even a clue?
    THANKS!

  • Comparison insertion/search time between different Collection class

    Hi,
    Does someone know where I can find a clear an complete comparison between different JAVA class which implements interface Collection?
    I want to compare:
    - elements insertion time
    - elements search/removal time
    Thank you very much in advance
    Diego

    from wikipedia: Its purpose is to characterize a function's behavior for very large (or very small) inputs in a simple but rigorous way that enables comparison to other functions.
    meaning if I ask how quick an algorithm is you might say it completes in 10 seconds but the next time you run it it might take 8 seconds. It kind of depends on what else your computer is doing/ how fast your computer is or how much data you are putting through ie if the puter has little memory it might need to use virtual memory which will have an effect on your performance.
    Big O notation identifies how much work has to be carried out. The easiest example is a simple search of an array:
    for (int i = 0; i < array.length; i++) {
      if (array[i] == "weijewr") {
        return i;
    }Where n represents a number of elements:
    This takes O(n) (big Oh of N) as potentially you need to look at each element.
    if you were to write a standard bubble sort it would be O(n2) as potentially you need to iterate the array once for each element.

  • Event-Handling  Between 2 Classes

    Trying to learn where did I make a mistake!
    Here is a very simple sample code:
    2 classes (each has 1 (awt-style)Panel & 1 (awt-style) Button. By clicking on one of the buttons how do I change the Background (color) of the Panel in the other class?
    //***********Sample Code **********************
    import java.awt.*;
    import java.awt.event.*;
    //=====================================================
    public class App extends Frame
    Panel_1 ap1; //ap1 --> additional panel #1
    Panel_2 ap2;
    public App()
    setLayout(null);
    setBounds(100,100,300,200);
    setBackground(Color.yellow);
    //re: Panel_1
    //=============
    ap1=new Panel_1();
    add(ap1);
    //re: Panel_2
    //===========
    ap2=new Panel_2();
    add(ap2);
    public static void main(String[] args)
    App app=new App();
    app.setVisible(true);
    //==============================================================
    class Panel_1 extends Panel implements ActionListener
    Panel_2 p2;
    Button ap1b=new Button();
    Panel_1()
    setBounds(50,120,100,50);
    setBackground(Color.green);
    ap1b.setBackground(Color.red);
    ap1b.addActionListener(p2);
    add(ap1b);
    public void actionPerformed(ActionEvent ae)
    if (ae.getSource()==p2.ap2b)
    System.out.println("Test Panel 1");
    //=================================
    class Panel_2 extends Panel implements ActionListener
    Panel_1 p1;
    Button ap2b=new Button();
    Panel_2()
    setBounds(50,30,200,50);
    setBackground(Color.orange);
    ap2b.setBackground(Color.red);
    ap2b.addActionListener(p1);
    add(ap2b);
    public void actionPerformed(ActionEvent ae)
    if (ae.getSource()==p1.ap1b)
    System.out.println("Test Panel 2");
    }

    There are several ways to do this. Without going into all of them, let's narrow them down by thinking in terms of design. Why should the panels know anything about each other? Each panel is its own deal. The component which has both of the panels should be the one listening to the buttons.
    Really there is no reason to have separate classes for the panels, but if you must, then write a listener as an inner class of the frame class, then pass that listener to the constructor of each panel as you instantiate it. Then you can have the listener work with both panels directly.
    Drake

  • Broadcast events between classes (objects)

    Hello,
    I'm can't figure out how to broadcast an event to another
    class.
    In actionscript 2 I created 2 classes. The first class called
    the second class to load a file from an url. When the file was
    loaded I used dispatchEvent({type: "fileLoaded", target: this,
    filename: sFilename})
    In the first I simply wrote addEventListener("fileLoaded",
    handleFile)
    But with AS3 this no longer works.
    Can anyone tell me how to accomplish this? Because I can't
    find a clear example and I don't know how to do this.

    In the defintion of your custom event I miss the isEnabled
    part (don't know if that has anything to do with the issue though).
    Below a custom event that works for me
    package Components {
    import flash.events.Event;
    public class ZoomEvent extends Event
    public var isEnabled:Boolean;
    public static const ZOOM:String = 'zoom';
    public var vertical:Boolean = true;
    public var minvalue:Number = 0;
    public var maxvalue:Number = 0;
    public var zoomfactor:Number = 0;
    public function ZoomEvent(type:String,
    isEnabled:Boolean=false) {
    super(type);
    this.isEnabled = isEnabled;
    public override function clone():Event {
    return new ZoomEvent(type, isEnabled);
    Furthermore I have somewhere read in the documentation that
    using custom event should go together with adding an embedded
    statement like: [Event(name="update",
    type="Components.UpdateEvent")] in the class where you use the
    event, but for me it also works without this embedding code (???)
    And is your class XMLData a subclass from a class that
    supports dispatchEvent. I do not know what classes support
    dispatchEvent, maybe all. Then this remark makes no sense.
    Good Lcuk

  • Swapping between different logical views

    I am designing an applet that has several logical views, such as Login, Registration, Waiting Area, and Game. I am very new to applets and Swing, and I can't figure out how to have each of these designed separately and then swap between them. Ideally, this is what I would like:
    1) Each view can be designed separately using NetBeans IDE, preferably in different classes for neatness.
    2) When certain conditions are met (such as successful login), then all content in the applet window will be removed and replaced with that of a new view.
    I attempted to use setContentPane to achieve this, but it doesn't seem to repaint correctly except when called initially. Otherwise, the setting the content pane and calling repaint will pain the screen blank. If you resize the window (only possible via applet viewers, not via web page applet) then the content displays properly. It seems like I need to somehow force the applet to repaint, but neither the repaint method nor manually modifying items, such as changing text on the new screen via setText, will not force it to display.
    When I used setContentPane(myLoginGUI.getContentPane) in an event-dispatching thread during init, it correctly displays the login page.
    Here's some of the code I was using, involving classes Client, LoginGUI, and RegisterGUI, which all extend japplet:
        //in Client.java:
        //called during init from an event dispatching thread
        //also called in RegisterGUI from button handler for goBackToLogin button
        public void createLoginGUI(){
            myLoginGUI = new LoginGUI();
            this.setContentPane(myLoginGUI.getContentPane());
            repaint();
        //called when user clicks register button from login page.  button handler
        //is in LoginGUI
        public void createRegisterGUI() {
            myRegisterGUI = new RegisterGUI();
            this.setContentPane(myRegisterGUI.getContentPane());
            repaint();
        }Thanks for reading this and any insights you may have.
    Message was edited by:
    bubonics

    The easiest way is to use a CardLayout:
    http://java.sun.com/docs/books/tutorial/uiswing/layout/card.html
    In general, whenever you add or remove a compnent from a Container you need to validate(), or if its a Swing compnent, revalidate() the container. So you could try to validate() the frame before the repaint.

  • How to pass/share components between different JPanels/Container

    Dear Friends,
    I know here a lot Java Guru, I met a problem below.
    How can I pass components between different JPanels??
    here, ListPanelMain.java is main,
    When I click a tree node in splitPane, I can see all its children on the right splitpane, but I hope they can be seen on another Panel called "ListRightPane.java"
    How to do it??
    Why cannot pass??
    [1]. main Program:
    package swing.com.test.test;
    import javax.swing.JFrame;
    import java.awt.BorderLayout;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JSplitPane;
    import javax.swing.JTextArea;
    import java.io.Serializable;
    import swing.com.test.test.ListPanel;
    import java.awt.GridLayout;
    public class ListPanelMain implements java.io.Serializable{
         private JFrame frame;
         * Launch the application
         * @param args
         public static void main(String args[]) {
              try {
                   ListPanelMain window = new ListPanelMain();
                   window.frame.setVisible(true);
              } catch (Exception e) {
                   e.printStackTrace();
         * Create the application
         public ListPanelMain() {
              initialize();
         * Initialize the contents of the frame
         private void initialize() {
              frame = new JFrame("FileTreePanelMain");
              frame.setBounds(100, 100, 900, 675);
         //     FieTreePanelComm      ftreecomm                = new      FieTreePanelComm();
              ListPanel                ftree                     = new      ListPanel("C:\\");
    //          ListAllFile           ftree                     = new      ListAllFile("C:\\");
         //     FileTreePanelText      fileTreePanelText      = new      FileTreePanelText(ftreecomm);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              final JPanel panel = new JPanel();
              panel.setLayout(new GridLayout(0, 2));
              frame.getContentPane().add(panel, BorderLayout.CENTER);
         //     final JSplitPane splitPane = new JSplitPane();
         //     frame.getContentPane().add(splitPane, BorderLayout.CENTER);
         //     splitPane.setLeftComponent(ftree);
              panel.add(ftree);
              final ListRightPanel listRightPanel = new ListRightPanel(ftree);
              //splitPane.setRightComponent(listRightPanel);
              panel.add(listRightPanel);
         frame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
         System.exit(0);
         frame.pack();
         frame.setVisible(true);
    [2]. Program 2:
    package swing.com.test.test;
    //File System Tree
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GridLayout;
    import java.io.File;
    import java.util.Iterator;
    import java.util.Vector;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.JPanel;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import java.io.Serializable;
    public class ListPanel extends JPanel implements Serializable{
    protected JTree fileTree;
    private FileSystemModel fileSystemModel;
    private JTextArea ltextArea = new JTextArea();
    protected JTextArea fileDetailsTextArea = new JTextArea();
    private String str = "";
         public String getlTextArea() {
                   //textArea.getText();
                   return str;
         public String setlTextArea(String ta) {
                   ltextArea.setText(ta);
                   str = ta;
                   return str;
    public ListPanel(String directory) {
    //super("JTree FileSystem Viewer");
                   setLayout(new BorderLayout());
                   final JPanel panel = new JPanel();
                   panel.setLayout(new BorderLayout());
              add(panel, BorderLayout.CENTER);
    fileDetailsTextArea.setEditable(false);
    fileSystemModel = new FileSystemModel(new File(directory));
    fileTree = new JTree(fileSystemModel);
    fileTree.setEditable(true);
    fileTree.addTreeSelectionListener(new TreeSelectionListener() {
    public void valueChanged(TreeSelectionEvent event) {
    System.out.println("1. What we save is: getlTextArea() =" + getlTextArea() );
    File file = (File) fileTree.getLastSelectedPathComponent();
    fileDetailsTextArea.setText(getFileDetails(file));
    final ListRightPanel lrp = new ListRightPanel(this);
    lrp.textArea.setText(getFileDetails(file));
    setlTextArea(getFileDetails(file));
    System.out.println("2. What we save is: getlTextArea() =" + getlTextArea() );
              final JSplitPane splitPane = new JSplitPane();
              panel.add(splitPane, BorderLayout.CENTER);
              final JPanel panel_1 = new JPanel();
              splitPane.setLeftComponent(panel_1);
              panel_1.add(new JScrollPane(fileTree));
              final JPanel panel_2 = new JPanel();
              splitPane.setRightComponent(panel_2);
              panel_2.add(new JScrollPane(fileDetailsTextArea));
    setVisible(true);
    private String getFileDetails(File file) {
    if (file == null)
    return "";
    StringBuffer buffer = new StringBuffer();
    if (file.listFiles()!=null){
         for (int i=0; i< file.listFiles().length; i++){
         buffer.append(((file.listFiles())) + "\n");
         System.out.println("List all files");
    return buffer.toString();
    public static void main(String args[]) {
    new ListPanel("c:\\");
    class FileSystemModel implements TreeModel {
    private File root;
    private Vector listeners = new Vector();
    public FileSystemModel(File rootDirectory) {
    root = rootDirectory;
    public Object getRoot() {
    return root;
    public Object getChild(Object parent, int index) {
    File directory = (File) parent;
    String[] children = directory.list();
    return new TreeFile(directory, children[index]);
    public int getChildCount(Object parent) {
    File file = (File) parent;
    if (file.isDirectory()) {
    String[] fileList = file.list();
    if (fileList != null)
    return file.list().length;
    return 0;
    public boolean isLeaf(Object node) {
    File file = (File) node;
    return file.isFile();
    public int getIndexOfChild(Object parent, Object child) {
    File directory = (File) parent;
    File file = (File) child;
    String[] children = directory.list();
    for (int i = 0; i < children.length; i++) {
    if (file.getName().equals(children[i])) {
    return i;
    return -1;
    public void valueForPathChanged(TreePath path, Object value) {
    File oldFile = (File) path.getLastPathComponent();
    String fileParentPath = oldFile.getParent();
    String newFileName = (String) value;
    File targetFile = new File(fileParentPath, newFileName);
    oldFile.renameTo(targetFile);
    File parent = new File(fileParentPath);
    int[] changedChildrenIndices = { getIndexOfChild(parent, targetFile) };
    Object[] changedChildren = { targetFile };
    fireTreeNodesChanged(path.getParentPath(), changedChildrenIndices, changedChildren);
    private void fireTreeNodesChanged(TreePath parentPath, int[] indices, Object[] children) {
    TreeModelEvent event = new TreeModelEvent(this, parentPath, indices, children);
    Iterator iterator = listeners.iterator();
    TreeModelListener listener = null;
    while (iterator.hasNext()) {
    listener = (TreeModelListener) iterator.next();
    listener.treeNodesChanged(event);
    public void addTreeModelListener(TreeModelListener listener) {
    listeners.add(listener);
    public void removeTreeModelListener(TreeModelListener listener) {
    listeners.remove(listener);
    private class TreeFile extends File {
    public TreeFile(File parent, String child) {
    super(parent, child);
    public String toString() {
    return getName();
    [3]. Program 3:
    package swing.com.test.test;
    import java.awt.BorderLayout;
    import java.io.File;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import java.io.Serializable;
    public class ListRightPanel extends JPanel implements TreeSelectionListener, Serializable{
         protected JTextArea textArea;
    //     protected ListAllFile laf;
    private String str = "";
              public String getlTextArea() {
                        //textArea.getText();
                        return str;
              public String setlTextArea(String ta) {
                        str = ta;
                        return str;
         * Create the panel
         public ListRightPanel(ListPanel laff) {
              super();
              setLayout(new BorderLayout());
              final JPanel panel = new JPanel();
              panel.setLayout(new BorderLayout());
              add(panel, BorderLayout.CENTER);
              textArea = new JTextArea();
    final String st = laff.getlTextArea();
    System.out.println("####################################");
    System.out.println("st=" + st);
         laff.fileTree.addTreeSelectionListener(new TreeSelectionListener() {
         public void valueChanged(TreeSelectionEvent event) {
         //laff.textArea.setText(getFileDetails(file));
              textArea.setText(getlTextArea());
         System.out.println("ListRightPanel Was Invoked from ListPanel!!getlTextArea() =" + getlTextArea() );
         System.out.println("st=" + st);
              panel.add(textArea, BorderLayout.CENTER);
         public void valueChanged(TreeSelectionEvent e){};
    It is runnable program, just compile and run it in Console is ok,
    Regards
    Sunny

    Thnaks, code post again, see
    [1]. package swing.com.test.test;
    import javax.swing.JFrame;
    import java.awt.BorderLayout;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JSplitPane;
    import javax.swing.JTextArea;
    import java.io.Serializable;
    import swing.com.test.test.ListPanel;
    import java.awt.GridLayout;
    public class ListPanelMain implements java.io.Serializable{
         private JFrame frame;
          * Launch the application
          * @param args
         public static void main(String args[]) {
              try {
                   ListPanelMain window = new ListPanelMain();
                   window.frame.setVisible(true);
              } catch (Exception e) {
                   e.printStackTrace();
          * Create the application
         public ListPanelMain() {
              initialize();
          * Initialize the contents of the frame
         private void initialize() {
              frame = new JFrame("FileTreePanelMain");
              frame.setBounds(100, 100, 900, 675);
         //     FieTreePanelComm      ftreecomm                = new       FieTreePanelComm();
              ListPanel                 ftree                     = new      ListPanel("C:\\");
    //          ListAllFile            ftree                     = new      ListAllFile("C:\\");
         //     FileTreePanelText      fileTreePanelText      = new      FileTreePanelText(ftreecomm);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              final JPanel panel = new JPanel();
              panel.setLayout(new GridLayout(0, 2));
              frame.getContentPane().add(panel, BorderLayout.CENTER);
         //     final JSplitPane splitPane = new JSplitPane();
         //     frame.getContentPane().add(splitPane, BorderLayout.CENTER);
         //     splitPane.setLeftComponent(ftree);
              panel.add(ftree);
              final ListRightPanel listRightPanel = new ListRightPanel(ftree);
              //splitPane.setRightComponent(listRightPanel);
              panel.add(listRightPanel);
                frame.addWindowListener(new WindowAdapter() {
                     public void windowClosing(WindowEvent e) {
                         System.exit(0);
                 frame.pack();
                 frame.setVisible(true);
    }[2] Program 2
    package swing.com.test.test;
    //File System Tree
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.GridLayout;
    import java.io.File;
    import java.util.Iterator;
    import java.util.Vector;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JSplitPane;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.JPanel;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import java.io.Serializable;
    public class ListPanel extends JPanel implements Serializable{
      protected JTree fileTree;
      private FileSystemModel fileSystemModel;
      private JTextArea ltextArea = new JTextArea();
      protected JTextArea fileDetailsTextArea = new JTextArea();
      private String str = "";
         public  String getlTextArea()  {
                   //textArea.getText();
                      return str;
         public  String setlTextArea(String ta)  {
                   ltextArea.setText(ta);
                   str = ta;
                      return str;
      public ListPanel(String directory) {
        //super("JTree FileSystem Viewer");
                   setLayout(new BorderLayout());
                   final JPanel panel = new JPanel();
                   panel.setLayout(new BorderLayout());
                  add(panel, BorderLayout.CENTER);
        fileDetailsTextArea.setEditable(false);
        fileSystemModel = new FileSystemModel(new File(directory));
        fileTree = new JTree(fileSystemModel);
        fileTree.setEditable(true);
        fileTree.addTreeSelectionListener(new TreeSelectionListener() {
          public void valueChanged(TreeSelectionEvent event) {
            System.out.println("1. What we save is: getlTextArea() =" + getlTextArea() );
            File file = (File) fileTree.getLastSelectedPathComponent();
            fileDetailsTextArea.setText(getFileDetails(file));
            final ListRightPanel lrp = new ListRightPanel(this);
            lrp.textArea.setText(getFileDetails(file));
            setlTextArea(getFileDetails(file));
            System.out.println("2. What we save is: getlTextArea() =" + getlTextArea() );
              final JSplitPane splitPane = new JSplitPane();
              panel.add(splitPane, BorderLayout.CENTER);
              final JPanel panel_1 = new JPanel();
              splitPane.setLeftComponent(panel_1);
              panel_1.add(new JScrollPane(fileTree));
              final JPanel panel_2 = new JPanel();
              splitPane.setRightComponent(panel_2);
              panel_2.add(new JScrollPane(fileDetailsTextArea));
        setVisible(true);
      private String getFileDetails(File file) {
        if (file == null)
          return "";
        StringBuffer buffer = new StringBuffer();
        if (file.listFiles()!=null){
             for (int i=0; i< file.listFiles().length; i++){
             buffer.append(((file.listFiles())) + "\n");
         System.out.println("List all files");
    return buffer.toString();
    public static void main(String args[]) {
    new ListPanel("c:\\");
    class FileSystemModel implements TreeModel {
    private File root;
    private Vector listeners = new Vector();
    public FileSystemModel(File rootDirectory) {
    root = rootDirectory;
    public Object getRoot() {
    return root;
    public Object getChild(Object parent, int index) {
    File directory = (File) parent;
    String[] children = directory.list();
    return new TreeFile(directory, children[index]);
    public int getChildCount(Object parent) {
    File file = (File) parent;
    if (file.isDirectory()) {
    String[] fileList = file.list();
    if (fileList != null)
    return file.list().length;
    return 0;
    public boolean isLeaf(Object node) {
    File file = (File) node;
    return file.isFile();
    public int getIndexOfChild(Object parent, Object child) {
    File directory = (File) parent;
    File file = (File) child;
    String[] children = directory.list();
    for (int i = 0; i < children.length; i++) {
    if (file.getName().equals(children[i])) {
    return i;
    return -1;
    public void valueForPathChanged(TreePath path, Object value) {
    File oldFile = (File) path.getLastPathComponent();
    String fileParentPath = oldFile.getParent();
    String newFileName = (String) value;
    File targetFile = new File(fileParentPath, newFileName);
    oldFile.renameTo(targetFile);
    File parent = new File(fileParentPath);
    int[] changedChildrenIndices = { getIndexOfChild(parent, targetFile) };
    Object[] changedChildren = { targetFile };
    fireTreeNodesChanged(path.getParentPath(), changedChildrenIndices, changedChildren);
    private void fireTreeNodesChanged(TreePath parentPath, int[] indices, Object[] children) {
    TreeModelEvent event = new TreeModelEvent(this, parentPath, indices, children);
    Iterator iterator = listeners.iterator();
    TreeModelListener listener = null;
    while (iterator.hasNext()) {
    listener = (TreeModelListener) iterator.next();
    listener.treeNodesChanged(event);
    public void addTreeModelListener(TreeModelListener listener) {
    listeners.add(listener);
    public void removeTreeModelListener(TreeModelListener listener) {
    listeners.remove(listener);
    private class TreeFile extends File {
    public TreeFile(File parent, String child) {
    super(parent, child);
    public String toString() {
    return getName();
    [3] Program 3:
    package swing.com.test.test;
    import java.awt.BorderLayout;
    import java.io.File;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JTree;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import java.io.Serializable;
    public class ListRightPanel extends JPanel implements TreeSelectionListener, Serializable{
         protected JTextArea textArea;
    //     protected ListAllFile  laf;
        private String str = "";
              public  String getlTextArea()  {
                        //textArea.getText();
                           return str;
              public  String setlTextArea(String ta)  {
                        str = ta;
                           return str;
          * Create the panel
         public ListRightPanel(ListPanel  laff) {
              super();
              setLayout(new BorderLayout());
              final JPanel panel = new JPanel();
              panel.setLayout(new BorderLayout());
              add(panel, BorderLayout.CENTER);
              textArea = new JTextArea();
            final String st = laff.getlTextArea();
            System.out.println("####################################");
            System.out.println("st=" + st);
             laff.fileTree.addTreeSelectionListener(new TreeSelectionListener() {
                 public void valueChanged(TreeSelectionEvent event) {
                   //laff.textArea.setText(getFileDetails(file));
                      textArea.setText(getlTextArea());
                     System.out.println("ListRightPanel Was Invoked from ListPanel!!getlTextArea() =" + getlTextArea() );
                     System.out.println("st=" + st);
              panel.add(textArea, BorderLayout.CENTER);
           public void valueChanged(TreeSelectionEvent e){};
    }You can try this one, thanks again
    sunny

  • Listen for event in own class?

    Hi
    I dispatch events from models to classes listening. How do you set up an event and listener in the same class?
    Eg for the former - a model "MyModel" to class - it's:
    public static const MY_VAR:String = "myVar";
    triggered by...
    dispatchEvent(new Event(MY_VAR));
    picked up in another class by...
    modelVar.addEventListener(MyModel.MY_VAR, doSomething);
    but what if the class that's dispatching also has the listener?
    So if MyClass is dispatching the event, along the lines of...
    addEventListener(MyClass.MY_VAR, doSomething);
    Cheers for taking a look

    Very often I'm waiting for a few key items before I can finally do something else. Setting simple flags or checking nulls can help with this.
    Often I download multiple data structures (JSON/XML/etc) and I need all of them before I can parse them because the co-depend on each other. URLLoaders finish at different times so I just set a flag for what I need but check if all are complete before I continue each time one finishes.
    e.g.
    package
         public class IHateWaiting extends EventDispatcher
              public static const MY_VAR:String = "myVar";
              private var _xmlA:XML;
              private var _xmlB:XML;
              public function IHateWaiting()
                   // load A
                   var ulA:URLLoader = new URLLoader();
                   ulA.addEventListener(Event.COMPLETE, _handleFinishedF);
                   ulA.load(new URLRequest("http://www.example.com/a.xml"));
                   // load B
                   var ulB:URLLoader = new URLLoader();
                   ulB.addEventListener(Event.COMPLETE, _handleFinishedF);
                   ulB.load(new URLRequest("http://www.example.com/b.xml"));
                   // listen to self
                   addEventListener(IHateWaiting.MY_VAR, _handleAppEventF);
              private function _handleFinishedF(e:Event):void
                   if (e.type == Event.COMPLETE)
                        var data:XML = XML(e.target.data);
                        // A or B? any way you can tell
                        if (data.A.length() > 0) _xmlA = data;
                        else if (data.B.length() > 0) _xmlB = data;
                        // event method (requires extra handler or a fake event)
                        if (_xmlA && _xmlB) dispatchEvent(new Event(IHateWaiting.MY_VAR));
                        // preferred direct reference, no handler needed
                        // if (_xmlA && _xmlB) _parseXML();
              private function _handleAppEventF(e:Event):void
                   if (e.type == IHateWaiting.MY_VAR) _parseXML();
              private function _parseXML():void
                    // parse XML
    I recommend the reference version from post #2. It's cleaner because you don't need to double up on functions (handler->reference) like you see above with dispatching. The only purpose for _handleAppEventF() in this case is just to run _parseXML(), which is a useless duplicate function.
    I've always kept my handlers free of model-esque logic, so you see me calling a different function from that handler, _parseXML(). This is just because I want my handlers to only handle events and then hand off the work elsewhere.
    Instead of dispatching the event, I agree with moccamaximum, run the method directly. Even if it's 2 lines of code to do 1 thing, I think the clarity of it is much cleaner coding. So I would recommend nuking the self-listener in the constructor above. When I have all the data I'm looking for, I'd run the methods in the class directly and If the parent needs to know, I'd dispatch when they complete.
    e.g.
              private function _handleFinishedF(e:Event):void
                   if (e.type == Event.COMPLETE)
                        var data:XML = XML(e.target.data);
                        // A or B? any way you can tell
                        if (data.A.length() > 0) _xmlA = data;
                        else if (data.B.length() > 0) _xmlB = data;
                        if (_xmlA && _xmlB)
                             // parse first (synchronous)
                             _parseXML();
                             // xml ready, dispatch to parent
                             dispatchEvent(new Event(IHateWaiting.MY_VAR));

  • Dispatching Event in ItemRenderer Component?

    Am I going about this the right way? Here's my situation:
    I have a custom itemRenderer for a List. This itemRenderer consists mainly of a checkbox and label, but has a few additional details in it (which is why I'm not using a drop-in itemRenderer). I want to detect when the selection of the checkbox changes, so I was thinking of creating a custom event in the itemRenderer and then bubbling it up to the list.
    Or is there a way I can detect when a user checks a checkbox from the lists itself?
    Thanks!

    I found this article which explains this topic very well also: http://weblogs.macromedia.com/pent/archives/2008/03/itemrenderers_p_2.html
    (It appears that these may be referencing the same series of articles on different sites.)
    However, I am now conflicted, because if I the version without bubbling, I am tying the itemRenderer directly to my component; whereas with bubbling I don't need to make that association. I may opt for the bubbling route after all, because I want to keep my itemRenderers generic enough to use in any of my custom controls, and not just in a certain type.
    For more clarification: the hangup is where the event gets triggered on the listData.owner. To do this, it appears that it must be type-cast first, and then manipulated. Any ideas on how to get around that? Here's Peter's example:
    ====================================
    First, you have to add metadata to the CatalogList control to let the compiler know the control dispatches the event:
         import events.BuyBookEvent;
         import mx.controls.TileList;
         [Event(name="buyBook",type="events.BuyBookEvent")]
         public class CatalogList extends TileList
    Second, add a function to CatalogList to dispatch the event. This function will be called by the itemRenderer instances:
              public function dispatchBuyEvent( item:Object ) : void
                   var event:BuyBookEvent = new BuyBookEvent();
                   event.bookData = item;
                   dispatchEvent( event );
    Third, change the Buy button code in the itemRenderer to invoke the function:
                   <mx:Button label="Buy" fillColors="[0x99ff99,0x99ff99]">
                        <mx:click>
                        <![CDATA[
                             (listData.owner as CatalogList).dispatchBuyEvent(data);
                        ]]>
                        </mx:click>
                   </mx:Button>
    Now the Button in the itemRenderer can simply invoke a function in the list control with the data for the record (or anything else that is appropriate for the action) and pass the responsibility of interfacing with the rest fo the application onto the list control.
    ====================================

  • How to use "User Events" in different parts of an application

    Hi,
    "You programmatically can create and name your own events, called user events, to carry user-defined data. Like queues and notifiers, user events allow different parts of an application to communicate asynchronously. You can handle both user interface and programmatically generated user events in the same Event structure."
    What you read was part of labview 7.1 user manual ( Chapter 9 - pg.12 ). I've some problems with the underlined sentence. I hope someone can help me.
    When using Queues, the programmer may use a named queue everywhere in the application. there is no need to wire queue reference among VIs or using global variables to store queue reference. the name of the queue will be all that you need. I wonder if it is also possible with a event refnum that is the output of "Register for Event" node. As far as I've tested. the answer is Negative! I tried to copy-paste refnum in front panels and using the same name. but there is no connection between event refnums.
    LV User manual claims that user events can be used like queues, but it doesn't seem so.
    Does anybody have an idea?
    Best Regards.

    I didn't look at Damien Gray's presentation recently, but if I remember it correctly, it is on a much higher level than what I meant, because it refers to LARGE application. This is a very simple one.
    Using a functional global is not problematic CPU-wise, nor memory wise (unless you get into really big data structures, like hundreds of MBs), so you shouldn't be afraid to use it. I'm also not sure why you're afraid of the loop. The loop is only there to "hold" the USR. It only runs once. If you want, you can replace it with a for loop that runs once. I've recently learned that apparently, you can also get rid of the loop and use a local variable (look at the example called XY chart) instead of a USR. I don't think a local variable should have any more impact than a USR, but that needs to be tested. It can definitely be more convenient for some VIs where you don't have to wire the SR through the entire VI.
    Anyway, you will need to have an "obtain ref" VI which will hold a 1D array of names and a corresponding array of refs. Then, you search the array for the name, and if it finds the name, it extracts the correct reference. You will also need a way to input references and names into the array and possibly a way to empty the array. You may need to have 2 levels - the inner VI will be the LV2 VI and the parent will be the obtain ref\fill array\close VI. You will need some error handling as well - what happens if you search for a name and it can't be found and so on...
    Hope this helps.
    Try to take over the world!

  • Communication between different JVMs

    Hallo,
    is there a simple way, to exchange data between different java sessions? At the moment I store the needed data to a table and load it in my java procedures when ever I need them.
    But because this data is temporary, it wouldn't really be necessary to store the data. It's just for communication between the different JVMs. Is there an other way to do this, too?
    Thanks, Christian

    Christian, I may have misunderstood your question, but, until java version 1.4, the only way for different JVMs to communicate was via sockets, or secondary storage (the file system -- which includes databases).
    In java version 5.0 (previously version 1.5), there is a new feature known as class data sharing.
    But since you posted to the "Database >> JVM" forum, I can't help thinking that you are referring to different database JVMs. Is that correct? In any case, sockets and secondary storage are your only options there as well.
    Good Luck,
    Avi.

Maybe you are looking for

  • Mid-2014 rMBP Display Issue

    Last week, bought mid-2014 base model rMPB 13.3. Display was warm yellowish with greenish tint. Compared with store models, which all had cool blue. Replacement had same issue, so I asked for refund. Display looked worse than my late 2010 base model

  • Error in query running.

    when i am running a query i am getting this error  in WAD: "Value 'SPEED STICK DEO REG (1dz)' (hex. '0053005000450045004400200053005400490043004B002000') of characteristic 0CP_TEXT contains invalid characters", I tried to run the same query in RSRT,

  • Recurring inspection lot status "created" changed automatically to "Release" without change history

    Dear Experts, I observed that for few materials recurring inspection lot (inspection lot origin 09) status from "CRTD CHCR SPRQ" to "REL  CALC SPRQ PRSI" changed automatically without manual interruption. I have thoroughly checked the change document

  • Is it possible to split a song in 2 as a whole, and insert a new part in the middle?

    Im recording a song, and just realized id like to have an 8 bar drum part in the middle of it, before it kicks in to the other part... Is it possible to do this or do I have to cut and paste each track indivually?  There are 27 so it would be pretty

  • Read from server and display in external frame

    Hello everyone, I am using Eclipse, My project consist of server and client connected through a socket. When I connect to the server, i am getting lots of data from the server and it takes a bit of time, so I was thinking while the user wait for the