0

I managed to get a delete button on a JFileChooser. I figured out where to put the button. In the process, I figured out, by messing with the getComponents() method, where the JTextField where the file is searched for and replaced it with a JComboBox. The plan is to get it to list all the files that begin with the text in the first row, the only one that can be edited on the JComboBox, otherwise it's uneditable, and it could select an item in another row and it would set the text of the item at the first row to the text of that item. (And also update the JCombobBox, though I don't think I implemented that part yet, though a simple method call should do that, but, anyway, I tried posting this on Java Programming Forums.

It's showing the items in there, but it's not letting it update with the typing. It is, instead, showing all the items in the directory. Also, when I go to select an item, it removes the first row and sets the text of the first row to the item. However, it now makes the first row uneditable I think or does something wacky.

It is removing the first row because the brilliant people who developed the JComboBox class couldn't bother to make a setItmeAt(Object item, int index) method, only a getItemAt(int index). So I had to get the text of the item, put it in a variable, remove the item at the first row, and then readd at the first row an item that has the text of the selected item.

I fear that maybe my code was too long, so I made it shorter, though even doing that today got no results at the Java Programming Forums, as the issue is with the JComboBox and the File class and stuff.

package addressbook.gui;

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;

public class FileChooserWithDelete extends JFileChooser
{

   private String textFieldString;
   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});

      }


      JButton delete = new JButton("Delete");
      delete.setToolTipText("Delete file");

      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();



                     java.io.File[] moreFiles = curDir.listFiles();

                     System.out.println("Obama is a loser!");


                     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);





      delete.addActionListener(
            new ActionListener()
            {




               public void actionPerformed(ActionEvent e)
               {

                  File f= getSelectedFile();

                  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]);
                  //javax.swing.JTextField jtf = (javax.swing.JTextField) (cont3.getComponents()[1]);

                  String text = (String) comboBox.getItemAt(0);

                  if (f == null)
                     f = new File("./" + text);



                  int option =  JOptionPane.showConfirmDialog(null, "Are you sure you wnat to delete?", "Delete file " + f.getName() + "?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

                  if (option == JOptionPane.YES_OPTION)
                  {

                     if (!f.exists() || text == null)
                     {
                        JOptionPane.showMessageDialog(null, "File doesn't exist.", "Could not find file.", JOptionPane.ERROR_MESSAGE);
                        cancelSelection();

                     }

                     else
                     {
                        f.delete();

                        cancelSelection();
                     }





                  }
               }});



      cont2.setLayout(new java.awt.FlowLayout());


      //((java.awt.Container) (getComponents()[3])).add(delete);
      cont2.add(delete);

      //cont2.add(delete);





   }




   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.matches("(?i).*" + searchFor + ".*")) {
               found.add(new Object[]{
                      ((Object[]) tmp)[0], searchFor, ((Object[]) tmp)[2]
                  });
            }
         }

         */

            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);
         // http://stackoverflow.com/questions/7605995
         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};
         }
      }
   }

   public JTextField getComboBoxTextField()
   {

      final JTextField jtf = (JTextField) comboBox.getEditor().getEditorComponent();

      return jtf;

   }

    public static void main(String[] args)
   {

     FileChooserWithDelete fcwd = new FileChooserWithDelete();

   fcwd.showOpenDialog(null);


}  
}

The link to the page at the java programming forum is here.

MongooseLover
  • 95
  • 1
  • 11
  • Code reformatted and modified to correct minor syntactical errors; don't ignore exceptions. – trashgod Dec 03 '13 at 09:52
  • Do you know what's going wrong? I'm baffled. I wish there was a setItemAt(Object obj, int index) method. Then I wouldn't have to remove. I'll bet that is part of the issue, the removing. – MongooseLover Dec 03 '13 at 19:58
  • I'd look at working with the `DefaultComboBoxModel`, which implements `insertElementAt()`. – trashgod Dec 03 '13 at 23:05
  • You're right, it does seem to be going to that exception quite often. However, if I don't catch it, it'll always crash. – MongooseLover Dec 03 '13 at 23:21
  • It seems to be throwing the exception when it hits this line: comboBox.removeItemAt(0); (How do you get line breaks in here?) – MongooseLover Dec 03 '13 at 23:28
  • I used insertElementAt() and it is still acting the same was as when I used insertItemAt(). Plus, I still have to remove the item I think. Plus, it is giving me a compile message now that I'm using unsafe or unchecked operations. – MongooseLover Dec 03 '13 at 23:43
  • It may be worth editing your question to include an [sscce](http://sscce.org/) that shows your current approach. – trashgod Dec 04 '13 at 00:08
  • SSCCE? This is a SSCCE. I admit, I've come to hate that term and feel it should be banned. (People seem to harp on it too much.) However, I made it as close to the issue (it was an even bigger program earlier and I paired it down.) What do you want me to do? I cannot think of a way to pair it down anymore than it already is. – MongooseLover Dec 04 '13 at 00:40
  • I added the printlns and stuff. (Why is it telling me to avoid extended discussion and recommending that I chat but then telling me that I don't have enough reputation to chat yet?) It seems to be going glitchy inside the ActionListener at comboBox.removeItemAt(0) or thereabouts because it's not printing out more than "Item count: 1". – MongooseLover Dec 04 '13 at 00:50
  • It seems to be going into the ActionListener twice when I just enter one character. That is odd. Should I be using an ItemListener instead? item count here: 1 Insert update Method called. Remove Update Went into Action Listener Item count valie is : 0 Item count: 0 Exception Method called. Went into Action Listener Item count valie is : 0 Item count: 0 Exception Plus, it seems to be having 0 items a lot. Why is that? – MongooseLover Dec 04 '13 at 01:02
  • Sorry, I have no particular insight; the edit may garner attention and help you refine your question; also consider `Action`, shown [here](http://stackoverflow.com/a/4039359/230513) in a menu & toolbar context, to populate your combo's model. – trashgod Dec 04 '13 at 03:06
  • Where would I add the Action? Also, I don't see a way, either in JCombobBox or DefaultComboBoxModel to reset the elements, either individually or collectively. I have to either recreate the model or the combobox itself using "new" and using an ArrayList and the toArray to get the files. When I went that route, now it lets me type, but it is no longer adding stuff to the list below. I have a larger class that I keep editing. I've been copying and pasting the relevant stuff into the SSCCE. – MongooseLover Dec 04 '13 at 18:49
  • I not sure what else to suggest; you may have an [*XY problem*](http://meta.stackexchange.com/q/66377/163188); if so, it may help to critically examine the problem you're actually trying to solve. – trashgod Dec 04 '13 at 18:54
  • What route do you recommend that I go then if my solution route isn't the best way to do it? You mentioned the DefaultComboBoxModel and Action, but how is that going to help? I wish there was a setConten() method inside either the JComboBox or a the DefaultComboBoxModel, but the only way I can think of, going either route, is to reinstantiate the JComboBox or its model using "new" and passing an array created from an ArrayList. However, that route lets you type but won't add. The other route adds, albeit everything, but won't let you type. – MongooseLover Dec 04 '13 at 21:18
  • Are you looking for something like [this](http://stackoverflow.com/q/7604005/230513). – trashgod Dec 04 '13 at 23:57
  • Yes! (I think more along those lines.) P.S. How do you put code comments in the answers in the replies in here? I cannot even figure out how to add a line break in here because when I hit enter, it submits.) – MongooseLover Dec 05 '13 at 02:36
  • Thanks, it worked great. (Though, sometimes it may be cutting off some lines in the JFileChooser comboBox.) Also, I don't quite know what to do if the directory changes. It will not look at the new directory that the file chooser has moved to, but will look at the original one that was there when the JFileChooser was open. I did use the example you've got. Now, I'm going to edit the code above to include the newest stuff. – MongooseLover Dec 05 '13 at 05:35

2 Answers2

1

You may be able to adapt the approach examined here. For notification, you may be able to leverage an existing JFileChooser event, as shown here. Alternatively, you can define your own PropertyChangeEvent, as shown here.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • Ok, I tried the PropertyChangeEvent route and it still is only showing the items in the old directory, not the newer one. Worse, sometimes it can't find the directories in the original. – MongooseLover Dec 06 '13 at 00:08
  • What events did you look at? – trashgod Dec 06 '13 at 02:27
  • PropertyChangeEvent. After calling the init() method, now it does update, but, it also will keep around the stuff from any other directories that it visited and I don't know how to fix that. I updated the code above again. – MongooseLover Dec 06 '13 at 05:04
  • My platform's chooser UI has different numbering. You may have to use your own [file browser](http://codereview.stackexchange.com/q/4446). – trashgod Dec 06 '13 at 11:50
  • What do you mean different numbering? – MongooseLover Dec 06 '13 at 19:31
  • Your sscce throws aioobe. – trashgod Dec 06 '13 at 19:34
  • I don't think the new one above throws aioobe. – MongooseLover Dec 06 '13 at 19:37
  • While File Browser is cool, I think it only would work on Windows platforms. How else could it use Notepad to open a file selected? – MongooseLover Dec 06 '13 at 19:38
  • Strangely, in addition to sometimes adding all the directories it visits, later, it either loses everything or has become so small that I can't scroll it anymore. And I don't know why and can't make an SSCCE this time as the code is even bigger, though I can say that it's not anything with the delete button that's doing this. – MongooseLover Dec 06 '13 at 20:26
  • `Desktop#open()` is cross-platform. – trashgod Dec 06 '13 at 21:42
  • Oh, it is. (Is there a way to make the computer open, say, a text file, when downloaded, with a jar file? Was also wondering that.) Anyway, Desktop.open will open it with a Windows or other OS affiliated file, which might be good if you're trying to make a java Windows Explorer or something but seems kind of silly if you're going to read the contents of a text file or something in to have your program do something specific with it. (i.e., it would be pretty useless to have the program open Windows Notepad if you're trying to select the file to read it into a Java tabbed notepad.) – MongooseLover Dec 06 '13 at 22:06
0

I have got it to work. However, there is a problem. The following lines are causing it to make ALL of my popups (i.e. JPopupMenu, JMenu, etc), scrunched so that you can't really read the titles on them.

The following lines seem to be the culprit.

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();
         }

What is that bit doing? When I take it out, it gets rid of the error.

package addressbook.gui;

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 String textFieldString;
   private JIntelligentComboBox comboBox;
   private DefaultComboBoxModel dcm;
   private JCheckBox read, write, execute;



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

      }


      JButton delete = new JButton("Delete");
      delete.setToolTipText("Delete file");

      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();




                     System.out.println("Obama is a loser!");







                     for (int i =0; i < moreFiles.length; i++)
                     {



                        dcm.addElement(new Object[] {moreFiles[i].getName(), "", 0});
                        //comboBox.insertItemAt(moreFiles[i].getName(), i);


                     }


                     for (int i =0; i < comboBox.getItemCount(); i++)
                     {
                        System.out.println(java.util.Arrays.toString((Object[]) comboBox.getItemAt(i)));


                     }

                    // comboBox.init();
                  */

                     comboBox.updateFiles();


                  }
               }
            });




      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]);


      read = new JCheckBox("Read");
      write = new JCheckBox("Write");
      execute = new JCheckBox("Execute");


      JPanel checkBoxPanel = new JPanel();
      checkBoxPanel.setBorder(BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));



      cont3.remove(1);

      cont3.add(comboBox, 1);


      checkBoxPanel.setLayout(new java.awt.FlowLayout());
      checkBoxPanel.add(read);
      checkBoxPanel.add(write);
      checkBoxPanel.add(execute);

      read.setEnabled(false);
      write.setEnabled(false);
      execute.setEnabled(false);


      addPropertyChangeListener(
            new PropertyChangeListener() {

               public void propertyChange(PropertyChangeEvent e2)
               {

                  if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY
                              .equals(e2.getPropertyName())) {
                     JFileChooser chooser = (JFileChooser)e2.getSource();
                     File oldFile = (File)e2.getOldValue();
                     File newFile = (File)e2.getNewValue();

                              // The selected file should always be the same as newFile
                     File curFile = chooser.getSelectedFile();

                     try
                     {

                        if (curFile.canRead())
                        {

                           read.setSelected(true);

                        }

                        else
                        {
                           read.setSelected(false);

                        }

                        if (curFile.canWrite())
                        {
                           write.setSelected(true);
                        }

                        else
                        {
                           write.setSelected(false);
                        }

                        if (curFile.canExecute())
                        {
                           execute.setSelected(true);

                        }

                        else
                        {
                           execute.setSelected(false);

                        }
                     }

                     catch(NullPointerException npe)
                     {

                        return;
                     }


                  } 



               }

            });




      delete.addActionListener(
            new ActionListener()
            {




               public void actionPerformed(ActionEvent e)
               {

                  File f= getSelectedFile();

                  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]);
                  //javax.swing.JTextField jtf = (javax.swing.JTextField) (cont3.getComponents()[1]);

                  String text = (String) comboBox.getItemAt(0);

                  if (f == null)
                     f = new File("./" + text);



                  int option =  JOptionPane.showConfirmDialog(null, "Are you sure you wnat to delete?", "Delete file " + f.getName() + "?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

                  if (option == JOptionPane.YES_OPTION)
                  {

                     if (!f.exists() || text == null)
                     {
                        JOptionPane.showMessageDialog(null, "File doesn't exist.", "Could not find file.", JOptionPane.ERROR_MESSAGE);
                        cancelSelection();

                     }

                     else
                     {
                        f.delete();

                        cancelSelection();
                     }





                  }
               }});



      cont2.setLayout(new java.awt.FlowLayout());


      //((java.awt.Container) (getComponents()[3])).add(delete);
      cont2.add(delete);

      cont2.add(checkBoxPanel);





   }




   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 updateFiles()
      {

         itemBackup.clear();


         java.io.File f = getCurrentDirectory();

         java.io.File[] files = f.listFiles();

         for (int i =0; i < files.length; i++)
         {

            itemBackup.add(new Object[] {files[i].getName(), "", 0});

         }





      }
      private void searchAndListEntries(Object searchFor) {
         List<Object> found = new ArrayList<Object>();

         for (int i =0; i < itemBackup.size(); i++)
         {

            System.out.println(java.util.Arrays.toString((Object[])itemBackup.get(i)));

         }



         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.matches("(?i).*" + searchFor + ".*")) {
               found.add(new Object[]{
                      ((Object[]) tmp)[0], searchFor, ((Object[]) tmp)[2]
                  });
            }
         }

         */




            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);

         // http://stackoverflow.com/questions/7605995\

         /*
         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();
         }
         */

         System.out.println("break");

         for (int i =0; i < found.size(); i++)
         {

            System.out.println(java.util.Arrays.toString((Object[]) found.get(i)));


         }
      }

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

   public JTextField getComboBoxTextField()
   {

      final JTextField jtf = (JTextField) comboBox.getEditor().getEditorComponent();

      return jtf;

   }
}
MongooseLover
  • 95
  • 1
  • 11