- class FilterField extends JComponent
- implements DocumentListener, ActionListener {
- LinkedList prevSearches;
- JTextField textField;
- JButton prevSearchButton;
- JPopupMenu prevSearchMenu;
- public FilterField (int width) {
- super();
- setLayout(new BorderLayout());
- textField = new JTextField (width);
- textField.getDocument().addDocumentListener (this);
- textField.addActionListener (this);
- prevSearchButton =
- new JButton (new ImageIcon ("mag-glass.png"));
- prevSearchButton.setBorder(null);
- prevSearchButton.addMouseListener (new MouseAdapter() {
- public void mousePressed (MouseEvent me) { popMenu (me.getX(), me.getY());
- }
- });
- add (prevSearchButton, BorderLayout.WEST);
- add (textField, BorderLayout.CENTER);
- prevSearches = new LinkedList ();
- }
- public void popMenu (int x, int y) {
- prevSearchMenu = new JPopupMenu();
- Iterator it = prevSearches.iterator();
- while (it.hasNext())
- prevSearchMenu.add (
- new PrevSearchAction(it.next().toString()));
- prevSearchMenu.show (prevSearchButton, x, y);
- }
- public void actionPerformed (ActionEvent e) {
- // called on return/enter, adds term to prevSearches
- if (e.getSource() == textField) {
- prevSearches.addFirst (textField.getText());
- if (prevSearches.size() > 10)
- prevSearches.removeLast();
- }
- }
- public void changedUpdate (DocumentEvent e) {
- ((FilterModel)getModel()).refilter();
- }
- public void insertUpdate (DocumentEvent e) {
- ((FilterModel)getModel()).refilter();
- }
- public void removeUpdate (DocumentEvent e) {
- ((FilterModel)getModel()).refilter();
- }
- }
- class PrevSearchAction extends AbstractAction {
- String term;
- public PrevSearchAction (String s) {
- term = s;
- putValue (Action.NAME, term);
- }
- public String toString() { return term; }
- public void actionPerformed (ActionEvent e) {
- getFilterField().textField.setText (term);
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/300820135477.html
来源: http://www.codesnippet.cn/detail/300820135477.html