JTree, JList and file selection

I have a file selection JPanel that I'm creating that has a JTree on the left representing folders and a JList on the right that should have the files and folders listed to be able to select. I have two problems at this point. First, and more important, when a folder is selected, the JList doesn't update to the files in the new folder and I don't see what's keeping it from working. Second, when clicking on a folder in the JTree, it drops the folder to the end of the list and then lets you expand it to the other folders, also it shows the whole folder path instead of just the folder name.
This is still my first venture into JTrees and JLists and I'm still really new at JPanel and anything GUI, so my code may not make the most sense, but right now I'm just trying to get it to work.
Thank you.
public class FileSelection extends JFrame{
          Container gcp = getContentPane();
          File dir=new File("c:/");
          private JList fileList;
          JTree tree;
          DefaultMutableTreeNode folders;
          String filePath,selectedFile="", path;
          TreePath selPath;
          FileListPanel fileLP;
          FolderListPanel folderLP;
          JScrollPane listScroller;
          public FileSelection(String name){
               super(name);
               gcp.setLayout(new BorderLayout());
               fileLP = new FileListPanel();
               folderLP = new FolderListPanel();
               gcp.add(fileLP, BorderLayout.CENTER);
               gcp.add(folderLP, BorderLayout.WEST);
               setVisible(true);
          private class FileListPanel extends JPanel implements ActionListener{
               public FileListPanel(){
                    final JButton selectItem = new JButton("Select");
                    final JButton cancel = new JButton("Cancel");
                    final JButton changeDir = new JButton("Change Directory");
                    //add buttons
                    add(selectItem);
                    add(changeDir);
                    add(cancel);
                    //instantiate buttons
                    selectItem.setActionCommand("SelectItem");
                    selectItem.addActionListener(this);
                    changeDir.setActionCommand("ChangeDirectory");
                    changeDir.addActionListener(this);
                    cancel.setActionCommand("Cancel");
                    cancel.addActionListener(this);
                    final String[] fileArr=dir.list();
                    fileList = new JList(fileArr);
                    fileList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
                    fileList.setLayoutOrientation(JList.VERTICAL_WRAP);
                    fileList.setVisible(true);
                    fileList.setVisibleRowCount(-1);
                    fileList.setSelectedIndex(0);
                    listScroller = new JScrollPane(fileList);
                    listScroller.setPreferredSize(new Dimension(200,200));
                    listScroller.setAlignmentX(LEFT_ALIGNMENT);
                    add(listScroller);
                    MouseListener mouseListener = new MouseAdapter(){
                         public void mouseClicked(MouseEvent e){
                              if(e.getClickCount()==2){
                                   int itemIndex = fileList.locationToIndex(e.getPoint());
                                   currFile=fileArr[itemIndex];
                                   dispose();
                    fileList.addMouseListener(mouseListener);
               public void actionPerformed(ActionEvent e){
                    if("SelectItem".equals(e.getActionCommand())){
                         currFile=(String)fileList.getSelectedValue();
                         dispose();
                    }else{
                    if("Cancel".equals(e.getActionCommand())){
                         dispose();
                    }else{
                    if("ChangeDirectory".equals(e.getActionCommand())){
                         ChangeDir cd = new ChangeDir("Select Directory");
                         cd.setSize(new Dimension(300,275));
                         cd.setLocation(500, 225);
          private class FolderListPanel extends JPanel{
               public FolderListPanel(){
                    String[] files = dir.list();
                    DefaultMutableTreeNode topNode = new DefaultMutableTreeNode("Files");
                    folders = new DefaultMutableTreeNode("C:/");
                    topNode.add(folders);
                    folders = getFolders(dir, folders);
                    tree = new JTree(topNode);
                    tree.setVisible(true);
                    JScrollPane treeScroller = new JScrollPane(tree);
                    treeScroller.setPreferredSize(new Dimension(500,233));
                    treeScroller.setAlignmentX(LEFT_ALIGNMENT);
                    add(treeScroller);
                    MouseListener mouseListener = new MouseAdapter(){
                         public void mouseClicked(MouseEvent e){
                              try{
                                   if(e.getClickCount()==1){
                                        selPath = tree.getPathForLocation(e.getX(), e.getY());
                                        path=selPath.getLastPathComponent().toString();
                                        dir = new File(path);
                                        TreeNode tn=findNode(folders, path);                    
                                        if(tn!=null){
                                             folders.add((MutableTreeNode) getTreeNode(dir, (DefaultMutableTreeNode) tn));
                                        tree.updateUI();
                                        final String[] fileArr=dir.list();
                                        fileList = new JList(fileArr);
                                        fileList.updateUI();
                                        listScroller.updateUI();
                                        fileLP = new FileListPanel();
                              }catch(NullPointerException npe){
                    tree.addMouseListener(mouseListener);
               public DefaultMutableTreeNode getFolders(File dir, DefaultMutableTreeNode folders){
                    File[] folderList = dir.listFiles();
                    int check=0;
                    for(int x=0;x<folderList.length;x++){
                         if(folderList[x].isDirectory()){
                              folders.add(new DefaultMutableTreeNode(folderList[x]));               
                    return folders;
               public TreeNode getTreeNode(File dir, DefaultMutableTreeNode folders){
                    File[] folderList = dir.listFiles();
                    int check=0;
                    for(int x=0;x<folderList.length;x++){
                         if(folderList[x].isDirectory()){
                              folders.add(new DefaultMutableTreeNode(folderList[x]));               
                    return folders;
               public TreeNode findNode(DefaultMutableTreeNode folders, String node){
                    Enumeration children = folders.postorderEnumeration();
                    Object current;
                    while(children.hasMoreElements()){
                         current = children.nextElement();
                         if(current.toString().equals(node)){
                              return (TreeNode)current;
                    return null;
     }

Wow! I changed the FolderListPanel's mouseListener to:
tree.addTreeSelectionListener(new TreeSelectionListener(){
                         public void valueChanged(TreeSelectionEvent tse){
                              DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
                              if(node==null)return;
                              Object nodeInfo = node.getUserObject();
                              dir=new File(nodeInfo.toString());
                              folders.add((MutableTreeNode) getFolders(dir,node));
                    });and it's amazing how much better the tree is!!! But I still don't have the JList part working. I changed the JList and the FileListPanel to public from private, but that didn't change anything.

Similar Messages

  • I have a 15" MacBook Pro 2.4 GHz Intel Core 2 Duo (Early 2008) running OSX Lion 10.7.5. I want to erase the Hard Drive, install Mountain Lion, and manually restore select applications and files. Is there a known procedure to do this? Any tips or feedback?

    I have a 15" MacBook Pro 2.4 GHz Intel Core 2 Duo (Early 2008) running OSX Lion 10.7.5.
    I want to erase the Hard Drive, install Mountain Lion, and manually restore select applications and files.
    Is there a known procedure to do this? Any tips or feedback?

    1. Make a backup, open App Store and purchase Mountain Lion. When its download finishes, close the installer and open Lion Diskmaker to create a bootable USB drive with Mountain Lion.
    2. Press Option key while your Mac is starting, select the external drive and open Disk Utility.
    3. Select Macintosh HD in the sidebar and erase the drive.
    4. Close the window and install Mountain Lion

  • JTree and file directory

    I'm messing with using a JTree to list folders for file selection. I have this class that I'm just using to get a grip on this with, but I'm stuck now. Basically I get it reading the directories, but when I add the next round of folders, it gets added on the "C:/" node instead of the node that was clicked on.
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class JavaTest extends JFrame{
         public class TreePanel extends JFrame{
              Container gcp = getContentPane();
              File dir;
              String filePath, dlim, selectedFile="", path;
              DefaultMutableTreeNode folders;
              TreePath selPath;
              JTree tree;
              public TreePanel(String name){
                   super(name);
                   gcp.setLayout(new BorderLayout());
                   gcp.add(new FileListPanel(), BorderLayout.CENTER);
                   setVisible(true);
              private class FileListPanel extends JPanel implements ActionListener{
                   public FileListPanel(){
                        dir = new File("c:/");
                        String[] files = dir.list();
                        DefaultMutableTreeNode topNode = new DefaultMutableTreeNode("Files");
                        folders = new DefaultMutableTreeNode("C:/");
                        topNode.add(folders);
                        folders = getFolders(dir, folders);
                        tree = new JTree(topNode);
                        tree.setVisible(true);
                        JScrollPane listScroller = new JScrollPane(tree);
                        listScroller.setPreferredSize(new Dimension(200,200));
                        listScroller.setAlignmentX(LEFT_ALIGNMENT);
                        add(listScroller);
                        MouseListener mouseListener = new MouseAdapter(){
                             public void mouseClicked(MouseEvent e){
                                  try{
                                       if(e.getClickCount()==1){
                                            selPath = tree.getPathForLocation(e.getX(), e.getY());
                                            path=selPath.getLastPathComponent().toString();
                                            dir = new File(path);
                                            folders = getFolders(dir,folders);
                                            tree.updateUI();
                                  }catch(NullPointerException npe){
                        tree.addMouseListener(mouseListener);
                   public DefaultMutableTreeNode getFolders(File dir, DefaultMutableTreeNode folders){
                        File[] folderList = dir.listFiles();
                        int check=0;
                        for(int x=0;x<folderList.length;x++){
                             if(folderList[x].isDirectory()){
                                  folders.add(new DefaultMutableTreeNode(folderList[x]));               
                        return folders;
                   public void actionPerformed(ActionEvent e){
         public static void main(String[] args){
              JavaTest jt = new JavaTest();
              TreePanel tp;
              tp = jt.new TreePanel("test");
              tp.setVisible(true);
              tp.setSize(300, 300);
              tp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }this line:
    folders = getFolders(dir,folders);
    is the problem. I don't want to add it to 'folders' I need it to be added to the tree node that was clicked on but I don't see how to get DefaultMutableTreeNode item. I can get a string representation of it, but that doesn't help.

    Maybe this will help
    tjacobs.tree.FileSystemTreeModel
    =========================
    package tjacobs.tree;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.io.File;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.ArrayList;
    import javax.swing.JOptionPane;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.event.TreeModelEvent;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.DefaultTreeCellEditor;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import tjacobs.io.IOUtils;
    import tjacobs.io.DataFetcher;
    import tjacobs.ui.util.WindowUtilities;
    public class FileSystemTreeModel implements TreeModel {
         File mRoot;
         ArrayList<TreeModelListener> mListeners = new ArrayList<TreeModelListener>(1);
         public FileSystemTreeModel() {
              File f = new File(".");
              f = f.getAbsoluteFile();
              File par = null;
              do {
                   par = f.getParentFile();
                   if (par != null) {
                        f = par;
                   else {
                        setRootFile(f);
                        return;
              } while (mRoot == null);
         public FileSystemTreeModel(File root) {
              setRootFile(root);
         private void setRootFile(File root) {
              mRoot = root;
         public void addTreeModelListener(TreeModelListener l) {
              mListeners.add(l);
         public Object getChild(Object parent, int index) {
              try {
                   File fi = (File) parent;
                   File[] subs = fi.listFiles();
                   if (index < subs.length) {
                        return subs[index];
              catch (ClassCastException ex) {
                   ex.printStackTrace();
              return null;
         public int getChildCount(Object parent) {
              try {
                   File fi = (File) parent;
                   return fi.listFiles().length;
              catch (ClassCastException ex) {
                   ex.printStackTrace();
              return 0;
         public int getIndexOfChild(Object parent, Object child) {
              try {
                   File fi = (File) parent;
                   File[] subs = fi.listFiles();
                   for (int i = 0; i < subs.length; i++) {
                        File f = subs;
                        if (f.equals(child)) return i;
              catch (ClassCastException ex) {
                   ex.printStackTrace();
              return -1;
         public Object getRoot() {
              return mRoot;
         public boolean isLeaf(Object node) {
              File f = (File) node;
              return (!f.isDirectory());
         public void removeTreeModelListener(TreeModelListener l) {
              mListeners.remove(l);
         public void valueForPathChanged(TreePath path, Object newValue) {
              //change the file system through the FileSystemTreeModel?
              TreeModelEvent ev = new TreeModelEvent(newValue, path.getPath());
              File f = (File) path.getPathComponent(0);
              boolean worked = f.renameTo(new File(f.getParent(), (String)newValue));
              if (!worked) {
                   JOptionPane.showMessageDialog(null, "Rename Operation Failed");
              } else {
                   for (TreeModelListener l : mListeners) {
                        l.treeNodesChanged(ev);
         public static class NodeRunner extends MouseAdapter {
              private JTree mTree;
              private OutputStream mOut;
              private OutputStream mErr;
              private String[] mExecFileTypes;
    //          public void fetchedAll(byte[] buf) {}
    //          public void fetchedMore(byte[] buf, int start, int end) {
    //               System.out.println(new String(buf, start, end - start));
              public NodeRunner (JTree tree) {
                   this(tree, System.out, System.err);
              public NodeRunner (JTree tree, OutputStream out, OutputStream err) {
                   mTree = tree;
                   mTree.addMouseListener(this);
                   mOut = out;
                   mErr = err;
              public void mouseClicked(MouseEvent me) {
                   if (me.getClickCount() == 2) {
                        File f = (File)mTree.getSelectionPath().getLastPathComponent();
                        if (f.isDirectory()) return;
                        if (mExecFileTypes != null) {
                             boolean canExec = false;
                             String extension = IOUtils.getFileExtension(f);
                             for (String s : mExecFileTypes) {
                                  if (s.equals(extension)) {
                                       canExec = true;
                                       break;
                             if (!canExec) return;
                        try {
                             String cmd = f.getAbsolutePath();
                             final Process p = Runtime.getRuntime().exec(cmd);
                             Runnable r = new Runnable() {
                                  public void run() {
                                       IOUtils.pipe(p.getInputStream(), mOut);
                             Thread t = new Thread(r);
                             t.start();
                             r = new Runnable() {
                                  public void run() {
                                       IOUtils.pipe(p.getErrorStream(), mErr);
                             t = new Thread(r);
                             t.start();
    //                         InfoFetcher in = IOUtils.loadData(p.getInputStream());
    //                         Thread t = new Thread(in);
    //                         t.start();
    //                         InfoFetcher err = IOUtils.loadData(p.getErrorStream());
    //                         t = new Thread(err);
    //                         t.start();
    //                         InfoFetcher.FetcherListener flin = new InfoFetcher.FetcherListener() {
    //                              public void fetchedAll(byte[] buf) {}
    //                              public void fetchedMore(byte[] buf, int start, int length) {
    //                                   try {
    //                                        mOut.write(buf, start, length);
    //                                   catch (IOException iox) {
    //                                        iox.printStackTrace();
    //                         in.addFetcherListener(this);
    //                         err.addFetcherListener(this);
                        catch (IOException iox) {
                             iox.printStackTrace();
         public static void addExecExecution(JTree tree) {
              new NodeRunner(tree);
         public static void addExecExecution(JTree tree, String[] execExtensions) {
              NodeRunner nr = new NodeRunner(tree);
              nr.mExecFileTypes = execExtensions;
         public static void addExecExecution(JTree tree, OutputStream out, OutputStream err) {
              new NodeRunner(tree, out, err);
         public static void addExecExecution(JTree tree, OutputStream out, OutputStream err, String[] execExtensions) {
              NodeRunner nr = new NodeRunner(tree, out, err);
              nr.mExecFileTypes = execExtensions;
         public static void main(String[] args) {
              File f = new File(".").getAbsoluteFile().getParentFile();
              //System.out.println(f.getName());
              FileSystemTreeModel tm = new FileSystemTreeModel();
              //FileSystemTreeModel tm = new FileSystemTreeModel(f);
              JTree tree = new JTree(tm);
              FileSystemTreeModel.addExecExecution(tree, new String[] {"exe", "bat", "jar"});
              DefaultTreeCellRenderer rend = new FileSystemTreeRenderer();
              tree.setCellRenderer(rend);
              //tree.setCellEditor(new DefaultTreeCellEditor(tree, rend));
              tree.setCellEditor(new DefaultTreeCellEditor(tree, rend, new FileSystemTreeEditor(tree, rend)));
              tree.setEditable(true);
              JScrollPane sp = new JScrollPane(tree);
              WindowUtilities.visualize(sp);

  • Can't open documents - File select screen just flashes and then disappears

    In Adobe Creative Suite 3 Design Standard - When I open Photoshop, Illustrator, etc. and then try to open a document from one of these programs, the screen where you would select the file to open just flashes and then disappears. This locks me out of the program because it is waiting for a response from me - I can't even exit the program. I have to go to the Task List and close the program from there. This is a new issue - Have had Creative Suite for a while. Does not happen in Word, Excel, etc. I have already tried removing and reinstalling the software - No change. I have minimized all other windows - Still cannot access the file selection screen.

    If you have an LCD monitor, make sure it is running at its maximum resolution. After the dialog disappears, try pressing Alt + Spacebar, then M and see if you can find it on the edge of the screen and move it in by pressing arrow keys, press one a few times, then the opposite to bring it back if it didn't show up.

  • Can not import my wav. file, message "unable to decode and import selected wav/mp3 file"

    Please help, i don't know how to import my wav file. I checked to see if the settings are compatible
    and it seems like them are. The wav file im trying to import is: 88kbps, 11kHz...

    I don't think so, if its not how do I get it to be?
    (Embedded image moved to file: pic07711.jpg)
    Jackie Stjepanovic
    Trainer
    Staff Development
    Automobile Customer Service (ACS)
    (310) 781-4627
                                                                                    Captiv8r                                                 
                 <[email protected]                                        
                 >                                                          To
                                           Jackie Stjepanovic             
                 11/23/2010 08:56          <[email protected]>
                 AM                                                         cc
                                                                                    Subject
                 Please respond to         Can not import my
                 clearspace-974018         wav. file, message "unable to  
                 851-110472-2-3295         decode and import selected wav/mp3
                 [email protected]         file"                          
                     dobe.com                                                                               
    Is it PCM encoded?
    Cheers... Rick  
    http://www.robowizard.com/pc.gif
    Helpful and Handy Links
    http://www.gooberguides.com/ProductPages/Captivate/Captivate5Foundations.htm
    http://www.Adobe.com/cfusion/mmform/index.cfm?name=wishform&product=5
    http://www.ShowMeSolutions.biz
    http://sorcererstone.wordpress.com/
    http://www.gooberguides.com

  • Key pressed in Jlist and selecting the item of key list accordingly

    Hi,
    I have a JList with the items in sorted order.Now I want that if a person presses any key (say K) then the first item starting with K should be selected.Hmmm I can do it by addding a key listener to the list and cheking all the items in the list ,by traversing through the whole lenght of JList and selecting the item if it starts with the character of the key pressed.
    But i was thinking if there is any better way to do that?
    Regards Amin

    see bugid: 4654916 - it does say that the the
    scrolling for the JList should now work with keyboard
    selection.I have the same problem. Thanx for the hint with the bugid. Saw a good workaround there with a simple subclass of JList. Works for me although it is annoying to subclass JList all the time. The bug seems not to be fixed in the 1.4.1 JDK.
    Andreas

  • I don't want Adobe to open up and be selected immediately. I work with iPhoto and Ipages etc and preview which needs to be my main application for my work , but need adobe reader for other files... how can I do this please?

    I don't want Adobe to open up and be selected immediately. I work with iPhoto and Ipages etc and preview which needs to be my main application for my work , but need adobe reader for other files... how can I do this please?

    loopiloo1 wrote:
    I don't want Adobe to open up and be selected immediately.
    Sorry, I don't understand this - you don't want Adobe [Reader] not to open when doing what?  On what operating system?

  • Make Record for folder and multi-selected files

    Hi,
    'Make Record' item disappeared in MENU for folders not for files.
    And it can't make record for multi-selected files.
    I can only make Record by one and one.
    How to make Records for folder and multi-selected files?
    Regards
    Kitae

    Programatically, only a single document at a time can be made a record :-
    makeRecord
    public Item makeRecord(long parentId,
    long docId,
    NamedValue[] attrs,
    AttributeRequest[] attributes)
    throws FdkException
    You could potentially through a custom workflow triggered on UserRequest allow multiple submitted documents to be made records through a custom BPEL process calling Content DB Web Services.
    Matt.

  • HT1660 when deleting music files from iTunes and you select Keep File, where is that file stored and how it is retireved?

    when deleting music files from iTunes and you select Keep File, where is that file stored and how it is retrieved?

    The file is just left where it was when it was connected to the library. Typically:
         <User>/Music/iTunes/iTunes Media/Music/<Artist>/<Album>/## <Name>.<Ext>
    If you want to add it back just drag it into iTunes. If you want to cull the files you kept previously add the entire iTunes Media folder back into iTunes (or use one of Doug's scripts that has the same effect), then delete (and don't keep) the recent additions.
    Note that warning/prompt is only issued when the files you are removing are located inside the designated iTunes Media folder.
    tt2

  • Consume MouseEvent to prevent JList and JTree from receiving?!

    I have a JTree and a JList where I have made the CellRenderer so that it has a "button" area. When this button is clicked, I want something to happen. This I have achieved just nicely with a MouseListener, as per suggestion from JavaDocs.
    However, the problem is that when a click is deemed to be within the "button", I do not want the tree or list to process it anymore. But doing e.consume(), both on mousePressed or mouseClicked (though it obviously is pressed the JList and JTree themselves listen to) doesn't do jack.
    How can I achieve this functionality?

    da.futt wrote:
    stolsvik wrote:
    Okay, I managed with a hack: It is the order of listeners that's the problem: The ListUI's MouseListener is installed before mine, and hence will get the MouseEvent before me, so it has already processed it when I get it, and hence consuming it makes no difference. No. Normally, listeners are notified latest-registered to earliest-registered. I don't remember seeing an exception to that rule in the core API. well, you are both right (or wrong ;-) - the rule is: the order of listener notification is undefined, it's an implementation detail which listeners must not rely on. "Anecdotical" experience is that AWTListeners are notified first-registered-first-served, while listeners to swing specific events are notified last-registered-first-served. Below is a snippet (formulated in context of SwingX convenience classes, too lazy ...) showing that difference.
    The latter probably stems from hefty c&p of notification by walking the EventListenerList: the earliest code was implemented very near the beginning of Swing when every little drop of assumed performance optimization was squeezed, such as walking from back to front. Using EventListenerList involves lots of code duplication ... so lazy devs as we all are, simply c&p'ed that loop and just changed the concrete event type and method name. More recently, as in the we-use-all-those-nifty-cool-language-features ;-) I've seen more usage of forEach loops (f.i. in beansbinding) so notification is back to first-in-first-served :-)
    Bottom line: don't rely on any sequence - if needed, use an eventBus (or proxy or however it's called) and define the order there. Darryl's suggestion is as close as we can get in Swing (as it's not supported) but not entirely safe: there's no way to get notified when listeners are added/removed and no hook where to plug-in such a bus into the ui-delegate where it would belong.
    Cheers
    Jeanette
    // output
    02.10.2009 14:21:57 org.jdesktop.swingx.event.EventOrderCheck$1 mousePressed
    INFO: first added mouseListener
    02.10.2009 14:21:57 org.jdesktop.swingx.event.EventOrderCheck$2 mousePressed
    INFO: second added mouseListener
    02.10.2009 14:21:58 org.jdesktop.swingx.event.EventOrderCheck$4 valueChanged
    INFO: second added listSelectionListener
    02.10.2009 14:21:58 org.jdesktop.swingx.event.EventOrderCheck$3 valueChanged
    INFO: first added listSelectionListener
    // produced by
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.util.logging.Logger;
    import javax.swing.JList;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    import org.jdesktop.swingx.InteractiveTestCase;
    import org.jdesktop.test.AncientSwingTeam;
    public class EventOrderCheck extends InteractiveTestCase {
        public void interactiveOrderAWTEvent() {
            JList list = new JList(AncientSwingTeam.createNamedColorListModel());
            MouseListener first = new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    LOG.info("first added mouseListener");
            MouseListener second = new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    LOG.info("second added mouseListener");
            list.addMouseListener(first);
            list.addMouseListener(second);
            ListSelectionListener firstSelection = new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (e.getValueIsAdjusting()) return;
                    LOG.info("first added listSelectionListener");
            ListSelectionListener secondSelection = new ListSelectionListener() {
                @Override
                public void valueChanged(ListSelectionEvent e) {
                    if (e.getValueIsAdjusting()) return;
                    LOG.info("second added listSelectionListener");
            list.addListSelectionListener(firstSelection);
            list.addListSelectionListener(secondSelection);
            showWithScrollingInFrame(list, "event order");
        @SuppressWarnings("unused")
        private static final Logger LOG = Logger.getLogger(EventOrderCheck.class
                .getName());
        public static void main(String[] args) {
            EventOrderCheck test = new EventOrderCheck();
            try {
                test.runInteractiveTests();
            } catch (Exception e) {
                e.printStackTrace();
    }

  • JTree cut and paste multiple child and ancestor nodes not function correct

    Hello i'm creating a filebrowser for multimedia files (SDK 1.22) such as .jpg .gif .au .wav. (using Swing, JTree, DefaultMutableTreeNode)
    The problem is I want to cut and paste single and multiple nodes (from current node til the last child "top-down") which partly functions:
    single nodes and multiple nodes with only one folder per hierarchy level;
    Not function:
    - multiple folders in the same level -> the former order gets lost
    - if there is a file (MMed. document) between folders (or after them) in the same level this file is put inside one of those
    I tried much easier functions to cope with this problem but every time I solve one the "steps" the next problem appears...
    The thing I don't want to do, is something like a LinkedList, Hashtable (to store the nodes)... because the MMed. filebrowser would need to much resources while browsing through a media library with (e.g.) thousands of files!
    If someone has any idea to solve this problem I would be very pleased!
    Thank you anyway by reading this ;)
    // part of the code, if you want more detailed info
    // @mail: [email protected]
    import java.util.Enumeration;
    import javax.swing.*;
    import javax.swing.tree.*;
    // var declaration
    static Enumeration en;
    static DefaultMutableTreeNode jTreeModel, lastCopiedNode, dmt, insert, insertParent, insertSameFolder;
    static String varCut;
    static int index= 0;
    static int counter = 0;
    /* cut function */
    if (actionCommand.equals ("cut"))
         // get the selected node (DefaultMutableTreeNode)
         lastCopiedNode = (DefaultMutableTreeNode)  selPath.getLastPathComponent ();
         // get the nodes in an Enumeration array (in top- down order)
         en = dmt.preorderEnumeration();
         // the way to make sure if it is a cut or a copied node
         varCut = "cut";
    /* paste function */
    if (actionCommand.equals ("paste"))
    // node is cut
    if (varCut == "cut")
    // is necessary for first time same folder case
    insertParent = dmt;
    // getting the nodes out of the array
    while(en.hasMoreElements())
         // cast the Object to DefaultMutableTreeNode
         // and get stored (next) node
         insert = (DefaultMutableTreeNode) en.nextElement();
    // check if the node is a catalogue when getRepresentation()
    // is a function of my node creating class (to know if it is
    // a folder or a file)
    if (insert.getRepresentation().equals("catalogue"))
         // check if a "folder" node is inserted
         if (index == 1)
              counter = 0;
              index = 0;
         System.out.println ("***index and counter reset***");
         // the node is in the same folder
         // check if the folder is in the same hierarchy level
         // -> in this case the insertParent has to remain
         if (insert.getLevel() == insertParent.getLevel())
              // this is necessary to get right parent folder
              insertSameFolder = (Knoten) insert.getParent();
              jTreeModel.insertNodeInto (insert, insertSameFolder, index);
    System.out.println (">>>sameFolderCASE- insert"+counter+"> " + String.valueOf(insert) +
              "\ninsertTest -> " + String.valueOf(insertTest)
              // set insertParent folder to the new createded one
              insertParent = insert;
              index ++;
         else // the node is a subfolder
              // insertNode
              jTreeModel.insertNodeInto (insert, insertParent, index);
              // set insertParent folder to the new createded one
              insertParent = insert;
    System.out.println (">>>subFolderCASE- insertParent"+counter+"> " + String.valueOf(insertParent) +
              "\ninsertParent -> " + String.valueOf(insertParent)
              index ++;
    else // the node is a file
         // insertNode
         jTreeModel.insertNodeInto (insert, insertParent, counter);
         System.out.println (">>>fileCASE insert "+counter+"> " + String.valueOf(insert) +
         "\ninsertParent -> " + String.valueOf(insertParent)
    counter ++;
    // reset index and counter for the next loop
    index = 0;
    counter = 0;
    // reset cut var
    varCut = null;
    // remove the node (automatically deletes subfolders and files)
    dmt.removeNodeFromParent (lastCopiedNode);
    // if node is a copied one
    if varCut == null)
         // insert copied node the same way as for cut one's
         // to make it possible to copy more than one node
    }

    You need to use a recursive copy method to do this. Here's a simple example of the copy. To do a cut you need to do a copy and then delete the source.
    import java.io.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.event.*;
    import java.util.*;
    public class CopyTree extends JFrame
         Container cp;
         JTree cTree;
         JScrollPane spTree;
         DefaultTreeModel cModel;
         CNode cRoot;
         JMenuBar menuBar = new JMenuBar();
         JMenu editMenu = new JMenu("Edit");
         JMenuItem copyItem = new JMenuItem("Copy");
         JMenuItem pasteItem = new JMenuItem("Paste");
         TreePath [] sourcePaths;
         TreePath [] destPaths;
         // =====================================================================
         // constructors and public methods
         CopyTree()
              super("Copy Tree Example");
              addWindowListener(new WindowAdapter()
              {public void windowClosing(WindowEvent evt){System.exit(0);}});
              // edit menu
              copyItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuCopy();}});
              editMenu.add(copyItem);
              pasteItem.addActionListener(new ActionListener()
              {public void actionPerformed(ActionEvent e){mnuPaste();}});
              editMenu.add(pasteItem);
              menuBar.add(editMenu);
              setJMenuBar(menuBar);
              buildModel();
              cp = getContentPane();
              cTree = new JTree(cModel);
              spTree = new JScrollPane(cTree);
              cp.add(spTree, BorderLayout.CENTER);
              pack();
         static public void main(String [] args)
              new CopyTree().show();
         // =====================================================================
         // private methods - User Interface
         private void mnuCopy()
              sourcePaths = cTree.getSelectionPaths();
         private void mnuPaste()
              TreePath sp, dp;
              CNode sn,dn;
              int i;
              destPaths = cTree.getSelectionPaths();
              if(1 == destPaths.length)
                   dp = destPaths[0];
                   for(i=0; i< sourcePaths.length;i++)
                        sp = sourcePaths;
                        if(sp.isDescendant(dp) || dp.isDescendant(sp))
                             JOptionPane.showMessageDialog
                                  (null, "source and destinations overlap","Paste", JOptionPane.ERROR_MESSAGE);
                             return;
                   dn = (CNode)dp.getLastPathComponent(); // the node we will append our source to
                   for(i=0; i< sourcePaths.length;i++)
                        sn = (CNode)sourcePaths[i].getLastPathComponent();
                        copyNode(sn,dn);
              else
                   JOptionPane.showMessageDialog
                        (null, "multiple destinations not allowed","Paste", JOptionPane.ERROR_MESSAGE);
         // recursive copy method
         private void copyNode(CNode sn, CNode dn)
              int i;
              CNode scn = new CNode(sn);      // make a copy of the node
              // insert it into the model
              cModel.insertNodeInto(scn,dn,dn.getChildCount());
              // copy its children
              for(i = 0; i<sn.getChildCount();i++)
                   copyNode((CNode)sn.getChildAt(i),scn);
         // ===================================================================
         // private methods - just a sample tree
         private void buildModel()
              int k = 0;
              cRoot = new CNode("root");
              cModel = new DefaultTreeModel(cRoot);
              CNode n1a = new CNode("n1a");
              cModel.insertNodeInto(n1a,cRoot,k++);
              CNode n1b = new CNode("n1b");
              cModel.insertNodeInto(n1b,cRoot,k++);
              CNode n1c = new CNode("n1c");
              cModel.insertNodeInto(n1c,cRoot,k++);
              CNode n1d = new CNode("n1d");
              cModel.insertNodeInto(n1d,cRoot,k++);
              k = 0;
              CNode n1a1 = new CNode("n1a1");
              cModel.insertNodeInto(n1a1,n1a,k++);
              CNode n1a2 = new CNode("n1a2");
              cModel.insertNodeInto(n1a2,n1a,k++);
              CNode n1a3 = new CNode("n1a3");
              cModel.insertNodeInto(n1a3,n1a,k++);
              CNode n1a4 = new CNode("n1a4");
              cModel.insertNodeInto(n1a4,n1a,k++);
              k = 0;
              CNode n1c1 = new CNode("n1c1");
              cModel.insertNodeInto(n1c1,n1c,k++);
              CNode n1c2 = new CNode("n1c2");
              cModel.insertNodeInto(n1c2,n1c,k++);
         // simple tree node with copy constructor
         class CNode extends DefaultMutableTreeNode
              private String name = "";
              // default constructor
              CNode(){this("");}
              // new constructor
              CNode(String n){super(n);}
              // copy constructor
              CNode(CNode c)
                   super(c.getName());
              public String getName(){return (String)getUserObject();}
              public String toString(){return  getName();}

  • Displaying the path of the file selected by a FileChooser in a TextField

    I'm just getting started with Swing. I developed a simple dialog box that has two text fields and two buttons. The objective is to open two files using those two buttons. I used FileChooser to select the files. Now, I want to display the path of the selected files in their corresponding TextFields. I use the following code to do that.
    final FileChooser fc1 = new FileChooser();
    final FileChooser fc2 = new FileChooser();
    final TextField tf1 = new TextField();
    final TextField tf2 = new TextField();
    private void button1ActionPerformed(ActionEvent evt)
                int returnVal1 = fc1.showOpenDialog(labelPhpFile);
                if (returnVal1 == JFileChooser.APPROVE_OPTION)
                    File file1 = fc1.getSelectedFile();
                    String fileName1 = file1.getName();               
                    String filePath1 = file1.getPath();
                    tf1.setText(filePath1);
    private void button2ActionPerformed(ActionEvent evt)
                int returnVal2 = fc2.showOpenDialog(labelPhpFile);
                if (returnVal2 == JFileChooser.APPROVE_OPTION)
                    File file2 = fc2.getSelectedFile();
                    String fileName2 = file2.getName();               
                    String filePath2 = file2.getPath();
                    tf2.setText(filePath2);
    }The above code works fine only for the first file. Mean the path of the file selected using fc1 is getting displayed in the tf1 TextField. But, the file selected using fc2 is not getting displayed tf2 TextField. Please help me.
    Thank you :)

    h1. The Ubiquitous Newbie Tips
    * DON'T SHOUT!!!
    * Homework dumps will be flamed mercilessly.
    * Have a quick scan through the [Forum FAQ's|http://wikis.sun.com/display/SunForums/Forums.sun.com+FAQ].
    h5. Ask a good question
    * Don't forget to actually ask a question. No, The subject line doesn't count.
    * Ask once
        - Don't Crosspost!
        - Two people answering one question independantly is a waste of there time.
    * Don't even talk to me until you've:
        (a) [googled it|http://www.google.com.au/] and
        (b) looked it up in [Sun's Java Tutorials|http://java.sun.com/docs/books/tutorial/] and
        (c) read the relevant section of the [API Docs|http://java.sun.com/javase/6/docs/api/index-files/index-1.html] and maybe even
        (d) referred to the JLS (for "advanced" questions).
    * [Good questions|http://www.catb.org/~esr/faqs/smart-questions.html#intro] get better Answers. It's a fact. Trust me on this one.
        - Lots of regulars on these forums simply don't read badly written questions. It's just too frustrating.
          - FFS spare us the SMS and L33t speak! Pull your pants up, and get a hair cut!
        - Often you discover your own mistake whilst forming a "Good question".
        - Many of the regulars on these forums will bend over backwards to help with a "Good question",
          especially to a nuggetty problem, because they're interested in the answer.
    * Improve your chances of getting laid tonight by writing an SSCCE
        - For you normal people, That's a: Short Self-Contained Compilable Example.
        - Short is sweet: No-one wants to wade through 5000 lines to find your syntax errors!
        - Often you discover your own mistake whilst writing an SSCCE.
        - Solving your own problem yields a sense of accomplishment ;-)
    h5. Formatting Matters
    * Post your code between a pair of &#123;code} tags
        - That is: &#123;code} ... your code goes here ... &#123;code}
        - This makes your code easier to read by preserving whitespace and highlighting java syntax.
        - Copy&paste your source code directly from your editor. The forum editor basically sucks.
        - The forums tabwidth is 8, as per [the java coding conventions|http://java.sun.com/docs/codeconv/].
          - Indents will go jagged if your tabwidth!=8 and you've mixed tabs and spaces.
          - Lines longer than 80 characters should be wrapped.
          - Proper indentation illustrates program logic.
    * Post your error messages between a pair of &#123;code} tags:
        - That is: &#123;code} ... errors here ... &#123;code}
        - To make it easier for us to find, Mark the erroneous line(s) in your source-code. For example:
            System.out.println("Your momma!); // <<<< ERROR 1
        - Note that error messages are rendered basically useless if the code has been
          modified AT ALL since the error message was produced.
        - Here's [How to read a stacktrace|http://www.0xcafefeed.com/2004/06/of-thread-dumps-and-stack-traces/].
    * The forum editor has a "Preview" pane. Use it.
        - If you're new around here you'll probably find the "Rich Text" view is easier to use.
        - WARNING: Swapping from "Plain Text" view to "Rich Text" scrambles the markup!
        - To see how a posted "special effect" is done, click reply then click the quote button.
    If you (the newbie) have covered these bases *you deserve, and can therefore expect, GOOD answers!*
    h1. The pledge!
    We the New To Java regulars do hereby pledge to refrain from flaming anybody, no matter how gumbyish the question, if the OP has demonstrably tried to cover these bases. The rest are fair game.

  • Close excel programmatically after user cancels file selection

    Greetings all. I apologize but I incorrectly posted this question on the wrong board originally so am posting it again here. I have a VI that I wrote with some help from this site that reads in as many user selected Flat Data Files as desired into Excel. The VI opens Excel, places each Flat Data File on one row and ends, allowing the user to manipulate the Excel data as desired. I have tested it without problems with up to 100 files at a time. The VI minimizes Excel at startup so that it will not block the Select File(s) dialogue. MY problem is this: If the user cancels the file selection, it returns an error and leaves Excel open. I understand how to handle the error, but have been unable to make Excel close automatically if the action is canceled. I have tried to invoke the Close without saving node with no luck... probably because I don't understand how to apply it. Ideally, I want to take the error number to a case statement, and if it is anything other than zero (0), meaning no error, I want Excel to close down. This will eventually be an executable so I need to make this right. Can anybody help? I have attached a zip file with the VI's and some sample Flat Data Files.
    Thanks
    Attachments:
    RTS Flat File Data.zip ‏103 KB

    If you want anything to run after an error you must clear the error status boolean from the error cluster. To do this use the bundle by name and set the status value to FALSE, take this output cluster into the function you wish to run.
    Andrew Alford
    Production Test Engineering Technologist
    Sustainable Energy Technologies
    www.sustainableenergy.com

  • How can I print multiple copies of the same photo onto one sheet of paper?  Do I have to Duplicate the photo in iPhoto and then select them all?

    How can I print multiple copies of the same photo onto one sheet of paper?  Do I have to Duplicate the photo in iPhoto and then select them all?

    no - you simply have to select the option to print mucliples of a photo on a page
    select the photo and go to the file menu ==> print - select the printer, paper size and print size and click customize - in the tool bar click on the settings icon (the gear looking thingy) and select "multiple of the same photo per page" and the preview will reflect this option showing a full page of the selected size photos
    LN

  • How can I load the selected XML File (Selected from a Listview) into the correct Textboxes?

    Right, so I have a windowsform with lots of Textboxes, where the user can type in Information, and then hit "Save", once its saved it goes into a sortof XML Format 
    <?xml version="1.0" encoding="utf-8"?>
    <!--Database-->
    <Case>
      <Person>l<Driver></Driver><License-Holder></License-Holder><Address></Address><Phone></Phone><Date-of-Birth></Date-of-Birth><Registration></Registration>
    Like that.
    Now, on my Startup Form (The main form) there is a Listview that I gave the name Objectlist1. This list displays ANY file located in a specific folder on my computer. This is also where the Saved files appear.
    The list also updates every 5th second so after you save it appears quickly.
    Now, the Files are saved using the content or Value of the first Textbox:
    Dim XmlWrt As XmlWriter = XmlWriter.Create("C:\Users\USER\Desktop\TESTFOLDER\" + Firsttextbox.Text, settings)
    So it appears in the folder and on the list with the value inserted in the first Textbox.
    My problem comes when I want to load this back (Or reverse the function if you will)
    Where I can go to the Objectlist1/Listview, either doubleclick a file or Mark a file, and hit my button "Retrieve"
    I want the Form where you could input all the values to show - which it does
    And the information from the XML/File saved to appear where it once was typed or inserted.
    Here is an example of the code used to save the values from the Textboxes;
    Private Sub Savebutton_Click(sender As Object, e As EventArgs) Handles Savebutton.Click
            If IO.File.Exists(Pholderbox.Text) = False Then
                Dim settings As New XmlWriterSettings()
                settings.Indent = True
                Dim XmlWrt As XmlWriter = XmlWriter.Create("C:\Users\USER\Desktop\TESTFOLDER\" + Pholderbox.Text, settings)
                With XmlWrt
                    ' Write the Xml declaration.
                    .WriteStartDocument()
                    ' CLIENT
                    ' Write a comment.
                    .WriteComment("Database")
                    ' Write the root element.
                    .WriteStartElement("Case")
                    ' Start our first person.
                    .WriteStartElement("Person")
                    .WriteString(Textbox1.Text)
                    ' The person nodes.
                    .WriteStartElement("Driver")
                    .WriteString(Textbox2.Text)
                    .WriteEndElement()
    I've tried multiple codesamples but they all give either "XML Not found" or such Overloads.
    This is the current code I used when trying to make it work
    Private Function ReadSettingsXML(ByVal path As String) As MySettings # On Debug It marks here and tells me it wasn't found.
            Dim thisSettingsInfo As New MySettings
            If My.Computer.FileSystem.FileExists(Objectlist1.SelectedItems.ToString) Then
                Dim settingsInfo = XElement.Load(Objectlist1.SelectedItems.ToString)
                If settingsInfo IsNot Nothing Then
                    For Each mainGroup As XElement In settingsInfo.Elements
                        If mainGroup.Name = "<Database>" AndAlso mainGroup.HasElements Then
                            For Each subGroup As XElement In mainGroup.Elements
                                If subGroup.Name = "<Person>" Then
                                    thisSettingsInfo.Textbox1 = subGroup.Value
                                ElseIf subGroup.Name = "<Driver>" Then
                                    thisSettingsInfo.Textbox2 = subGroup.Value
                                ElseIf subGroup.Name = "<Address>" Then
                                    thisSettingsInfo.Textbox3 = subGroup.Value
                                End If
                            Next
                        End If
                    Next
                Else
                    thisSettingsInfo = Nothing
                    Throw New Exception("The settings XML file is corrupt and cannot be read.")
                End If
            Else
                thisSettingsInfo = Nothing
                Throw New Exception("The settings XML file could not be located.")
            End If
            Return thisSettingsInfo
        End Function
        Private Sub LoadXML_Click(sender As Object, e As EventArgs) Handles LoadXML.Click
            Dim settings As New MySettings
            settings = ReadSettingsXML(Objectlist1.SelectedItems.ToString)
            If settings IsNot Nothing Then
                Dim sb As New System.Text.StringBuilder
                With settings
                    Caseworker.Textbox1.Text = .Person
                    Caseworker.Textbox2.Text = .Driver
                    Caseworker.Textbox3.Text = .Address
                End With
            End If
        End Sub
    Also, the "Caseworker" is the form where all the textboxes are located.
    Been stuck on this for two working days, so any help is highly appreciated 
    Codesamples are also highly welcome so I can see what the heck you did and find and answer to my problems.

    I found a code that might be close to what I'm looking, but as of this code used here, it looks for a static document that already exist and is located in the code.
    See this one here, checks for the XML file, and since I can't link one program to 1 file, when its gonna have and use 100's of files.
            If (IO.File.Exists("MyXML.xml")) Then
                Same here with the static document.
                Dim document As XmlReader = New XmlTextReader("MyXML.xml")
                While (document.Read())
                    Dim type = document.NodeType
                    'if node type was element
                    If (type = XmlNodeType.Element) Then
                        If (document.Name = "FirstName") Then
                            TextBox1.Text = document.ReadInnerXml.ToString()
                        End If
                        If (document.Name = "LastName") Then
                            TextBox2.Text = document.ReadInnerXml.ToString()
                        End If
                    End If
                End While
    Am I at least close here, people? 
    Can anyone help with the now critical issue I got?
    I basically need to change these two;
     If (IO.File.Exists("MyXML.xml")) Then
                Same here with the static document.
                Dim document As XmlReader = New XmlTextReader("MyXML.xml")
    To whatever value, so they read from the file SELECTED in my Listview
    Cos the program saves files according to the info inserted in textboxes, so it can have whatever name you can think of, I need the program to "find and load" that file, once its selected, and then once I hit Retrieve or LOAD or whatever button, it
    injects the info from the File to the correct Textboxes.
    And I think this will work to get the info in the right boxes;
     If (document.Name = "FirstName") Then
                            TextBox1.Text = document.ReadInnerXml.ToString()
                        End If
                        If (document.Name = "LastName") Then
                            TextBox2.Text = document.ReadInnerXml.ToString()
    Any good advise? I'm stranded here.

Maybe you are looking for

  • How to setup a Firefox update server on a Windows 2012 server?

    Are there any instructions available on how to setup a Firefox update server that can automatically download updates from the Mozilla site and users can then grab the updates from the internal server? I'm using wampserver so that I can utilize Apache

  • How do I remove a reflection from my photo slideshow?

    I have set up a slideshow on a photo page and published OK. However I have reflections under some images and not under others, regardless of whether I view via Safari or Firefox. Actually I would rather not have a reflection at all. I have read throu

  • System copy - CUA how to keep (merge) some of the old target system users ?

    Hi, can anyone suggest if the following is possible and if so, the best way to enable the following within a CUA landscape :- Standard SAP System Copy of Production to QA. Cleanup of "Production" user master records in the QA system to remove users n

  • Custom Table updation thru table control

    Hi All, My requirement is to update the custom table by creating a custom screen with table control,say my z table has 2 fields name1 and bukrs. if i enter the value in table control then i click the save icon these fields should get updated in the z

  • Tungsten T sync with Windows 7 64bit?

    I have tried many fixes and so far no success.  With bluetooth my HP recognizes the handheld but the palm will almost complete the tansaction but then asks me for the pass key for my PC.  I have no idea what that is.  I'm not stupid but right now I f