2013-11-05 35 views
0

我有一個JFramePrincipal.java,我把JComboBox在那裏嘗試從我的MySQL表「pessoa」存儲客戶端名稱自動建議。如何實現這個工作代碼:jCombobox + jdbc +自動提示

/* 
* To change this license header, choose License Headers in Project Properties. 
* To change this template file, choose Tools | Templates 
* and open the template in the editor. 
*/ 

package teste; 

import java.awt.event.KeyAdapter; 
import java.awt.event.KeyEvent; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.Statement; 
import java.util.ArrayList; 
import java.util.List; 
import javax.swing.DefaultComboBoxModel; 
import javax.swing.JTextField; 
import javax.swing.SwingUtilities; 

/** 
* 
* @author Marcio 
*/ 
public class AutoSuggest extends javax.swing.JFrame { 

    public AutoSuggest() { 
    initComponents(); 

    final JTextField textfield = (JTextField) jComboBox1.getEditor().getEditorComponent(); 
    textfield.addKeyListener(new KeyAdapter() { 
     public void keyReleased(KeyEvent ke) { 
      SwingUtilities.invokeLater(new Runnable() { 
       public void run() { 
        comboFilter(textfield.getText()); 
       } 
      }); 
     } 
    }); 
} 



public void comboFilter(String enteredText) { 
    List<String> filterArray= new ArrayList<String>(); 

      String str1=""; 

    try 
    { 


    String str="SELECT * FROM pessoa WHERE nome LIKE '"+enteredText+"%'"; 

    Class.forName("com.mysql.jdbc.Driver"); 
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/teste", "root", ""); 
    Statement stmt=con.createStatement(); 
    ResultSet rs=stmt.executeQuery(str); 
    while(rs.next()) 
    { 

     str1=rs.getString("nome"); 
     filterArray.add(str1); 


    } 

    } 
    catch(Exception ex) 
    { 
    System.out.println("error"+ex); 
    } 




    if (filterArray.size() > 0) { 
     jComboBox1.setModel(new DefaultComboBoxModel(filterArray.toArray())); 
     jComboBox1.setSelectedItem(enteredText); 
     jComboBox1.showPopup(); 
    } 
    else { 
     jComboBox1.hidePopup(); 
    } 
} 

/** 
* This method is called from within the constructor to initialize the form. 
* WARNING: Do NOT modify this code. The content of this method is always 
* regenerated by the Form Editor. 
*/ 
@SuppressWarnings("unchecked") 
// <editor-fold defaultstate="collapsed" desc="Generated Code"> 
private void initComponents() { 

    jComboBox1 = new javax.swing.JComboBox(); 

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

    jComboBox1.setEditable(true); 

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
    getContentPane().setLayout(layout); 
    layout.setHorizontalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(layout.createSequentialGroup() 
      .addGap(87, 87, 87) 
      .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE) 
      .addContainerGap(98, Short.MAX_VALUE)) 
    ); 
    layout.setVerticalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(layout.createSequentialGroup() 
      .addGap(108, 108, 108) 
      .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
      .addContainerGap(172, Short.MAX_VALUE)) 
    ); 

    pack(); 
}// </editor-fold> 

/** 
* @param args the command line arguments 
*/ 
public static void main(String args[]) { 
    /* Set the Nimbus look and feel */ 
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> 
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. 
    * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
    */ 
    try { 
     for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
      if ("Nimbus".equals(info.getName())) { 
       javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
       break; 
      } 
     } 
    } catch (ClassNotFoundException ex) { 
     java.util.logging.Logger.getLogger(AutoSuggest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (InstantiationException ex) { 
     java.util.logging.Logger.getLogger(AutoSuggest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (IllegalAccessException ex) { 
     java.util.logging.Logger.getLogger(AutoSuggest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
     java.util.logging.Logger.getLogger(AutoSuggest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } 
    //</editor-fold> 

    /* Create and display the form */ 
    java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      new AutoSuggest().setVisible(true); 
     } 
    }); 
} 
// Variables declaration - do not modify 
private javax.swing.JComboBox jComboBox1; 
// End of variables declaration 
} 

我的Principal.java主屏幕。

private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {           

    final JTextField textfield = (JTextField) jComboBox1.getEditor().getEditorComponent(); 
    textfield.addKeyListener(new KeyAdapter() { 
     public void keyReleased(KeyEvent ke) { 
      SwingUtilities.invokeLater(new Runnable() { 
       public void run() { 
        comboFilter(textfield.getText()); 
       } 
      }); 
     } 
    }); 

}           


public void comboFilter(String enteredText) { 
    List<String> filterArray = new ArrayList<String>(); 

    String str1 = ""; 

    try { 

     String str = "SELECT * FROM pessoa WHERE nome LIKE '" + enteredText + "%'"; 

     Class.forName("com.mysql.jdbc.Driver"); 
     Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/teste", "root", ""); 
     Statement stmt = con.createStatement(); 
     ResultSet rs = stmt.executeQuery(str); 
     while (rs.next()) { 

      str1 = rs.getString("nome"); 
      filterArray.add(str1); 

     } 

    } catch (Exception ex) { 
     System.out.println("error" + ex); 
    } 

    if (filterArray.size() > 0) { 
     jComboBox1.setModel(new DefaultComboBoxModel(filterArray.toArray())); 
     jComboBox1.setSelectedItem(enteredText); 
     jComboBox1.showPopup(); 
    } else { 
     jComboBox1.hidePopup(); 
    } 
} 
+2

我的第一個建議是不要使用KeyListerner,而是使用的DocumentListener來監視更改到外地 – MadProgrammer

+0

我也建議你看一看的SwingLabs自動完成支持 – MadProgrammer

回答

0

您可以參考下面的工作代碼從roseindia。希望這是你正在尋找的。

import java.awt.*; 
import java.awt.event.*; 
import java.util.*; 
import javax.swing.*; 

public class AutoSuggest extends JPanel{ 
    private final JTextField tf; 
    private final JComboBox combo = new JComboBox(); 
    private final Vector<String> v = new Vector<String>(); 
    public AutoSuggest() { 
     super(new BorderLayout()); 
     combo.setEditable(true); 
     tf = (JTextField) combo.getEditor().getEditorComponent(); 
     tf.addKeyListener(new KeyAdapter() { 
       public void keyTyped(KeyEvent e) { 
       EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       String text = tf.getText(); 
         if(text.length()==0) { 
        combo.hidePopup(); 
        setModel(new DefaultComboBoxModel(v), ""); 
       }else{ 
        DefaultComboBoxModel m = getSuggestedModel(v, text); 
        if(m.getSize()==0 || hide_flag) { 
          combo.hidePopup(); 
         hide_flag = false; 
        }else{ 
         setModel(m, text); 
         combo.showPopup(); 
        } 
       } 
      } 
     }); 
      } 
       public void keyPressed(KeyEvent e) { 
       String text = tf.getText(); 
     int code = e.getKeyCode(); 
      if(code==KeyEvent.VK_ENTER) { 
      if(!v.contains(text)) { 
       v.addElement(text); 
       Collections.sort(v); 
       setModel(getSuggestedModel(v, text), text); 
      } 
      hide_flag = true; 
     }else if(code==KeyEvent.VK_ESCAPE) { 
      hide_flag = true; 
     }else if(code==KeyEvent.VK_RIGHT) { 
      for(int i=0;i<v.size();i++) { 
       String str = v.elementAt(i); 
       if(str.startsWith(text)) { 
        combo.setSelectedIndex(-1); 
        tf.setText(str); 
        return; 
       } 
      } 
     } 
      } 
     }); 
     String[] countries = {"Afghanistan", "Albania", "Algeria", "Andorra", "Angola","Argentina" 
,"Armenia","Austria","Bahamas","Bahrain", "Bangladesh","Barbados", "Belarus","Belgium", 
"Benin","Bhutan","Bolivia","Bosnia & Herzegovina","Botswana","Brazil","Bulgaria", 
"Burkina Faso","Burma","Burundi","Cambodia","Cameroon","Canada", "China","Colombia", 
"Comoros","Congo","Croatia","Cuba","Cyprus","Czech Republic","Denmark", "Georgia", 
"Germany","Ghana","Great Britain","Greece","Hungary","Holland","India","Iran","Iraq", 
"Italy","Somalia", "Spain", "Sri Lanka", "Sudan","Suriname", "Swaziland","Sweden", 
"Switzerland", "Syria","Uganda","Ukraine","United Arab Emirates","United Kingdom", 
"United States","Uruguay","Uzbekistan","Vanuatu","Venezuela","Vietnam", 
"Yemen","Zaire","Zambia","Zimbabwe"}; 
      for(int i=0;i<countries.length;i++){ 
        v.addElement(countries[i]); 
      } 
     setModel(new DefaultComboBoxModel(v), ""); 
     JPanel p = new JPanel(new BorderLayout()); 
     p.setBorder(BorderFactory.createTitledBorder("AutoSuggestion Box")); 
     p.add(combo, BorderLayout.NORTH); 
     add(p); 
     setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); 
     setPreferredSize(new Dimension(300, 150)); 
    } 
    private boolean hide_flag = false; 
     private void setModel(DefaultComboBoxModel mdl, String str) { 
     combo.setModel(mdl); 
     combo.setSelectedIndex(-1); 
     tf.setText(str); 
    } 
private static DefaultComboBoxModel getSuggestedModel(java.util.List<String> list, String text) { 
     DefaultComboBoxModel m = new DefaultComboBoxModel(); 
     for(String s: list) { 
      if(s.startsWith(text)) m.addElement(s); 
     } 
     return m; 
    } 
    public static void main(String[] args) { 
     JFrame frame = new JFrame(); 
     frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 
     frame.getContentPane().add(new AutoSuggest()); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 
    } 
+1

使用的KeyListener大大氣餒,因爲它沒有考慮到當用戶將文本粘貼到我發佈的代碼的字段 – MadProgrammer

+0

時會發生什麼情況,AutoSuggest工作得很好,他從我的數據庫中獲取插入的名稱,並在我搜索時給我一個自動建議,但我不知道如何實現在我的另一個類上的Principal.java上 'private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt){ }' – Lettus

+0

編寫一個自定義方法來獲取已過濾數據的模型並使用該模型。請參考如何在上面的代碼中使用getSuggestedModel(..)。 –