我在jtextfield上应用自动建议,但它无效

时间:2015-10-30 05:55:29

标签: java swing

   **AddcompanyName.java**
    package suncomputer;

    import java.awt.Color;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.HeadlessException;
    import java.awt.Insets;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextField;

    /**
     *
     * @author strugle
     */
    public class AddcompanyName extends JFrame {
        Connection connection = null;
            Statement stmt=null;
            ResultSet resultset=null;
            int masterTotal=0;
            private JLabel lablelcompanyId = new JLabel("Id ");
            private JLabel lablelCompanyName = new JLabel("Company Name");

            private JTextField textcompanyid = new JTextField(20);
            private JTextField textCompanyName = new JTextField(20);
            JButton button_save=new JButton("Save");

        public AddcompanyName(){
            **AutoSuggestor autoSuggestor=new AutoSuggestor(textCompanyName,this, null, Color.WHITE.brighter(), Color.BLUE, Color.RED,0.75f){
                    @Override
                    boolean wordTyped(String typedWord) {
                        ArrayList<String> words = new ArrayList<String>();
                        words.add("hello");
                        words.add("heritage");
                        words.add("happiness");
                        words.add("goodbye");
                        words.add("cruel");
                        words.add("car");
                        words.add("war");
                        words.add("will");
                        words.add("world");
                        words.add("wall");
                        return super.wordTyped(typedWord);
                    }
                        };**
            JPanel newPanel = new JPanel(new GridBagLayout());

            GridBagConstraints constraints = new GridBagConstraints();
            constraints.anchor = GridBagConstraints.WEST;
            constraints.insets = new Insets(10, 10, 10, 10);

            // add components to the panel
            constraints.gridx = 0;
            constraints.gridy = 0;      
            newPanel.add(lablelcompanyId, constraints);

            constraints.gridx = 1;
            newPanel.add(textcompanyid, constraints);

            constraints.gridx = 0;
            constraints.gridy = 1;      
            newPanel.add(lablelCompanyName, constraints);

            constraints.gridx = 1;
            newPanel.add(textCompanyName, constraints);

                    constraints.gridx=2;
                    newPanel.add(button_save,constraints);
                    newPanel.setBorder(BorderFactory.createTitledBorder(
                    BorderFactory.createEtchedBorder(), "Add Company"));

            // add the panel to this frame
            add(newPanel);
                    pack();
            setLocationRelativeTo(null);
                    addWindowListener(new java.awt.event.WindowAdapter() {
                         public void windowOpened(java.awt.event.WindowEvent evt) {
                         formWindowOpened(evt);
                        }
                    });

                button_save.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    commonDatabaseC common_db=new commonDatabaseC();
                    Connection connection=common_db.getConnection();
                    String insertCompanyName = "INSERT INTO Master_CompanyName(id,Name) VALUES (?,?)";
            try{
            PreparedStatement preparedStatement =connection.prepareStatement(insertCompanyName);
            preparedStatement.setInt(1,Integer.parseInt(textcompanyid.getText()));
            preparedStatement.setString(2,textCompanyName.getText());
            preparedStatement .executeUpdate();
            JOptionPane.showMessageDialog(null,"Record Saved....");
            }
            catch(SQLException sQLException){
                sQLException.printStackTrace();
            }
                }

                    });
        }

        private void formWindowOpened(java.awt.event.WindowEvent evt) {
            int companyid=fetchProductid()+1;
            textcompanyid.setText(""+companyid);
            textcompanyid.setEditable(false);
        }
        public int fetchProductid(){
            int companyid=0;
            try{
                commonDatabaseC cmd=new commonDatabaseC();
                connection=cmd.getConnection();
                stmt=connection.createStatement();
            }
            catch(SQLException sqle){
               System.out.println("failed to statement");
            }try{
            resultset=stmt.executeQuery("select max(id) from master_companyname");

            }catch(SQLException sql){
               System.out.println("failed to execmtequery"); 
            }try{
            resultset.beforeFirst();
            while(resultset.next()){
            resultset.last();
            companyid=resultset.getInt(1);
            System.out.println(companyid);
            }
            }catch(SQLException sqle){
                 System.out.println("failed to fecth records"); 
            }
            finally{
                try{
                    connection.close();
                    resultset.close();
                }
                catch(SQLException sQLException){
                    JFrame frame=new JFrame();
                    JOptionPane.showMessageDialog(frame,"A basic JOptionPane message dialog");
                }

            }
            return companyid;
        }
    }
    **AutoSuggestor.java**
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package suncomputer;

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.util.ArrayList;
    import javax.swing.AbstractAction;
    import javax.swing.JComponent;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JWindow;
    import javax.swing.KeyStroke;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;

    /**
     *
     * @author strugle
     */
    class AutoSuggestor {

        private final JTextField textField;
        private final Window container;
        private JPanel suggestionsPanel;
        private JWindow autoSuggestionPopUpWindow;
        private String typedWord;
        private final ArrayList<String> dictionary = new ArrayList<String>();
        private int currentIndexOfSpace, tW, tH;
        private DocumentListener documentListener = new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent de) {
                checkForAndShowSuggestions();
            }

            @Override
            public void removeUpdate(DocumentEvent de) {
                checkForAndShowSuggestions();
            }

            @Override
            public void changedUpdate(DocumentEvent de) {
                checkForAndShowSuggestions();
            }
        };
        private final Color suggestionsTextColor;
        private final Color suggestionFocusedColor;

        public AutoSuggestor(JTextField textField, Window mainWindow, ArrayList<String> words, Color popUpBackground, Color textColor, Color suggestionFocusedColor, float opacity) {
            this.textField = textField;
            this.suggestionsTextColor = textColor;
            this.container = mainWindow;
            this.suggestionFocusedColor = suggestionFocusedColor;
            this.textField.getDocument().addDocumentListener(documentListener);

            setDictionary(words);

            typedWord = "";
            currentIndexOfSpace = 0;
            tW = 0;
            tH = 0;

            autoSuggestionPopUpWindow = new JWindow(mainWindow);
            autoSuggestionPopUpWindow.setOpacity(opacity);

            suggestionsPanel = new JPanel();
            suggestionsPanel.setLayout(new GridLayout(0, 1));
            suggestionsPanel.setBackground(popUpBackground);

            addKeyBindingToRequestFocusInPopUpWindow();
        }

        private void addKeyBindingToRequestFocusInPopUpWindow() {
            textField.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "Down released");
            textField.getActionMap().put("Down released", new AbstractAction() {
                @Override
                public void actionPerformed(ActionEvent ae) {//focuses the first label on popwindow
                    for (int i = 0; i < suggestionsPanel.getComponentCount(); i++) {
                        if (suggestionsPanel.getComponent(i) instanceof SuggestionLabel) {
                            ((SuggestionLabel) suggestionsPanel.getComponent(i)).setFocused(true);
                            autoSuggestionPopUpWindow.toFront();
                            autoSuggestionPopUpWindow.requestFocusInWindow();
                            suggestionsPanel.requestFocusInWindow();
                            suggestionsPanel.getComponent(i).requestFocusInWindow();
                            break;
                        }
                    }
                }
            });
            suggestionsPanel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "Down released");
            suggestionsPanel.getActionMap().put("Down released", new AbstractAction() {
                int lastFocusableIndex = 0;

                @Override
                public void actionPerformed(ActionEvent ae) {//allows scrolling of labels in pop window (I know very hacky for now :))

                    ArrayList<SuggestionLabel> sls = getAddedSuggestionLabels();
                    int max = sls.size();

                    if (max > 1) {//more than 1 suggestion
                        for (int i = 0; i < max; i++) {
                            SuggestionLabel sl = sls.get(i);
                            if (sl.isFocused()) {
                                if (lastFocusableIndex == max - 1) {
                                    lastFocusableIndex = 0;
                                    sl.setFocused(false);
                                    autoSuggestionPopUpWindow.setVisible(false);
                                    setFocusToTextField();
                                    checkForAndShowSuggestions();//fire method as if document listener change occured and fired it

                                } else {
                                    sl.setFocused(false);
                                    lastFocusableIndex = i;
                                }
                            } else if (lastFocusableIndex <= i) {
                                if (i < max) {
                                    sl.setFocused(true);
                                    autoSuggestionPopUpWindow.toFront();
                                    autoSuggestionPopUpWindow.requestFocusInWindow();
                                    suggestionsPanel.requestFocusInWindow();
                                    suggestionsPanel.getComponent(i).requestFocusInWindow();
                                    lastFocusableIndex = i;
                                    break;
                                }
                            }
                        }
                    } else {//only a single suggestion was given
                        autoSuggestionPopUpWindow.setVisible(false);
                        setFocusToTextField();
                        checkForAndShowSuggestions();//fire method as if document listener change occured and fired it
                    }
                }
            });
        }

        private void setFocusToTextField() {
            container.toFront();
            container.requestFocusInWindow();
            textField.requestFocusInWindow();
        }

        public ArrayList<SuggestionLabel> getAddedSuggestionLabels() {
            ArrayList<SuggestionLabel> sls = new ArrayList<SuggestionLabel>();
            for (int i = 0; i < suggestionsPanel.getComponentCount(); i++) {
                if (suggestionsPanel.getComponent(i) instanceof SuggestionLabel) {
                    SuggestionLabel sl = (SuggestionLabel) suggestionsPanel.getComponent(i);
                    sls.add(sl);
                }
            }
            return sls;
        }

        private void checkForAndShowSuggestions() {
            typedWord = getCurrentlyTypedWord();

            suggestionsPanel.removeAll();//remove previos words/jlabels that were added

            //used to calcualte size of JWindow as new Jlabels are added
            tW = 0;
            tH = 0;

            boolean added = wordTyped(typedWord);

            if (!added) {
                if (autoSuggestionPopUpWindow.isVisible()) {
                    autoSuggestionPopUpWindow.setVisible(false);
                }
            } else {
                showPopUpWindow();
                setFocusToTextField();
            }
        }

        protected void addWordToSuggestions(String word) {
            SuggestionLabel suggestionLabel = new SuggestionLabel(word, suggestionFocusedColor, suggestionsTextColor, this);

            calculatePopUpWindowSize(suggestionLabel);

            suggestionsPanel.add(suggestionLabel);
        }

        public String getCurrentlyTypedWord() {//get newest word after last white spaceif any or the first word if no white spaces
            String text = textField.getText();
            String wordBeingTyped = "";
            if (text.contains(" ")) {
                int tmp = text.lastIndexOf(" ");
                if (tmp >= currentIndexOfSpace) {
                    currentIndexOfSpace = tmp;
                    wordBeingTyped = text.substring(text.lastIndexOf(" "));
                }
            } else {
                wordBeingTyped = text;
            }
            return wordBeingTyped.trim();
        }

        private void calculatePopUpWindowSize(JLabel label) {
            //so we can size the JWindow correctly
            if (tW < label.getPreferredSize().width) {
                tW = label.getPreferredSize().width;
            }
            tH += label.getPreferredSize().height;
        }

        private void showPopUpWindow() {
            autoSuggestionPopUpWindow.getContentPane().add(suggestionsPanel);
            autoSuggestionPopUpWindow.setMinimumSize(new Dimension(textField.getWidth(), 30));
            autoSuggestionPopUpWindow.setSize(tW, tH);
            autoSuggestionPopUpWindow.setVisible(true);

            int windowX = 0;
            int windowY = 0;

            windowX = container.getX() + textField.getX() + 5;
            if (suggestionsPanel.getHeight() > autoSuggestionPopUpWindow.getMinimumSize().height) {
                windowY = container.getY() + textField.getY() + textField.getHeight() + autoSuggestionPopUpWindow.getMinimumSize().height;
            } else {
                windowY = container.getY() + textField.getY() + textField.getHeight() + autoSuggestionPopUpWindow.getHeight();
            }

            autoSuggestionPopUpWindow.setLocation(windowX, windowY);
            autoSuggestionPopUpWindow.setMinimumSize(new Dimension(textField.getWidth(), 30));
            autoSuggestionPopUpWindow.revalidate();
            autoSuggestionPopUpWindow.repaint();

        }

        public void setDictionary(ArrayList<String> words) {
            dictionary.clear();
            if (words == null) {
                return;//so we can call constructor with null value for dictionary without exception thrown
            }
            for (String word : words) {
                dictionary.add(word);
            }
        }

        public JWindow getAutoSuggestionPopUpWindow() {
            return autoSuggestionPopUpWindow;
        }

        public Window getContainer() {
            return container;
        }

        public JTextField getTextField() {
            return textField;
        }

        public void addToDictionary(String word) {
            dictionary.add(word);
        }

        boolean wordTyped(String typedWord) {

            if (typedWord.isEmpty()) {
                return false;
            }
            //System.out.println("Typed word: " + typedWord);

            boolean suggestionAdded = false;

            for (String word : dictionary) {//get words in the dictionary which we added
                boolean fullymatches = true;
                for (int i = 0; i < typedWord.length(); i++) {//each string in the word
                    if (!typedWord.toLowerCase().startsWith(String.valueOf(word.toLowerCase().charAt(i)), i)) {//check for match
                        fullymatches = false;
                        break;
                    }
                }
                if (fullymatches) {
                    addWordToSuggestions(word);
                    suggestionAdded = true;
                }
            }
            return suggestionAdded;
        }
    }
**SuggestionLable.java**
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package suncomputer;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JWindow;
import javax.swing.KeyStroke;
import javax.swing.border.LineBorder;

/**
 *
 * @author strugle
 */
class SuggestionLabel extends JLabel {

    private boolean focused = false;
    private final JWindow autoSuggestionsPopUpWindow;
    private final JTextField textField;
    private final AutoSuggestor autoSuggestor;
    private Color suggestionsTextColor, suggestionBorderColor;

    public SuggestionLabel(String string, final Color borderColor, Color suggestionsTextColor, AutoSuggestor autoSuggestor) {
        super(string);

        this.suggestionsTextColor = suggestionsTextColor;
        this.autoSuggestor = autoSuggestor;
        this.textField = autoSuggestor.getTextField();
        this.suggestionBorderColor = borderColor;
        this.autoSuggestionsPopUpWindow = autoSuggestor.getAutoSuggestionPopUpWindow();

        initComponent();
    }

    private void initComponent() {
        setFocusable(true);
        setForeground(suggestionsTextColor);

        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent me) {
                super.mouseClicked(me);
                replaceWithSuggestedText();

                autoSuggestionsPopUpWindow.setVisible(false);
            }
        });

        getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true), "Enter released");
        getActionMap().put("Enter released", new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                replaceWithSuggestedText();
                autoSuggestionsPopUpWindow.setVisible(false);
            }
        });
    }

    public void setFocused(boolean focused) {
        if (focused) {
            setBorder(new LineBorder(suggestionBorderColor));
        } else {
            setBorder(null);
        }
        repaint();
        this.focused = focused;
    }

    public boolean isFocused() {
        return focused;
    }

    private void replaceWithSuggestedText() {
        String suggestedWord = getText();
        String text = textField.getText();
        String typedWord = autoSuggestor.getCurrentlyTypedWord();
        String t = text.substring(0, text.lastIndexOf(typedWord));
        String tmp = t + text.substring(text.lastIndexOf(typedWord)).replace(typedWord, suggestedWord);
        textField.setText(tmp + " ");
    }
}

** AddcompanyName.java类    private JTextField textCompanyName = new JTextField(20); textCompanyName字段实现AutoSuggestor但它不起作用 我没有得到什么问题。 **

1 个答案:

答案 0 :(得分:1)

这似乎毫无意义......

AutoSuggestor autoSuggestor = new AutoSuggestor(textCompanyName, this, null, Color.WHITE.brighter(), Color.BLUE, Color.RED, 0.75f) {
    @Override
    boolean wordTyped(String typedWord) {
        ArrayList<String> words = new ArrayList<String>();
        words.add("hello");
        words.add("heritage");
        words.add("happiness");
        words.add("goodbye");
        words.add("cruel");
        words.add("car");
        words.add("war");
        words.add("will");
        words.add("world");
        words.add("wall");
        return super.wordTyped(typedWord);
    }
};

您填写了List个完整的字词,但随后对它们不做任何操作,而是拨打super.wordTyped

boolean wordTyped(String typedWord) {

    if (typedWord.isEmpty()) {
        return false;
    }
    //System.out.println("Typed word: " + typedWord);

    boolean suggestionAdded = false;

    for (String word : dictionary) {//get words in the dictionary which we added
        boolean fullymatches = true;
        for (int i = 0; i < typedWord.length(); i++) {//each string in the word
            if (!typedWord.toLowerCase().startsWith(String.valueOf(word.toLowerCase().charAt(i)), i)) {//check for match
                fullymatches = false;
                break;
            }
        }
        if (fullymatches) {
            addWordToSuggestions(word);
            suggestionAdded = true;
        }
    }
    return suggestionAdded;
}

dictionary为空

您应该使用setDictionary ...

    AutoSuggestor autoSuggestor = new AutoSuggestor(textCompanyName, this, null, Color.WHITE.brighter(), Color.BLUE, Color.RED, 0.75f);
    ArrayList<String> words = new ArrayList<String>();
    words.add("hello");
    words.add("heritage");
    words.add("happiness");
    words.add("goodbye");
    words.add("cruel");
    words.add("car");
    words.add("war");
    words.add("will");
    words.add("world");
    words.add("wall");
    autoSuggestor.setDictionary(words);

这有点浪费......

public void setDictionary(ArrayList<String> words) {
    dictionary.clear();
    if (words == null) {
        return;//so we can call constructor with null value for dictionary without exception thrown
    }
    for (String word : words) {
        dictionary.add(word);
    }
}

什么时候可以使用......

public void setDictionary(ArrayList<String> words) {
    dictionary.clear();
    if (words == null) {
        return;//so we can call constructor with null value for dictionary without exception thrown
    }
    dictionary.addAll(words);
}

这似乎还有很多工作......

public String getCurrentlyTypedWord() {//get newest word after last white spaceif any or the first word if no white spaces
    String text = textField.getText();
    String wordBeingTyped = "";
    if (text.contains(" ")) {
        int tmp = text.lastIndexOf(" ");
        if (tmp >= currentIndexOfSpace) {
            currentIndexOfSpace = tmp;
            wordBeingTyped = text.substring(text.lastIndexOf(" "));
        }
    } else {
        wordBeingTyped = text;
    }
    return wordBeingTyped.trim();
}

当你可以做...

public String getCurrentlyTypedWord() {//get newest word after last white spaceif any or the first word if no white spaces
    String parts[] = textField.getText().split(" ");
    return parts[parts.length - 1];
}