我如何刷新JTable?
这是我的代码。
public void itemStateChanged(ItemEvent evt)
{
String text=(String)to_Cmb2.getSelectedItem();
try
{
// Connect to an Access Database
Connection con=DriverManager.getConnection("jdbc:odbc:flightdsn");
Statement s=con.createStatement();
// Read data from a table
ResultSet rs = s.executeQuery("SELECT FlightNo,City,To,Arrives,Departs FROM I_Flights_Routes WHERE To ='"+text+"' ");
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.addElement(md.getColumnName(i));
}
// Get row data
while (rs.next())
{
Vector<Object> row = new Vector<>(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement(rs.getObject(i));
}
data.addElement(row);
}
rs.close();
s.close();
con.close();
}
catch (Exception e)
{
System.out.println(e);
}
// Create table with database data
JTable table = new JTable(data, columnNames)
{
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(50,10,400,200);
td.add(scrollPane);
// td is Jpanel object
td.setVisible(true);
}
答案 0 :(得分:3)
你正在创造一个全新的JTable - 不要这样做。使用相同的JTable但
另外,您可以避免使用空布局和setBounds(...)
,因为这会创建非常不灵活的GUI,在其他平台或其他分辨率上看起来很糟糕,并且很难升级和管理。