【发布时间】:2015-10-24 15:47:58
【问题描述】:
当我在JTextField 的数据库中查找名称时,我想按回车键显示所有相应的名称。不幸的是我做不到,请有人帮助我。
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,欢迎来到 StackOverflow!你的问题并不完全清楚。您是否尝试根据当前用户输入从数据库中提供搜索建议?