Learn how easy it is to sync an existing GitHub or Google Code repo to a SourceForge project! See Demo

Close

Searching other Swing components

garbersb
2007-02-07
2013-04-25
  • garbersb
    garbersb
    2007-02-07

    The swing classes allow you to search a JTextArea or anything that extends a JTextArea by using the JTextComponentSpellChecker classes spellCheck method.  It takes a JTextComponent.  I have a JList that renderes JTextAreas.  The reason I do this is that I want multiple rows of space when someone adds values to my list.  However, when I pass in my special rendererer it is not able to highlight the words OR change the words dynamically.  I have been trying to figure out how to do this with my existing code.  I have attached my ListUtility class which is a list that has a special renderer.  The special renderer since it extends JTextArea is what I am passing into the JTextComponentSpellCheckers spellCheck method.  It will actually find the misspelt words but will NOT change them within the app.  Any help would be greatly appreciated.

    /////List Utility Class
    package com.indstudy.gui;

    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;

    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JList;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.ListCellRenderer;
    import javax.swing.ListSelectionModel;
    import javax.swing.border.TitledBorder;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;

    /**
    * Utility class used to display a list.  this will also
    * allow a user to add and remove String values to this list.
    */
    public class ListUtility extends JPanel implements ActionListener, ListSelectionListener {

        /** ScrollPane for our List */
        JScrollPane scrollPaneList = null;
       
        /** List */
        JList list = null;
       
        /** DefaultListModel */
        DefaultListModel defaultListModel = null;
       
        /** Button Add */
        JButton buttonAdd = null;
       
        /** Button Remove */
        JButton buttonRemove = null;
       
        /** Button Edit */
        JButton buttonEdit = null;
       
        /** Global name value */
        String name = null;
       
        /** Global array value that will be used to ask the user to select one.*/
        String[] values = null;
       
       
        public ListUtility(String name, boolean specialrenderer, String[] values) {
            this(name, specialrenderer, 600, 100, 0, 1, -1);
            this.values = values;
        }

        public ListUtility(String name, boolean specialrenderer) {
            this(name, specialrenderer, 600, 100, 0, 1, -1);       
        }

        public ListUtility(String name, boolean specialrenderer, int width, int height) {
            this(name, specialrenderer, width, height, 0, 1, 2);       
        }

        public ListUtility(String name, boolean specialrenderer, int firstLetterMnemonic, int secondLetterMnemonic, int thirdLetterMnemonic) {
            this(name, specialrenderer, 600, 100, 0, 1, 2);
        }
        /**
         * Main Constructor that will end up creating a component that will allow a user to add and remove
         * String values to a particular list.
         * @param name Name of the Component we are concerned with.
         */
        public ListUtility(String name, boolean specialrenderer, int width, int height, int firstLetterMnemonic, int secondLetterMnemonic, int thirdLetterMnemonic) {
            this.name = name;
           
            //We will then end up creating our Assumptions List
            JPanel panelButtons = new JPanel();
            panelButtons.setLayout(new GridLayout(3, 1));
           
            //To set the mnemonic keys we will get the fist and
            //second letters of the name passed in
            char firstLetterOfName = name.charAt(firstLetterMnemonic);
            char secondLetterOfName = name.charAt(secondLetterMnemonic);
            char thirdLettorOfName = 'z';
            if (thirdLetterMnemonic != -1) {
                thirdLettorOfName = name.charAt(thirdLetterMnemonic);
            }
           
            if (firstLetterOfName == 'A' || secondLetterOfName == 'A') {
                firstLetterOfName = name.charAt(1);
                secondLetterOfName = name.charAt(2);
            }
           
            buttonAdd = new JButton("Add " + name);
            buttonAdd.setMnemonic(firstLetterOfName);
            buttonAdd.addActionListener(this);
            panelButtons.add(buttonAdd);
           
            buttonRemove = new JButton("Remove " + name);
            buttonRemove.setMnemonic(secondLetterOfName);
            buttonRemove.addActionListener(this);
            panelButtons.add(buttonRemove);
           
            if (thirdLetterMnemonic != -1) {
            buttonEdit = new JButton("Edit " + name);
            buttonEdit.setMnemonic(thirdLettorOfName);
            buttonEdit.addActionListener(this);
            panelButtons.add(buttonEdit);
            }
           
            //We will also create another Panel to put the JList and the buttons
            GridBagLayout gbl = new GridBagLayout();
            GridBagConstraints gbc = new GridBagConstraints();
            this.setLayout(gbl);
           
            defaultListModel = new DefaultListModel();
            list = new JList(defaultListModel);
            list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            list.addListSelectionListener(this);
           
            //If they want the special renderer which will move things down
            //to two consecutive lines we will do that.
            if (specialrenderer) {
                list.setCellRenderer(new ListUtilityRenderer());
            }
           
            scrollPaneList = new JScrollPane(list);
            scrollPaneList.setPreferredSize(new Dimension(width, height));
            scrollPaneList.setMinimumSize(new Dimension(width, height));

            //We want to have a border with how many of the items are listed.
            int selectedIndex = list.getSelectedIndex() + 1;
            int totalItemsInList = list.getModel().getSize();
           
            scrollPaneList.setBorder(new TitledBorder(name + "s" + "(" + selectedIndex + " of " + totalItemsInList + " selected)"));
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbl.setConstraints(scrollPaneList, gbc);       
            this.add(scrollPaneList);
                   
            gbc.gridx = 1;
            gbc.gridy = 0;
            gbl.setConstraints(panelButtons, gbc);       
            this.add(panelButtons);

        }
       
        public JTextArea retrieveSingleItemWithinList() {
            ListCellRenderer listCellRenderer = list.getCellRenderer();
            ListUtilityRenderer listUtilityRenderer = (ListUtilityRenderer) listCellRenderer;
           
            return listUtilityRenderer;
           
        }

        /* (non-Javadoc)
         * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
         */
        public void actionPerformed(ActionEvent evt) {
           
            //If they want to add a value we will end up prompting them
            if (evt.getSource() == buttonAdd) {
                String value = null;
                if (values == null) {
                    value = JOptionPane.showInputDialog(this, "Enter a value for the " + name + ".                                                                                                                                                                                                                                      ");
                }  else {
                    value = (String) JOptionPane.showInputDialog(this, "Enter a value for the " + name + ".", "Enter a value", JOptionPane.QUESTION_MESSAGE, null, values, null);
                }
               
                //We will only add this value if something is returned
                if (value != null && value.length() != 0) {
                    defaultListModel.addElement(value);
                }
            } else if (evt.getSource() == buttonRemove) {
                int selectedIndx = list.getSelectedIndex();
                //We want to make sure something is selected.
                if (selectedIndx >= 0) {
                    defaultListModel.removeElementAt(selectedIndx);
                } else {
                    JOptionPane.showMessageDialog(this, "You need to select a value to be deleted.");
                }
            } else if (evt.getSource() == buttonEdit) {
                int selectedIndx = list.getSelectedIndex();
               
                if (selectedIndx >= 0) {
                String selectedValue = (String) defaultListModel.getElementAt(selectedIndx);
               
                String value = (String) JOptionPane.showInputDialog(this, "Edit the information for the " + name + ".                                                                                                                                                                                                                                ", selectedValue);
               
                if (value != null && value.length() != 0) {
                    defaultListModel.set(selectedIndx, value);
                }
                } else {
                    JOptionPane.showMessageDialog(this, "You need to select a value to edit.");
                }
               
            }
        }
       
        /**
         * This will set the values within the list.
         * @param values
         */
        public void setListValues(ArrayList values) {
           
            //Before we set this we will end up getting rid of all the elements within our list
            defaultListModel.removeAllElements();
           
            //We will then loop through our ArrayList and input the values within our list.
            if (values != null && values.size() != 0) {
            for (int i = 0; i < values.size(); i++) {
                String value = (String) values.get(i);
                if (value != null) {
                    defaultListModel.addElement(value);
                }
            }
            }
           
            //We want to have a border with how many of the items are listed.
            int selectedIndex = list.getSelectedIndex() + 1;
            int totalItemsInList = list.getModel().getSize();
           
            scrollPaneList.setBorder(new TitledBorder(name + "s" + "(" + selectedIndex + " of " + totalItemsInList + " selected)"));

        }
       
        /**
         * This will end up returning all the values within our ArrayList.
         * @return
         */
        public ArrayList getListValues() {
            //ArrayList that we will return
            ArrayList values = new ArrayList();
           
            for (int i = 0; i < defaultListModel.getSize(); i++) {
                String value = (String) defaultListModel.getElementAt(i);
                if (value.length() != 0) {
                    values.add(value);
                }
            } //end of looping through our defaultListModel
           
            //return the ArrayList of values
            return values;
        }

        /**
         * @param crossReferences
         */
        public void updateValues(String[] values) {
            this.values = values;
        }

        /**
         * @param arrayListCategoryWordInSubSection
         */
        public void highlightCategorialWords(ArrayList arrayListCategoryWordInSubSection) {
            ListUtilityRenderer cellRenderer = (ListUtilityRenderer) list.getCellRenderer();
            cellRenderer.highlightWords(arrayListCategoryWordInSubSection);
            //list.setSelectedIndex(0);
            list.updateUI();
        }

        /**
         * This will remove the highlight from our ListUtility.
         */
        public void removeHighlight() {
            ListUtilityRenderer cellRenderer = (ListUtilityRenderer) list.getCellRenderer();
            cellRenderer.arrayListCategoryWordsInSubSection = null;
            cellRenderer.removeHighlight();
            list.updateUI();
        }

        public void valueChanged(ListSelectionEvent e) {

            int selectedIndex = list.getSelectedIndex() + 1;
            int totalItemsInList = list.getModel().getSize();
           
            scrollPaneList.setBorder(new TitledBorder(name + "s" + "(" + selectedIndex + " of " + totalItemsInList + " selected)"));

        }
    }

    //////////
    //
    // ListUtilityRenderer method
    //
    ////////////

    package com.indstudy.gui;

    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.util.ArrayList;

    import javax.swing.JList;
    import javax.swing.JTextArea;
    import javax.swing.ListCellRenderer;
    import javax.swing.border.LineBorder;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.text.DefaultHighlighter;
    import javax.swing.text.Document;
    import javax.swing.text.Highlighter;

    import com.indstudy.CategoryWordInSubSection;

    /**
    * List Utility Renderer used for the ListUtility component.
    */
    public class ListUtilityRenderer extends JTextArea implements ListCellRenderer, DocumentListener {

        /** ArrayList of Category Words in a particular sub section */
        ArrayList arrayListCategoryWordsInSubSection = null;   

        /* (non-Javadoc)
         * @see javax.swing.ListCellRenderer#getListCellRendererComponent(javax.swing.JList, java.lang.Object, int, boolean, boolean)
         */
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {

            //Highlighter
            Highlighter hilite = this.getHighlighter();

            if (value != null) {
            //set the text of the value object
            setText(value.toString());
           
            setWrapStyleWord(true);
            setLineWrap(true);
            setPreferredSize(new Dimension(575, 50));
            setMaximumSize(new Dimension(575, 50));
            setMinimumSize(new Dimension(575, 50));
            setBorder(new LineBorder(Color.BLACK));
           
            this.getDocument().addDocumentListener(this);
           
            //If we have an ArrayList of Categories in a specific sub section.
            if (arrayListCategoryWordsInSubSection != null) {
               
                //We will loop through the ArrayList
                for (int i = 0; i < arrayListCategoryWordsInSubSection.size(); i++) {
                    CategoryWordInSubSection categoryWordInSubSection = (CategoryWordInSubSection) arrayListCategoryWordsInSubSection.get(i);
                    try {
                        hilite.addHighlight(categoryWordInSubSection.wordBeginningIndex, categoryWordInSubSection.wordEndingIndex, myHighlightPainter);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            }
           
            //If this is selected we will set the background to yellow
            if (isSelected) {
                try {
                    int i = this.getText().length();
                    hilite.addHighlight(0, this.getText().length(), selectionHighlightPainter);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return this;
        }
       
        /**
         * This will highlight the words correctly.
         * @param arrayListCategoryWordsInSubSection
         */
        public void highlightWords(ArrayList arrayListCategoryWordsInSubSection) {
            this.arrayListCategoryWordsInSubSection = arrayListCategoryWordsInSubSection;
        }

       
        /** Highlighter */
        Highlighter.HighlightPainter myHighlightPainter = new MyHighlightPainter(Color.RED);
       

        /** Highlight Painter */
        class MyHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter {
            public MyHighlightPainter(Color color) {
                super(color);
            }
        }
       
        Highlighter.HighlightPainter selectionHighlightPainter = new SelectionHighlightPainter(Color.YELLOW);
       
        class SelectionHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter {
            public SelectionHighlightPainter(Color color) {
                super(Color.YELLOW);
            }
        }

        /**
         * Will remove the Highlight of our ListUtility
         */
        public void removeHighlight() {
            Highlighter hilite = this.getHighlighter();
            Highlighter.Highlight[] hilites = hilite.getHighlights();
       
            for (int i=0; i<hilites.length; i++) {
                if (hilites[i].getPainter() instanceof MyHighlightPainter) {
                    hilite.removeHighlight(hilites[i]);
                }
            }
        }
    }