[英]Refresh JTable data in Swing
I have added text field and jTable in same frame. 我在同一框架中添加了文本字段和jTable。 After getting value from the text field on jButton1 click, I am inserting the value in database and the same data is getting displayed in jTable . 从jButton1单击上的文本字段获取值后,我将值插入数据库中,并且jTable中显示了相同的数据。 But the problem is my table is not getting updated itself after adding data . 但是问题是我的表在添加数据后没有得到更新。 I have to evrytime execute the program to get table update . 我必须evrytime执行该程序以获取表更新。 I have tried Frame.invalidate, Frame.validate, Frame.repaint , tbale.repaint
but nothing worked out , where am I going wrong Thank you in advance..! 我已经尝试过Frame.invalidate, Frame.validate, Frame.repaint , tbale.repaint
但没有解决,我要去哪里错了,谢谢!
public class mainFrame extends javax.swing.JFrame {
static JTable table;
static Connection connection;
static Statement statement;
static JTable jTable1;
static int count;
static String r;
/**
* Creates new form mainFrame
*/
public mainFrame() {
super();
initComponents();
setLocation(500, 180);
try {
//----------database
Class.forName("org.sqlite.JDBC");
connection = null;
connection = DriverManager.getConnection("jdbc:sqlite:excel.db");
statement = connection.createStatement();
statement.executeUpdate("CREATE TABLE IF NOT EXISTS testing (id INTEGER PRIMARY KEY , namexcel string)");
//--------
final String queryCheck = "SELECT count(*) from testing";
final PreparedStatement ps = connection.prepareStatement(queryCheck);
// ps.setString(1, name);
final ResultSet resultSet = ps.executeQuery();
if (resultSet.next()) {
count = resultSet.getInt(1);
System.out.println(count);
}
String read = "select * from testing";
ResultSet rs = statement.executeQuery(read);
Object[][] data = new Object[count][2];
int i = 0;
while (rs.next()) {
for (int c = 0; c < 1; c++) {
data[i][c] = rs.getString("namexcel");
}
i++;
}
String[] headers = {"Name"};
table = new JTable(data, headers);
jScrollPane2.setViewportView(table);
// pack();
} catch (Exception e) {
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
//.....
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
String link = jTextField1.getText();
System.out.println("" + link + "");
jTextField1.setText("");
File f = new File("" + link + "");
if (!f.exists()) {
JOptionPane.showMessageDialog(null, "File Doesnt Exist....!!");
} else {
FileInputStream file = new FileInputStream(f);
XSSFWorkbook workbook = new XSSFWorkbook(file);
String name = workbook.getSheetName(0);
System.out.println(name);
final String queryCheck = "SELECT count(*) from testing WHERE namexcel = ?";
final PreparedStatement ps = connection.prepareStatement(queryCheck);
ps.setString(1, name);
final ResultSet resultSet = ps.executeQuery();
if (resultSet.next()) {
final int count = resultSet.getInt(1);
if (count == 0) {
JOptionPane.showMessageDialog(null, "thank you");
statement.executeUpdate("insert into testing (namexcel) values('" + name + "')");
mainFrame frame = new mainFrame();
frame.invalidate();
frame.validate();
table.revalidate();
} else {
JOptionPane.showMessageDialog(null, "Name Already exist please select diffrent name of excel");
}
}
}
} catch (Exception r) {
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) throws Exception {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception ex) {
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new mainFrame().setVisible(true);
}
});
}
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
public static javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextField jTextField1;
} }
following is the inicomponent method 以下是inicomponent方法
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jScrollPane2 = new javax.swing.JScrollPane();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
jButton1.setText("Add");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel1.setFont(new java.awt.Font("Dialog", 1, 11)); // NOI18N
jLabel1.setText("Add Excel Sheet Link");
jTextField1.setText("");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(26, 26, 26)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jTextField1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap())))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 13, Short.MAX_VALUE)
.addComponent(jButton1)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 394, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(20, Short.MAX_VALUE))
);
pack();
}
Don't do table = new JTable(data, headers);
不做table = new JTable(data, headers);
in your constructor. 在您的构造函数中。 You are derefrencing the initial table you drag and dropped. 您正在取消引用拖放的初始表。 Sure jScrollPane2.setViewportView(table);
确定jScrollPane2.setViewportView(table);
might have fixed it (by set the viewport to the new table) but this is unnecessary, and smells of future problems if you don't understand what's going on. 可能已经修复了它(通过将视口设置为新表),但这是不必要的,并且如果您不了解正在发生的情况,还会闻到将来的问题。
Instead work with the table's model to update. 而是使用表的模型进行更新。 So instead of the table = new JTable
, do 因此,代替table = new JTable
,执行
DefaultTableModel model = new DefaultTableModel(data, headers); table.setModel(model);
That's it. 而已。
To update the table, just update the model, upon successful update in the database. 要更新表,只需在数据库中成功更新后更新模型即可。
if (successfulInsert) { DefaultTableModel model = (DefaultTableModel)table.getModel(); Object[] row = .... // get the data for the row model.addRow(row); }
See more at How to Use Tables and Creating a TableModel and DefaultTableModel API 有关更多信息,请参见如何使用表以及如何 创建TableModel和DefaultTableModel API。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.