这里是编程新手。使用 MySQL 搜索结果更新表时遇到问题。
我正忙于学习 Java 8,目前正在编写一个带有 GUI 的小型数据库程序作为练习。我为此使用 Netbeans。我没有编写 GUI 代码(尽管我可以),而是使用 NetBeans GUI 设计器。
当我运行该程序时,会弹出一个窗口,其中包含一个文本字段和搜索按钮,其中包含一个 Jtable,其中 4 列已填充数据库条目。
我希望能够使用文本字段和搜索按钮运行部分搜索,并让 Jtabel 刷新以在单击搜索按钮时仅显示搜索结果。
到目前为止,我要么将搜索结果作为更多行附加到表中。将整个表作为更多行追加到表中,或者根本不发生任何事情。
这是我用来设置数组和 getter 的 Java 类。
class array {
private String Column_One;
private String Column_Two;
private String Column_Three;
private String Column_Four;
public User(String Column_One, String Column_Two, String Column_Three, String Column_Four) {
this.Column_One = Column_One;
this.Column_Two = Column_Two;
this.Column_Three = Column_Three;
this.Column_Four = Column_Four;
}
public String get Column_One() {
return Column_One;
}
public String getColumn_Two() {
return Column_Two;
}
public String getColumn_Three() {
return Column_Three;
}
public String getColumn_Four() {
return Column_Four;
}
}
这是我启动程序时用于填充 Jtable 的代码
public class JavaClass extends javax.swing.JFrame {
public ArrayList<array> List = new ArrayList<array>();
public JavaClass() {
initComponents();
populate_Table();
// the next line is for a Jpanel containing the search textflield and search button part of a defunct combo box selection event
JPanel.setVisible(true);
public ArrayList<array> arrayLists() {
{
String Url = "Url";
try {
Connection DbCon = DriverManager.getConnection(Url, "username", "password");
String sql = "SELECT ColumnOne, ColumnTwo, ColumnThree, ColumnFour FROM mysqldatabasetable ";
Statement pst = DbCon.createStatement();
ResultSet rs = pst.executeQuery(sql);
User user;
while (rs.next()) {
// The next line is what the columns will be called in Mysql
user = new User(rs.getString("sqlColumnOne"), rs.getString("sqlColumnTwo"), rs.getString("sqlColumnThree"), rs.getString("sqlColumnFour"));
List.add(array);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
return List;
}
public void populate_Table() {
ArrayList<array> JtableList = arrayLists();
DefaultTableModel model = (DefaultTableModel) Guidatabasetable.getModel();
Object[] row = new Object[4];
for (int i = 0; i < JtableList.size(); i++) {
row[0] = JtableList.get(i).getColumn_One();
row[1] = JtableList.get(i).getColumn_Two();
row[2] = JtableList.get(i).getColumn_Three();
row[3] = JtableList.get(i).Column_Four();
model.addRow(row);
}
Guidatabasetable.setModel(model);
}
最佳答案
因此,从表面上看,您需要从 JTable
模型中删除所有预先存在的行。根据内存,使用 DefaultTableModel
,这非常简单......
DefaultTableModel model = (DefaultTableModel) Guidatabasetable.getModel();
model.setRowCount(0);
// Fill with results from database
关于java - 使用 Mysql 数据库的搜索结果刷新 Jtable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60023286/