慕神8447489
您犯的错误是每次打开视图面板时都会创建一个新的 JTable 。您不仅创建了一个新的,还将它添加到您的 view-JPanel中。这就是为什么你会得到奇怪的行为。此代码段解决了您的问题。我刚刚将removeAll()方法调用添加到 add-JPanel ActionListener。当 add-JPanel 打开时,旧的 JTable 将从视图 JPanel 中删除。我不得不注释掉你的数据库交互。 // ... // ... // ... add.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { if (viewpanel.isShowing()) { remove(viewpanel); /* * I basically just added this one line. * Since you want to make a fresh query after * you come back to the viewpanel, we can delete * all the elements (which is only the JTable). */ viewpanel.removeAll(); add(addpanel); } revalidate(); repaint(); } }); view.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { java.util.List<String[]> datalist = new ArrayList<>(); String[] columnNames = {"Emp ID", "Emp Name", "Department", "Basic Pay", "House Allowance", "Payee", "NHIF", "NSSF", "Pension", "NetPay"}; try { // String query = "SELECT * FROM payroll"; // Class.forName("com.mysql.jdbc.Driver"); // Connection con = DriverManager.getConnection(host, username, // password); // Statement st = con.prepareStatement(query); // ResultSet rs = st.executeQuery(query); String[] results = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"}; datalist.add(results); // con.close(); String[][] data = new String[datalist.size()][]; data = datalist.toArray(data); JTable table = new JTable(data, columnNames); JScrollPane sp = new JScrollPane(table); viewpanel.add(sp); } catch (Exception ex) { ex.printStackTrace(); } if (addpanel.isShowing()) { remove(addpanel); add(viewpanel); } else if (viewpanel.isShowing()) { remove(viewpanel); add(viewpanel); } revalidate(); repaint(); } }); // ... // ... // ...上面的解决方案当然不是唯一的。我不知道你想用这个 UI 去哪里,但你可以删除表格的内容并在再次打开 view-JPanel 时重新填充它们。另一种解决方案是专门删除 JTable(但在这种情况下,您可能需要将其作为字段,因为您在无法从add.addActionListener-Block 引用的块中创建表)第三种解决方案是添加一个布尔标志,它检查表是否已加载,如果没有,则仅创建一个新的 JTable。