[英]INSERT row does not update JTable in GUI
As mentioned in the header I cannot get my JTable to update with a new row unless I restart the program. 如标题中所述,除非重新启动程序,否则我无法让JTable用新行更新。 When I restart, the new row is there and everything is as it should be.
当我重新启动时,新的行就在那里,一切都应该保持原样。 I have tried revalidating/repainting the panel and frame, I have tried the fire methods.
我尝试过重新验证/重新粉刷面板和框架,还尝试过防火方法。 I'm at a loss.
我很茫然。 Thanks in advance
提前致谢
ActionListener (in adminGUI class) for 'Add' button: “添加”按钮的ActionListener(在adminGUI类中):
if(source.equals(add2)){
String c = itb.getText();
int a = main.getResults();
boolean matches = Pattern.matches("[A-Z][a-z]+", c);
if(matches == true){
main.addGenre(a, c);
}
String Method(in main class) to add a row to the database table: 用于在数据库表中添加行的String方法(在主类中):
public static void addGenre(int a, String b){
int rowsAdded;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection connect =DriverManager.getConnection("jdbc:odbc:MovieDB");
Statement stmt = connect.createStatement();
String query = "INSERT INTO Genres (genre_id, genre_name)" + "VALUES(" + a + ", '" + b + "')";
rowsAdded = stmt.executeUpdate(query);
}catch(Exception exc){}
}
Method(also in main class) to increment the auto-increment-key column: 用于增加auto-increment-key列的方法(也在主类中):
public static int getResults(){
int a = 0;
ResultSet ints = main.getResults("Select genre_id from Genres");
try {
while(ints.next()){
int d = ints.getInt("genre_id");
if(d>a){
a = d;
}
a++;
}
} catch (SQLException ex) {
Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
}
return a;
}
JTable details: JTable详细信息:
ResultSet rs1 = main.getResults("Select * from Genres");
JTable tab1 = new JTable(DbUtils.resultSetToTableModel(rs1));
DbUtils.resultSetToTableModel details : DbUtils.resultSetToTableModel详细信息:
public class DbUtils {
public static TableModel resultSetToTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector columnNames = new Vector();
// Get the column names
for (int column = 0; column < numberOfColumns; column++) {
columnNames.addElement(metaData.getColumnLabel(column + 1));
}
// Get all rows.
Vector rows = new Vector();
while (rs.next()) {
Vector newRow = new Vector();
for (int i = 1; i <= numberOfColumns; i++) {
newRow.addElement(rs.getObject(i));
}
rows.addElement(newRow);
}
return new DefaultTableModel(rows, columnNames);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
} }
"I cannot get my JTable to update with a new row unless I restart the program."
“除非重新启动程序,否则我无法让JTable用新的行进行更新。”
I think what you're expecting is that when the database table update, so should your JTable
. 我认为您期望的是数据库表更新时,
JTable
应该更新。 It doesn't really work like that. 并不是真的那样。 You need to update the
TableModel
, and the JTable
will be automatically updated 您需要更新
TableModel
,并且JTable
将自动更新
Since resultSetToTableModel
returns a DefuaultTableModel
, you can use either of the two methods from DefaultTableModel
: 由于
resultSetToTableModel
返回DefuaultTableModel
,因此可以使用DefaultTableModel
中的两种方法之一:
public void addRow(Object[] rowData)
- Adds a row to the end of the model. public void addRow(Object[] rowData)
-在模型的末尾添加一行。 The new row will contain null values unless rowData is specified. 除非指定rowData,否则新行将包含空值。 Notification of the row being added will be generated.
将生成有关添加行的通知。
public void addRow(Vector rowData)
- Adds a row to the end of the model. public void addRow(Vector rowData)
-在模型的末尾添加一行。 The new row will contain null values unless rowData is specified. 除非指定rowData,否则新行将包含空值。 Notification of the row being added will be generated.
将生成有关添加行的通知。
So when your are adding the data to the database, you also want to update the DefaultTableModel
like this 因此,当您将数据添加到数据库时,您还想像这样更新
DefaultTableModel
public static void addGenre(Integer a, String b){
...
rowsAdded = stmt.executeUpdate(query);
if (rowsAdded > 0) {
DefaultTableModel model = (DefaultTableModel)tab1.getModel();
model.addRow( new Object[] { a, b });
}
}
Also noticed I changed the method signature to Integer
instead of int
so it will fit with the Object[]
passed to addRow
. 还注意到我将方法签名更改为
Integer
而不是int
因此它将与传递给addRow
的Object[]
匹配。 The int
you pass to it will get autoboxed to Integer
您传递给它的
int
将自动装箱为Integer
SIDE NOTES 旁注
Don't swallow you exception by putting nothing in the catch
block. 不要在
catch
块中放置任何内容来吞下您的异常。 Put something meaningful that will notify you of any exceptions that may occur, like 放置一些有意义的东西,它会通知您任何可能发生的异常,例如
catch(Exception ex) { ex.printStackTrace(); }
You should also close
your Connection
s, Statement
s, and ResultSet
s 您还应该
close
Connection
, Statement
和ResultSet
。
You should use PreparedStatement
instead of Statement
, to avoid SQL injection. 您应该使用
PreparedStatement
而不是Statement
,以避免SQL注入。
private void resetListData() throws ClassNotFoundException, SQLException
{
Connection cne = null;
try {
Class.forName("org.sqlite.JDBC");
cne = DriverManager.getConnection("jdbc:sqlite:table.sqlite");
cne.setAutoCommit(false);
PreparedStatement psd = (PreparedStatement) cne.prepareStatement("Select * from Genres");
psd.execute();
ResultSet r = psd.getResultSet();
ResultSetMetaData rsmd = r.getMetaData();
int count = rsmd.getColumnCount();
String[] meta = new String[count];
for (int i = 0; i < count; i++)
{
String name = rsmd.getColumnName(i + 1);
meta[i] = name;
//System.out.println(name);
}
model = new DefaultTableModel(new Object[][]{}, new String[]{"name", "address"});
jTable1.setModel(model);
while (r.next())
{
Object[] row = new Object[count];
for (int i = 1; i <= count; ++i)
{
row[i - 1] = r.getString(i); // Or even rs.getObject()
}
model.addRow(row);
}
cne.close();
} catch (ClassNotFoundException | SQLException e) {
}
}
Use this code. 使用此代码。 so you can insert one row at the end of Jtable without restarting application.,
因此您可以在Jtable的末尾插入一行,而无需重新启动应用程序。
Thanks.. 谢谢..
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.