简体   繁体   中英

Jtable cant load data from database

I cant seems to load data into table despite being able to load column name dynamically. When I try to load data nothing appear despite the fact that Java Icon still showed on the taskbar. It doesn't look like there is anything wrong with GUI itself so I was wondering if opening a connection from constructor will cause logical error.I printed out the locals variables in the second for loop of populateTable method to check if data was passed into local variables and they did, so I don't know exactly what was causing this error.

here is the code for GUI:

public class WeatherFrame extends JFrame {

    private JPanel contentPane;
    private JTable table;
    HealthData health = new HealthData();
    private DefaultTableModel model;
    String[] columnNames = {"zipcode", "county", "city", "state", "year", "month","ageGroup",
                            "numOfVisits", "MonthlyMax", "MonthlyMin", "MonthlyNor"};

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    WeatherFrame frame = new WeatherFrame();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public WeatherFrame() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 800, 300);
        contentPane = new JPanel();
        contentPane.setBounds(100, 100,750, 200);
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setBounds(6, 25, 788, 180);
        contentPane.add(scrollPane);

        model = new DefaultTableModel();
        populateTable();
        table = new JTable(model);

        scrollPane.setViewportView(table);

        JButton btnInsert = new JButton("insert");
        btnInsert.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        btnInsert.setBounds(315, 217, 117, 29);
        contentPane.add(btnInsert);

        JButton btnDelete = new JButton("delete");
        btnDelete.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        btnDelete.setBounds(198, 243, 117, 29);
        contentPane.add(btnDelete);

        JButton btnSearch = new JButton("search");
        btnSearch.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        btnSearch.setBounds(81, 243, 117, 29);
        contentPane.add(btnSearch);

        JLabel lblWeatherTable = new JLabel("Weather Table");
        lblWeatherTable.setBounds(149, 6, 107, 16);
        contentPane.add(lblWeatherTable);

        JButton btnNext = new JButton("update");
        btnNext.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
        btnNext.setBounds(198, 217, 117, 29);
        contentPane.add(btnNext);

        JButton btnRefresh = new JButton("refresh");
        btnRefresh.setBounds(81, 217, 117, 29);
        contentPane.add(btnRefresh);
    }

    public void populateTable() {

        for(String name: columnNames)
            model.addColumn(name);

        ArrayList<Health> healthdata = new ArrayList<Health>();
        healthdata = health.showAllData();                                  
        model.addRow(healthdata.toArray()); 
    }
}

this is the constructor for the HealthData class

public HealthData(){
        try {
            /* Connect to database */
            connection = DriverManager.getConnection(jdbcURL, MySQLConfig.user, MySQLConfig.password);
            statement = connection.createStatement();
           data = new ArrayList<Health>();
        } catch (Exception e) 
        {
            e.printStackTrace();
        }

    }

this is the code for showAlldata method

public ArrayList<Health> showAllData(){
        ArrayList<Health> list = new ArrayList<Health>();
        try {
            connection = DriverManager.getConnection(jdbcURL, MySQLConfig.user, MySQLConfig.password);
            Statement stmt = connection.createStatement();
            ResultSet result = stmt.executeQuery(SELECT_ALL_QUERY);


            /* Get and print out data from health table : zipcode, county, city, state, year, month, ageGroup, numberOfVisits, MMax, MMin, MNor */
            while(result.next()){
                Health data = new Health();
                int zipcode = result.getInt(1);
                data.setZipCode(zipcode);
                String county = result.getString(2);
                data.setCounty(county);
                String city = result.getString(3);
                data.setCity(city);
                String state = result.getString(4);
                data.setState(state);
                int year = result.getInt(5);
                data.setYear(year);
                int month = result.getInt(6);
                data.setMonth(month);
                String ageGroup = result.getString(7);
                data.setAgeGroup(ageGroup);
                int numOfVisits = result.getInt(8);
                data.setNumOfVisits(numOfVisits);
                float MMax = result.getFloat(9);
                data.setMMax(MMax);
                float MMin = result.getFloat(10);
                data.setMMin(MMin);
                float MNor = result.getFloat(11);
                data.setMNor(MNor);
                list.add(data);     
                connection.close()
                stmt.close();   
            }   

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }

Can someone suggest a solution for solving this problem. Thank you in advance for helping. I already posted a question about this but this question is up to date with required codes.

I edit the code to make only one call to showAlldata and also close connection and statement, however, the same error still persist

public void populateTable() {

        model = new DefaultTableModel(){

            @Override
            public boolean isCellEditable(int row, int column) {
               //all cells false
               return false;
            }
        };

        for(String name: columnNames)
            model.addColumn(name);
        ArrayList<Health> temp = new ArrayList<Health>();
        temp = health.showAllData();
        for(int i = 0; i< temp.size(); i++) {
            Object[] data = {temp.get(i).getZipCode(), temp.get(i).getCounty(), temp.get(i).getCounty(), temp.get(i).getState(),temp.get(i).getYear(),
                             temp.get(i).getMonth(), temp.get(i).getAgeGroup(), temp.get(i).getNumOfVisits(), temp.get(i).getMMax(), temp.get(i).getMMin(), temp.get(i).getMNor()};
            model.addRow(data);
        }
    }

thank you very much for helping, I solved this question by modifying my populateTable Method as above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM