我制作了一个带有搜索引擎功能的小程序。这里的问题是,当我尝试首先使用关键字进行搜索时,通过以 JTable 格式打开一个新的 JFrame 来正确显示它。但是当我关闭该框架并在搜索表单中输入其他内容以搜索其他内容时,它不仅会显示我搜索过的最新内容,还会显示我之前搜索过的内容。在水平方向上,它也不断重复表格列。以下是截图:
首先我搜索 Dosa:
然后我关闭那个 Frame 并搜索 Idli,看看它是怎么来的:
谁能帮助我并告诉我哪里出错了?这是我的数据库活动和检索代码。
search.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
try {
s=field.getText();
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/delikat",
"root", "");
Statement st = (Statement) con.createStatement();
ResultSet rs= (ResultSet) st.executeQuery( "SELECT * FROM delicious where name = '"+s+ "'" );
ResultSetMetaData md = (ResultSetMetaData) rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
while (rs.next()) {
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
st.close();
}
catch(Exception e) {
e.printStackTrace();
}
Vector<Vector<Object>> NULL = null;
if(data==NULL) {
JOptionPane.showMessageDialog(frame, "No Data Found");
}
else {
//Declare a new Frame for the Query Result Display
JFrame tab=new JFrame();
//Add the Data and the Column Names to the Table
JTable table = new JTable(data, columnNames);
//Add Scroll Pane for instances when more data is to be displayed
JScrollPane scrollPane = new JScrollPane( table );
/* Open the Result of the Query in a new Frame, in a Tabular Format with Scroll Pane.
Add all the elements to the Frame and set the specifications of the Frame like
Size, Visibility, etc.
*/
tab.add( scrollPane );
tab.setVisible(true);
tab.setSize(810,100);
}
}
});
请帮助我克服这个问题。谢谢你。