In a JTable when selectin a value of the row it shows me the previous value

时间:2021-07-25 12:21:00

标签: java swing jdbc jtable

我在做一个大学项目,遇到了一个错误。

我从我的数据库中获得了 3 个值(名称、地址、类型),我想在 JTable 中显示它们并且它可以工作,但是当我进行另一个查询搜索另一个值时,它在表中显示给我但是,当我按下一行时,表格会显示上一个值。

例如

第一次查询:名称=centerName1,地址=假街道-假城市,类型=医院 |姓名 |地址 |类型 | |:---: | :------: |:----: | |中心名称1|假街-假城市| 高分辨率照片| CLIPARTO医院|

第二次查询:名称=centerName2,地址=假街道2-假城市2,类型=医院 |姓名 |地址 |类型 | |:---: | :------: |:----: | |中心名称2|假街道2 - 假城市2 |医院|

在第二次查询之后,表格在“Nome Centro”、“Indirizzo”、“Tipo Centro”列中显示了我的值“centerName2”、“fake street 2 - fake city 2”、“hospital”但是,当我按下值更改为“centerName1”、“fake street - fake city”、“hospital”的行。

有人知道可能是什么问题吗?

感谢您的帮助。

homepage.java 类:

...
        search.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                
                String researchText = find.getText();
                
                List<InfoCentriVaccinali> centriVaccinali = new ArrayList<>();
                if(researchText != null && researchText.trim().length() > 1)
                    try {
                        centriVaccinali = stub.cercaCentroVaccinale(researchText);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    
                
                String[] columnNames = {"Nome centro", "Indirizzo", "Tipo Centro"};
                DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
                
                table = new JTable(tableModel) {
                    public boolean editCellAt(int row, int column, java.util.EventObject e) {
                        return false;
                     }
                };
                table.setRowSelectionAllowed(false);
                
                for(int i=0; i<centriVaccinali.size(); i++) {
                    String nome = centriVaccinali.get(i).getNomeCentro();
                    String indirizzo = centriVaccinali.get(i).getIndirizzo();
                    String tipo = centriVaccinali.get(i).getTipoCentro();
                    
                    Object[] infoData = {nome, indirizzo, tipo};
                    
                    tableModel.addRow(infoData);
                }
                
                
                scrollPane = new JScrollPane(table);
                scrollPane.setBounds(1, 150, 798, 150);
                panel_Homepage.add(scrollPane);
            }
        });

InfoCentriVaccinali.java 类:

public class InfoCentriVaccinali implements Serializable {
    
    private String nomeCentro;
    private String indirizzo;
    private String tipoCentro;
    
    public InfoCentriVaccinali(String nomeCentro, String indirizzo, String tipoCentro) {
        this.nomeCentro = nomeCentro;
        this.indirizzo = indirizzo;
        this.tipoCentro = tipoCentro;
    }
    
    public String getNomeCentro() {
        return nomeCentro;
    }
    
    public String getIndirizzo() {
        return indirizzo;
    }
    
    public String getTipoCentro() {
        return tipoCentro;
    }
}

1 个答案:

答案 0 :(得分:2)

您没有从 GUI 中删除上一个表格。您只需添加新的。并且由于没有 LayoutManager(您将其设置为 null),因此每次设置时将表添加到面板中,所有这些表都会在同一个位置结束。您还为每次搜索创建了一个带有新表模型的新表,而不是使用带有单个模型的单个表。

所以你可以做的是:

  1. 使用正确的 LayoutManager
  2. 在构造函数中一次性添加所有 Component(包括一张表)。
  3. 将表的模型设置为 DefaultTableModel
  4. 对于每次搜索,更新您为单个表创建的 DefaultTableModel,而不是每次都创建一个新模型和一个新表。

遵循部分更正的代码以正确更新表(假设您取消注释返回结果列表的相关 RMI 调用),但它尚未使用 LayoutManager

import java.awt.Color;
import java.awt.event.*;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;


public class HomepageGUI extends JFrame {
    
    private static final int WIDTH          = 800;
    private static final int HEIGHT         = 600;
    private static final String FIND        = "Ricerca per Nome, Comune, Provincia o Vaccino";
    
    boolean resetText = true;
    
    JPanel panel_Homepage;
    JFrame frame_Homepage;
    JLabel log_Citizen;
    JLabel log_Doctor;
    ImageIcon searchPicture;
    JButton search;
    JTextField find;
    JTable table;
    DefaultTableModel tableModel;
    JScrollPane scrollPane;
    
    public HomepageGUI() {
        panel_Homepage = new JPanel();
        frame_Homepage = new JFrame();
        
        frame_Homepage.setTitle("CENTRI VACCINALI");
        frame_Homepage.setSize(WIDTH, HEIGHT);
        frame_Homepage.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame_Homepage.setResizable(false);
        frame_Homepage.setLocationRelativeTo(null);
        frame_Homepage.add(panel_Homepage);
        
        panel_Homepage.setLayout(null);
        
        /**
         * Label cittadino
         */
        log_Citizen = new JLabel("Login as a citizen");
        log_Citizen.setBounds(650, 20, 100, 25);
        panel_Homepage.add(log_Citizen);
        
        /**
         * Label dottore
         */
        log_Doctor = new JLabel("Login as a doctor");
        log_Doctor.setBounds(650, 40, 100, 25);
        panel_Homepage.add(log_Doctor);
        
        /**
         * Bottone ricerca
         */
        searchPicture = new ImageIcon("ext-img/Search.png");
        search = new JButton(searchPicture);
        search.setBounds(171, 100, 29, 29);
        
        tableModel = new DefaultTableModel(new String[]{"Nome centro", "Indirizzo", "Tipo Centro"}, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        table = new JTable(tableModel);
        
        search.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                
                String researchText = find.getText();
                
                List<InfoCentriVaccinali> centriVaccinali = new ArrayList<>();
                if(researchText != null && researchText.trim().length() > 1)
                    ; //Read from RMI server here... Code commented out because of no MRE in the question.
//                    try {
//                        centriVaccinali = stub.cercaCentroVaccinale(researchText);
//                    } catch (Exception ex) {
//                        ex.printStackTrace();
//                    }

                tableModel.setRowCount(0); //Removes all existing rows from the table model.
                
                for(int i=0; i<centriVaccinali.size(); i++) {
                    String nome = centriVaccinali.get(i).getNomeCentro();
                    String indirizzo = centriVaccinali.get(i).getIndirizzo();
                    String tipo = centriVaccinali.get(i).getTipoCentro();
                    
                    System.out.println(nome);
                    System.out.println(indirizzo);
                    System.out.println(tipo);
                    
                    Object[] infoData = {nome, indirizzo, tipo};
                    
                    tableModel.addRow(infoData); //Just adds to the model which updates the table.
                }
            }
        });
        table.setRowSelectionAllowed(false);
        scrollPane = new JScrollPane(table);
        scrollPane.setBounds(1, 150, 798, 150);
        panel_Homepage.add(scrollPane);
        panel_Homepage.add(search);
        
        /**
         * Campo ricerca
         */
        find = new JTextField(20);
        find.setText(FIND);
        find.setBounds(200, 100, 400, 29);
        panel_Homepage.add(find);
        
        frame_Homepage.setVisible(true);
        
        
        log_Citizen.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseReleased(MouseEvent e) {
                //LoginCitizenGUI LogCitizen = new LoginCitizenGUI(stub);
                frame_Homepage.dispose();
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                log_Citizen.setForeground(Color.RED);
            }

            @Override
            public void mouseExited(MouseEvent e) {
                log_Citizen.setForeground(Color.BLACK);
            }
        });
    
        log_Doctor.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                //LoginDoctorGUI LogDoctor = new LoginDoctorGUI(stub);
                frame_Homepage.dispose();
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                log_Doctor.setForeground(Color.RED);
            }

            @Override
            public void mouseExited(MouseEvent e) {
                log_Doctor.setForeground(Color.BLACK);
            }
            
        });
        
        find.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(resetText) {
                    find.setText("");
                    resetText = false;
                }
            }
        });
    }
    
    public static void main(final String[] args) {
        SwingUtilities.invokeLater(() -> {
            new HomepageGUI();
        });
    }
}

RMI 和 JDBC 似乎无关。

其他注意事项:

为了您/我们的方便,您还可以使用 MouseAdapterMouseInputAdapter 等类,以便不必实现 MouseListener 的所有方法。这些类使用空体方法实现 MouseListener 接口,因此您可以覆盖所需的方法。