Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Having trouble with a JComboBox in a JFileChooser. Issue with removing elements and items.

  1. #1
    Member GoodbyeWorld's Avatar
    Join Date
    Jul 2012
    Location
    Hidden command post deep within the bowels of a hidden bunker somewhere under a nondescrip building
    Posts
    161
    My Mood
    Stressed
    Thanks
    14
    Thanked 25 Times in 25 Posts

    Angry Having trouble with a JComboBox in a JFileChooser. Issue with removing elements and items.

    I have no idea quite what it's doing in the ComboBoxModel section part with all the arrays of Object. I have tried what I thought should and have tried removing all the elements, hoping that would work, but it doesn't even remove them at all. They're still in there.

    Worse, it seems I need to call init() to show the new items, but, everything I've tried has made it so that the old items for the previous directories I've visited, still are there and I don't want that.



     
    import javax.swing.JFileChooser;
    import java.io.File;
    import javax.swing.JButton;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JOptionPane;
    import javax.swing.JComboBox;
    import javax.swing.event.DocumentListener;
    import javax.swing.event.DocumentEvent;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.Window;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.DefaultComboBoxModel;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JTextField;
    import javax.swing.MutableComboBoxModel;
    import javax.swing.SwingUtilities;
    import javax.swing.plaf.basic.BasicComboBoxEditor;
    import javax.swing.plaf.basic.BasicComboBoxRenderer;
    import javax.swing.plaf.basic.BasicComboPopup;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.JPanel;
    import javax.swing.JCheckBox;
    import javax.swing.BorderFactory;
     
     
    public class FileChooserWithDelete extends JFileChooser
    {
     
     
       private JIntelligentComboBox comboBox;
       private DefaultComboBoxModel dcm;
     
     
     
     
       public FileChooserWithDelete()
       {
          super("./");
          dcm = new DefaultComboBoxModel();
     
     
          java.io.File f = getCurrentDirectory();
     
          java.io.File[] files = f.listFiles();
     
          for (int i =0; i < files.length; i++)
          {
     
             dcm.addElement(new Object[] {files[i].getName(), "", 0});
     
          }
     
     
     
     
          comboBox = new JIntelligentComboBox(dcm);
     
     
          addPropertyChangeListener(
                new PropertyChangeListener() {
                   public void propertyChange(PropertyChangeEvent evt) {
                      if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
                         JFileChooser chooser = (JFileChooser) evt.getSource();
                         java.io.File oldDir = (java.io.File) evt.getOldValue();
                         java.io.File newDir = (java.io.File) evt.getNewValue();
     
                         java.io.File curDir = chooser.getCurrentDirectory();
                         System.out.println(curDir.getName());
     
     
     
                         //dcm.removeAllElements();
                         comboBox.removeAllItems();
                         dcm.removeAllElements();
     
     
     
     
                         java.io.File[] moreFiles = curDir.listFiles();
     
     
     
     
                         for (int i =0; i < moreFiles.length; i++)
                         {
     
     
     
                            dcm.addElement(new Object[] {moreFiles[i].getName(), "", 0});
     
     
     
                         }
     
     
                        // comboBox.init();
     
     
                      }
                   }
                });
     
     
     
     
          java.awt.Container cont = (java.awt.Container) (getComponents()[3]);
     
          java.awt.Container cont2 = (java.awt.Container) (cont.getComponents()[3]);
          java.awt.Container cont3 = (java.awt.Container) (cont.getComponents()[0]);
     
     
          cont3.remove(1);
     
          cont3.add(comboBox, 1);
     
       }
     
     
     
     
       protected class JIntelligentComboBox extends JComboBox {
     
          private List<Object> itemBackup = new ArrayList<Object>();
     
          public JIntelligentComboBox(MutableComboBoxModel aModel) {
             super(aModel);
             init();
          }
     
          private void init() {
             this.setRenderer(new searchRenderer());
             this.setEditor(new searchComboBoxEditor());
             this.setEditable(true);
             int size = this.getModel().getSize();
             Object[] tmp = new Object[this.getModel().getSize()];
             for (int i = 0; i < size; i++) {
                tmp[i] = this.getModel().getElementAt(i);
     
     
                itemBackup.add(tmp[i]);
             }
             this.removeAllItems();
             this.getModel().addElement(new Object[]{"", "", 0});
             for (int i = 0; i < tmp.length; i++) {
                this.getModel().addElement(tmp[i]);
             }
             final JTextField jtf = (JTextField) this.getEditor().getEditorComponent();
             jtf.addKeyListener(
                   new KeyAdapter() {
     
                      @Override
                      public void keyReleased(KeyEvent e) {
                         searchAndListEntries(jtf.getText());
                      }
                   });
          }
     
          @Override
          public MutableComboBoxModel getModel() {
             return (MutableComboBoxModel) super.getModel();
          }
     
          private void searchAndListEntries(Object searchFor) {
             List<Object> found = new ArrayList<Object>();
             for (int i = 0; i < this.itemBackup.size(); i++) {
                Object tmp = this.itemBackup.get(i);
                if (tmp == null || searchFor == null) {
                   continue;
                }
                Object[] o = (Object[]) tmp;
                String s = (String) o[0];
     
     
                if (s.startsWith((String) searchFor))
                   found.add(new Object[] {((Object[]) tmp) [0],  searchFor, ((Object[]) tmp) [2]});}
     
             this.removeAllItems();
             this.getModel().addElement(new Object[]{searchFor, searchFor, 0});
             for (int i = 0; i < found.size(); i++) {
                this.getModel().addElement(found.get(i));
             }
             this.setPopupVisible(true);
             // [url=http://stackoverflow.com/questions/7605995]java - Set Size of JComboBox PopupMenu - Stack Overflow[/url]
             BasicComboPopup popup =
                (BasicComboPopup) this.getAccessibleContext().getAccessibleChild(0);
             Window popupWindow = SwingUtilities.windowForComponent(popup);
             Window comboWindow = SwingUtilities.windowForComponent(this);
     
             if (comboWindow.equals(popupWindow)) {
                Component c = popup.getParent();
                Dimension d = c.getPreferredSize();
                c.setPreferredSize(d);
     
             } 
             else {
                popupWindow.pack();
             }
          }
     
          class searchRenderer extends BasicComboBoxRenderer {
     
             @Override
             public Component getListCellRendererComponent(JList list,
                 Object value, int index, boolean isSelected, boolean cellHasFocus) {
                if (index == 0) {
                   setText("");
                   return this;
                }
                Object[] v = (Object[]) value;
                String s = (String) v[0];
                String lowerS = s.toLowerCase();
                String sf = (String) v[1];
                String lowerSf = sf.toLowerCase();
                List<String> notMatching = new ArrayList<String>();
     
                if (!sf.equals("")) {
                   int fs = -1;
                   int lastFs = 0;
                   while ((fs = lowerS.indexOf(lowerSf, (lastFs == 0) ? -1 : lastFs)) > -1) {
                      notMatching.add(s.substring(lastFs, fs));
                      lastFs = fs + sf.length();
                   }
                   notMatching.add(s.substring(lastFs));
                }
                String html = "";
                if (notMatching.size() > 1) {
                   html = notMatching.get(0);
                   int start = html.length();
                   int sfl = sf.length();
                   for (int i = 1; i < notMatching.size(); i++) {
                      String t = notMatching.get(i);
                      html += "<b style=\"color: black;\">"
                         + s.substring(start, start + sfl) + "</b>" + t;
                      start += sfl + t.length();
                   }
                }
                this.setText("<html><head></head><body style=\"color: gray;\">"
                   + html + "</body></head>");
                return this;
             }
          }
     
          class searchComboBoxEditor extends BasicComboBoxEditor {
     
             public searchComboBoxEditor() {
                super();
             }
     
             @Override
             public void setItem(Object anObject) {
                if (anObject == null) {
                   super.setItem(anObject);
                } 
     
     
                else {
                   Object[] o = (Object[]) anObject;
                   super.setItem(o[0]);
                }
     
     
             }
     
             @Override
             public Object getItem() {
                return new Object[]{super.getItem(), super.getItem(), 0};
             }
          }
       }
     
     
    }



    I found some of this online and had to use it as is. I'm not sure what the itemBackup object is doing. I'm wondering if that's part of the reason it's not ever removing anything.

    In the PropertyChangeListener, I thought I told it to remove all the items and then add the elements from the current directory, but it's not adding the new ones and the old ones are still there.

    I've tried both calling removeAllElements() from the model and removeAllItems() on the combo box itself, but the old stuff is still there.
    Last edited by GoodbyeWorld; December 12th, 2013 at 01:29 PM. Reason: removed shameful rudeness


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Having trouble with a JComboBox in a JFileChooser. Issue with removing elements and items.

    You start your post complaining about the help you've received from people who are doing this for free in their spare time.

    You then say that you got this code from online and pasted it in without really understanding what it's doing.

    Then you post a ton of code and expect somebody else to debug it for you.

    Nope.

    I think you know that this isn't going to work, but you're just frustrated. We've all been there, so take a couple days to cool off, and come back with a question that we can help you with.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. The Following User Says Thank You to KevinWorkman For This Useful Post:

    GregBrannon (December 11th, 2013)

  4. #3
    Member GoodbyeWorld's Avatar
    Join Date
    Jul 2012
    Location
    Hidden command post deep within the bowels of a hidden bunker somewhere under a nondescrip building
    Posts
    161
    My Mood
    Stressed
    Thanks
    14
    Thanked 25 Times in 25 Posts

    Default Re: Having trouble with a JComboBox in a JFileChooser. Issue with removing elements and items.

    I don't quite get why it needs to have Object arrays as elements. However, it does have all of the items it should, it's just not displaying them.

    It appears to be in the method searchAndListEntries that things are going wrong.

    I had a println before the stuff in the method and it was looking in the right directory before that as it is storing all the correct items. However, I had another println at the end of the method and now the stuff suddenly is only showing stuff from the old directory in the find results.


     for (int i = 0; i < this.itemBackup.size(); i++) {
                Object tmp = this.itemBackup.get(i);
                if (tmp == null || searchFor == null) {
                   continue;
                }
                Object[] o = (Object[]) tmp;
                String s = (String) o[0];
     
     
                if (s.startsWith((String) searchFor))
                   found.add(new Object[] {((Object[]) tmp) [0],  searchFor, ((Object[]) tmp) [2]});}
     
     
     
     
             this.removeAllItems();
             this.getModel().addElement(new Object[]{searchFor, searchFor, 0});
             for (int i = 0; i < found.size(); i++) {
                this.getModel().addElement(found.get(i));
             }


    itemBackUp has the correct things in it because I checked before it went to the for loop.


    It seems to be going wrong somewhere in here.

  5. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Having trouble with a JComboBox in a JFileChooser. Issue with removing elements and items.

    Why the 'tude, Dude? How's that going to help?

    I reviewed all of your started threads requesting help with Java that were not marked SOLVED or social posts, and none of them included an SSCCE. None. If I missed it, please post a link.

    Post your own code and explain what you need help with. None of your posts in this thread describe what the program should do, what it does do that you'd like to change, or what you need help with. What's your question?

  6. #5
    Member GoodbyeWorld's Avatar
    Join Date
    Jul 2012
    Location
    Hidden command post deep within the bowels of a hidden bunker somewhere under a nondescrip building
    Posts
    161
    My Mood
    Stressed
    Thanks
    14
    Thanked 25 Times in 25 Posts

    Default Re: Having trouble with a JComboBox in a JFileChooser. Issue with removing elements and items.

    Quote Originally Posted by GregBrannon View Post
    Why the 'tude, Dude? How's that going to help?

    I reviewed all of your started threads requesting help with Java that were not marked SOLVED or social posts, and none of them included an SSCCE. None. If I missed it, please post a link.

    Post your own code and explain what you need help with. None of your posts in this thread describe what the program should do, what it does do that you'd like to change, or what you need help with. What's your question?

    I don't know what a SSCCE is. I thought it was a program that was a short as could be made that included the problem, and, if possible, compiled.


    This one doesn't have a main method, true. I forgot to put that. I forgot that I had it in a package.

    The thing is that I was trying to replace the JTextField in the JFileChooser class with a JComboBox. It was going to display all files (in the current directory, which is what I'm having problems with and hence why I made a separate thread on this from the one I started earlier that asked how to set it up.) The code that I somebody, at Stack Overflow, recommended java - Set Size of JComboBox PopupMenu - Stack Overflow was good for what I was trying to do, save that it involved a simple letter pattern instead of Files in a Directory.

    I got that to display it and it was working. The drawback was that it was only showing the current directory. The feature was supposed to be a suggestion combo box that, like the one in Windows stuff and lots of other things like Firefox, will add to the combo box all the files that, in the current directory, start with the characters in the JComboBox.

    This feature DOES work if I always stay in the current directory. However, if I move up or down in the file hierarchy, it will still show the first one, and I could move many up or down and it would still show the one that it started with.

    I tried calling the init() method, which did work, but had the nasty drawback of keeping everything in the old directories, though it did show the new stuff.


    Wow, that was it. I spent hours on that and couldn't figure it out.





    I admit, the part of the Object arrays in the ComboBoxModel is a bit confusing. (Sadly, this has no comments explaining what they were doing.) Why didn't they just use Object instead? (Was it part of an interface requirement?)


    I tried figuring out where it's going wrong. Something in the init() method will help it find the stuff in the new directories but calling init() again isn't a fix, and indeed breaks it in some ways.


    All of the objects seem to be working. It's somewhere in the searchAndListEntries method that it's going wrong.


    Even stranger, at some point in the execution, it can't find anything at all it seems. It just lost the data. (Though maybe I fixed that.)



    Maybe I'm wrong, but it almost seems to me that the issue likely isn't what IS in there that's causing this but what ISN'T in there but should be that is.


    ------Update-------


    I think I saw the problem. itemBackup is never changing after it's first initialized. Hence why it was only showing the first directory and never changing.


    It also explained why if I called init(), it showed both as it never was removing the old ones from itemBackup but was causing it now to add the new ones.

Similar Threads

  1. [SOLVED] Using JComboBox in JFileChooser and having problems
    By GoodbyeWorld in forum What's Wrong With My Code?
    Replies: 5
    Last Post: December 9th, 2013, 02:44 PM
  2. Disable items in JComboBox or ?
    By JavaCoderJ in forum Object Oriented Programming
    Replies: 1
    Last Post: October 26th, 2013, 07:58 PM
  3. Need some help with removing and finding items from an ArrayList
    By bankston13 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: August 30th, 2012, 08:51 PM
  4. (jComboBox, JTextField, jFileChooser) as table editor overrides the refrences!
    By campusGraphics in forum What's Wrong With My Code?
    Replies: 0
    Last Post: June 15th, 2012, 11:20 AM
  5. JComboBox help again but different help 75+ items in it
    By derekxec in forum AWT / Java Swing
    Replies: 7
    Last Post: August 27th, 2011, 06:53 PM

Tags for this Thread