1
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);

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

        scrollPane.setViewportView(table);

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

        JButton btnDelete = new JButton("delete");
        btnDelete.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                DeleteFrame delete = new DeleteFrame();
                delete.setVisible(true);
            }
        });
        btnDelete.setBounds(412, 217, 117, 29);
        contentPane.add(btnDelete);

        JButton btnSearch = new JButton("search");
        btnSearch.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                SelectFrame search = new SelectFrame();
                search.setVisible(true);
            }
        });
        btnSearch.setBounds(530, 217, 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) {
                UpdateFrame update = new UpdateFrame();
                update.setVisible(true);
            }
        });
        btnNext.setBounds(150, 217, 117, 29);
        contentPane.add(btnNext);

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

        JButton btnAnalyze = new JButton("Analyze");
        btnAnalyze.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ShowAnalyze analyze = new ShowAnalyze(health.analyze());
                analyze.setVisible(true);
            }
        });
        btnAnalyze.setBounds(662, 217, 117, 29);
        contentPane.add(btnAnalyze);
    }

    @SuppressWarnings("serial")
    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);
        }
        table.setModel(model);
    }
}

I'm trying to refresh the jtable using a refresh button, when I click the button it seems like it is loading, but after that nothing changes on the table. How can I fix this problem? In the action performed method of the refresh button, I called populateTable which is a function to load data into table.

KhoaVo
  • 376
  • 3
  • 18
  • 1
    1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Dec 03 '15 at 12:31
  • would refresh button work if it put `revalidate();` and `repaint();` inside the action performed method? – KhoaVo Dec 03 '15 at 12:46
  • I added `table.setModel(model)` to populatTable method, but at this point I'm getting null pointer exception – KhoaVo Dec 03 '15 at 13:28
  • Avoid using `null` layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify – MadProgrammer Dec 03 '15 at 22:48

2 Answers2

3
  • JTable and its DefaultTableModel (desclared as private JTable table; and private DefaultTableModel model;) doesn't know something that a new model = new DefaultTableModel(){ is (re)created in public void populateTable() {,

you have to

  • add a new DefaultTableModel to JTables instance that is already visible in your Swing GUI

  • (better option is) add a new data directly to private DefaultTableModel model;, this model is designated for

  • rest is very well described in comment by @ Andrew Thompson

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • yes, I think the second option is what I did, I called the populateTable method, which add new data directly to `private DefaultTableModel model;` but It doesn't refresh at all – KhoaVo Dec 03 '15 at 12:55
3

In the populateTable method, you change the table model but you do not pass that new model to the JTable.

Option 1: replace the table model

In the constructor, you call:

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

In the populateTable, I would expect something like:

table.setModel(model);

Option 2: update the table model

As mKorbel already suggested, you can also update your table model instead of throwing the existing model away and creating a new one. Your populateTable method could look like this (using Java 8 and with a new initializeModel method to create the table model initially):

public void populateTable() {
    boolean firstTime = (model == null);

    if (firstTime) {
        initializeModel();
    } else {
        model.getDataVector().clear();
    }

    for (Health item : health.showAllData()) {
        model.addRow(new Vector<>(Arrays.asList(
                item.getZipCode(), item.getCounty(), item.getState(), item.getYear(),
                item.getMonth(), item.getAgeGroup(), item.getNumOfVisits(),
                item.getMMax(), item.getMMin(), item.getMNor()
        )));
    }

    if (firstTime && table != null) {
        table.setModel(model);
    }
}

private void initializeModel() {
    model = new DefaultTableModel() {
        @Override
        public boolean isCellEditable(int row, int column) {
            //all cells false
            return false;
        }
    };

    for (String name : columnNames)
        model.addColumn(name);
}
Community
  • 1
  • 1
Freek de Bruijn
  • 3,552
  • 2
  • 22
  • 28
  • Weird I added `table.setModel(model);` to the last line of populateTable method and i get null pointer exception – KhoaVo Dec 03 '15 at 13:14
  • That's because in the constructor, the `populateTable` method is called before the table is initialized. You could add a check to the `setModel` call, see my answer. – Freek de Bruijn Dec 03 '15 at 14:24
  • Thanks, I followed your input, and fix the problem by calling populateTable after I initialized the table – KhoaVo Dec 03 '15 at 14:47