-2
當我寫入數據庫時,我正在尋找數據庫中的名稱JTextField
,我想按enter鍵顯示所有相應的名稱。不幸的是我無法做到,有人可以幫助我。Jtextfield在數據庫msql中使用keylistener進行搜索
public class Rechercher extends JFrame{
private JLabel rechercher;
private JTextField trechercher;
private JButton executer;
private JButton exit;
static Connection connection;
Vector titrecolonnes = new Vector();
Vector donnee = new Vector();
private JTable table;
private TableRowSorter<TableModel> sorter;
public Rechercher()
{
initComponents();
}
public void initComponents()
{
setLayout(null);
trechercher = new JTextField("");
add(trechercher);
trechercher.setBounds(140, 30, 235,35);
executer = new JButton("Rechercher :");
add(executer);
executer.setBounds(10, 34, 115,25);
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("com.mysql.jdbc.Driver found");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/eva","root","");
System.out.println("Connexion Ok");
}catch(Exception cnfe)
{
System.out.println("Error:"+cnfe.getMessage());
}
//-----actionner textfield
trechercher.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e){
trechercher.setText("");
}
});
//------Connection à la base de donneés
trechercher.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e) {
try{
// Read data from a table
String sql = "SELECT * FROM impaye";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
titrecolonnes.addElement(md.getColumnName(i));
}
// Get row data
while (rs.next())
{
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement(rs.getObject(i));
}
donnee.addElement(row);
}
rs.close();
stmt.close();
}catch(Exception cnfe)
{
System.out.println("Error:"+cnfe.getMessage());
}
TableModel model = new DefaultTableModel (donnee, titrecolonnes)
{
public Class getColumnClass(int columnNames) {
Class returnValue;
if ((columnNames >= 0) && (columnNames < getColumnCount())) {
returnValue = getValueAt(0, columnNames).getClass();
} else {
returnValue = Object.class;
}
return returnValue;
}
};
table = new JTable (model) ;
sorter = new TableRowSorter<TableModel>(model) ;
JScrollPane scrollPane = new JScrollPane((table));
table.setRowSorter (sorter) ;
getContentPane().setLayout(new GridLayout(1,1));
getContentPane().add(scrollPane);
}
});
}
}
嗨@Recay,歡迎計算器!你的問題並不完全清楚。您是否試圖根據當前的用戶輸入提供來自數據庫的搜索建議? –