所以我正在编写一个包含这段代码的程序
final ListModel listModel = new DefaultListModel();
JButton btnBuscar = new JButton("Buscar");
btnBuscar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
listModel = MySQL("SELECT * FROM catalogos WHERE id = '" +
searchField.getText() +
"' OR name LIKE '%" +
searchField.getText() +
"%' OR keywords LIKE '%" +
searchField.getText() + "%'", "SELECT");
}
});
btnBuscar.setBounds(336, 11, 89, 23);
searchPanel.add(btnBuscar);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 44, 316, 185);
searchPanel.add(scrollPane);
JList list = new JList(listModel);
scrollPane.setViewportView(list);
正如您所看到的,我创建了一个ListModel变量,然后想要在按下按钮时使用它。函数MySQL返回一个listModel。
然后,我想创建一个列表,并在listmodel中为其提供元素。这段代码有什么问题?
答案 0 :(得分:3)
示例的快捷方式
try {
String sqlSyntax = "SELECT * FROM ........";
Statement stmt = myDbConnection.createStatement();
ResultSet rsts = stmt.executeQuery(sqlSyntax);
while (rsts.next()) {
final String str = rsts.getString(1); // or another data types
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
listModel.add(str.trim());
}
});
}
} catch (SQLException ex) {
// exeption handling
} finally {
try {
rsts.close();
stmt.close();
} catch (SQLException ex) {
// not important
}
}
答案 1 :(得分:0)
除了SQL问题,您正在尝试重新分配final
变量。您应该使listModel
字段(实例变量)而不是最终的局部变量,以便您的actionListener可以访问并更改它。
而不是
public class YourClassName {
public ? yourMethodName() {
final ListModel listModel = new DefaultListMode();
JButton btnBuscar = new JButton("Buscar");
...
你会写
public class YourClassName {
private ListModel listModel = new DefaultListModel();
public ? yourMethodName() {
JButton btnBuscar = ...