从另一个 class 访问一个 jtable

Access a jtable from another class

我找到了类似的项目,但我就是无法理解如何去做。我有一个名为 HealthTracker 的 class,它包含一个 JTable。然后我有另一个名为 SQL 的 class,它具有我所有的 sql 相关方法。其中一种方法称为 populateTable。我可以进行查询等,但我不知道如何从我的 SQL class 访问位于 HealthTracker class 中的 JTable。这是我 SQL class.

的代码
public void populateTable(int qryType){ 
    try{
        DefaultTableModel tblModel = new DefaultTableModel(){
           @Override
           public boolean isCellEditable(int row, int column){
              return false;
           }
        };

        Connection dbconn = SQL.dbConn();
        Statement stmt = dbconn.createStatement();

        String qry = "SELECT * FROM Services";
        ResultSet rs = stmt.executeQuery(qry);

        int numCols = rs.getMetaData().getColumnCount();            
        for (int col = 1; col <= numCols; col++){
            tblModel.addColumn(rs.getMetaData().getColumnLabel(col));
        }

        int row = 0;
        while (rs != null && rs.next()){
            tblModel.addRow(new Object[0]);
            tblModel.setValueAt(rs.getString("ServiceID"), row, 0);
            tblModel.setValueAt(rs.getString("Institution"), row, 1);
            tblModel.setValueAt(rs.getString("Comments"), row, 2);
            row++;
        }   
        rs.close(); 

        // This is the line that gives me the error
        HealthTracker.this.tblMain.setModel(tblModel);

    } catch (Exception e){
        e.printStackTrace();
    }
}

这很好,但是我仍然需要能够从其他 classes 访问该 JTable。看到这段代码发生在应用程序首次加载以初始化 table 时,但用户需要能够过滤数据。所以我创建了一个过滤器按钮,显示另一个 window (SearchRecord.java class),用户可以在其中输入他们的参数,然后单击查找。单击 "find" 按钮后,我 运行 查询和 table 应重新加载新结果。也许我的处理方式不对?

public class SearchRecord {

    private JFrame frame;
    private JTextField txtInstitution;
    private JTextField txtStartDate;
    private JTextField txtEndDate;

    //  Launch the application
    public static void searchForm() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    SearchRecord window = new SearchRecord();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //  Create the application
    public SearchRecord() {
        initialize();
    }

    //  Initialize the contents of the frame
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 462, 180);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JLabel label = new JLabel("Enter Search Parameters");
        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setFont(new Font("Tahoma", Font.BOLD, 12));
        label.setBounds(10, 11, 414, 14);
        frame.getContentPane().add(label);

        JLabel lblInstitution = new JLabel("Institution: ");
        lblInstitution.setBounds(10, 47, 85, 14);
        frame.getContentPane().add(lblInstitution);
        lblInstitution.setHorizontalAlignment(SwingConstants.RIGHT);
        lblInstitution.setFont(new Font("Tahoma", Font.BOLD, 12));

        txtInstitution = new JTextField();
        txtInstitution.setBounds(98, 45, 326, 20);
        frame.getContentPane().add(txtInstitution);
        txtInstitution.setColumns(10);

        JLabel lblStartDate = new JLabel("Start Date: ");
        lblStartDate.setBounds(10, 78, 85, 14);
        frame.getContentPane().add(lblStartDate);
        lblStartDate.setHorizontalAlignment(SwingConstants.RIGHT);
        lblStartDate.setFont(new Font("Tahoma", Font.BOLD, 12));

        txtStartDate = new JTextField();
        txtStartDate.setBounds(98, 76, 175, 20);
        frame.getContentPane().add(txtStartDate);
        txtStartDate.setColumns(10);

        JButton button = new JButton("...");
        button.setBounds(283, 76, 25, 23);
        frame.getContentPane().add(button);

        JButton button_1 = new JButton("...");
        button_1.setBounds(283, 106, 25, 23);
        frame.getContentPane().add(button_1);

        JLabel lblEndDate = new JLabel("End Date: ");
        lblEndDate.setBounds(10, 109, 85, 14);
        frame.getContentPane().add(lblEndDate);
        lblEndDate.setHorizontalAlignment(SwingConstants.RIGHT);
        lblEndDate.setFont(new Font("Tahoma", Font.BOLD, 12));

        txtEndDate = new JTextField();
        txtEndDate.setBounds(98, 107, 175, 20);
        frame.getContentPane().add(txtEndDate);
        txtEndDate.setColumns(10);

        JButton btnFind = new JButton("Find");
        btnFind.setFont(new Font("Tahoma", Font.BOLD, 12));
        btnFind.setBounds(354, 106, 70, 23);
        frame.getContentPane().add(btnFind);

        //  Find Records
        btnFind.addActionListener(new ActionListener() 
        {
            public void actionPerformed(ActionEvent e) 
            {
                //  Gather all the fields from form
                String[] fields = new String[3];
                fields[0] = txtInstitution.getText();
                fields[1] = txtStartDate.getText();
                fields[2] = txtEndDate.getText();

                //  Refresh Table w/Filtered Data from DB
                SQL loadTbl = new SQL();
                try{
                    HealthTracker.this.tblMain.setModel(loadTbl.populateTable(0));
                } catch (SQLException e1){
                    e1.printStackTrace();
                }               
            }
        });     
    }
}

让您的 populateTable 方法 return 成为 TableModel 的实例,而不是让它尝试将模型应用于 JTable

的实例
public TableModel populateTable(int qryType) throws SQLException{ 
    DefaultTableModel tblModel = new DefaultTableModel(){
       @Override
       public boolean isCellEditable(int row, int column){
          return false;
       }
    };
    String qry = "SELECT * FROM Services";
    try (Connection dbconn = SQL.dbConn(); 
        Statement stmt = dbconn.createStatement();
        ResultSet rs = stmt.executeQuery(qry)) {

        int numCols = rs.getMetaData().getColumnCount();            
        for (int col = 1; col <= numCols; col++){
            tblModel.addColumn(rs.getMetaData().getColumnLabel(col));
        }

        int row = 0;
        while (rs != null && rs.next()){
            tblModel.addRow(new Object[0]);
            tblModel.setValueAt(rs.getString("ServiceID"), row, 0);
            tblModel.setValueAt(rs.getString("Institution"), row, 1);
            tblModel.setValueAt(rs.getString("Comments"), row, 2);
            row++;
        }   
    }
    return model;
}

这意味着该方法只有一个工作,加载TableModel,仅此而已。这也意味着您可以随时随地调用它