【发布时间】:2018-12-12 10:22:11
【问题描述】:
我的 JPanel 类中有数据库 JTable,我想在我的 JFRame 类中使用它
我希望通过单击一些按钮来自动更新我的 JTable
它不是错误,但它不想自动更新,除非我将 Jframe 放在 Jpanel 类上,这将创建一个新的 Frame
这是我的 JPanel
public class TUsers extends JPanel {
private static final long serialVersionUID = 1L;
String [] header = {"Id","name","address"};
JTable BTab = new JTable();
JScrollPane scrPnl = new JScrollPane();
public Object [][] table = null;
TUsers(){
Dbcon dc = new Dbcon();
Connection psql = dc.getConnection();
try
{
Statement stmt = psql.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
String sql = "SELECT * FROM public.patrons ORDER BY id ASC";
ResultSet res = stmt.executeQuery(sql);
ResultSetMetaData meta = res.getMetaData();
int y = meta.getColumnCount();
int x = 0;
while(res.next())
{
y = res.getRow();
}
table = new Object[x][y];
int n = 0;
res.beforeFirst();
while(res.next())
{
table[n][0]=res.getString("Id");
table[n][1]=res.getString("name");
table[n][2]=res.getString("address");
x++;
}
scrPnl.setViewportView(BTab);
BTab.setModel(new DefaultTableModel(table, header));
TableColumnModel table = BTab.getColumnModel();
table.getColumn(0).setPreferredWidth(2);
table.getColumn(1).setPreferredWidth(100);
table.getColumn(2).setPreferredWidth(180);
scrPnl.setPreferredSize(new Dimension(350, 120));
add(scrPnl, BorderLayout.CENTER);
revalidate();
repaint();
stmt.close();
res.close();
来自我的 JFrame 类
public class AddUser extends JFrame {
TUsers t = new TUsers();
AddUser()
{
setTitle("Admin");
setLocation(400,400);
setSize(400, 400);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
void Layout()
{
getContentPane().add(t).setBounds(10, 225, 350, 150);
//if i delete this it wont show the table
setVisible(true);
}
void EventHandle()
{
b_crt.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Dbcon dc = new Dbcon();
Connection psql = dc.getConnection();
try
{
Statement stmt = psql.createStatement();
String sql = "INSERT INTO public.patrons VALUES ('"
+t_id.getText()+"','"
+t_usrnm.getText()+"','"
+t_adrs.getText()+"');";
int i = stmt.executeUpdate(sql);
if(i == i)
{
JOptionPane.showMessageDialog(null, "Success");
}
Clear();
}
catch(Exception x)
{
JOptionPane.showMessageDialog(null, x.getMessage());
}
TUsers t = new TUsers();
}
});
}
}
我已经放了
我的 JPanel 上的 repaint() 和 revalidate() 但它不起作用
【问题讨论】:
-
当您认为数据库中的数据已更改时,您需要重新加载
TableModel -
我在 Create ActionListener 上调用 Table 类,但它不会更改我的 JFrame 上的表,除非我重新打开它
-
为什么要这样?您正在创建该类的一个新实例,该实例未显示在屏幕上,或者与屏幕上实际显示的任何内容有任何关系
-
所以我必须在我的 ActionListener 中重新加载
TableModel? t.fireTableDataChanged();? -
不,表数据没变,数据库有,需要重新从数据库中拉取结果,更新表模型
标签: java swing user-interface awt