user2670495
user2670495

Reputation: 27

how to refresh contents of jtable on event of action listener?

i have used following code to display jtable in a new panel in existing dialog. i have used mytablemodel class for table model and setmodel method is just like constructor(since i have to create several table using same model object so i have used method instead of constructor).But some how my jtable does not change the contents on actionlisten..same contents reappera even if value of input is changed...plz help

 btnShow.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
         showTable();

        }

    });
    panel_1.add(btnShow);

private void showTable() {
     fillData();
    //filldata used to fill object data for table using date specified by user                   


                MyTableModel model=new MyTableModel();
                model.setModel(data,col,totalrow);
                table = new JTable(model);
                table.setForeground(new Color(255,0,0) );
                System.out.println("after table");
                panel_2.add(new JScrollPane(table));
                panel_2.setVisible(true);
                table.setVisible(true);
                System.out.println("after scroll pane");

 }

Upvotes: 0

Views: 1847

Answers (2)

camickr
camickr

Reputation: 324128

But some how my jtable does not change the contents

That is because you are creating a new table but that table is not visible on the GUI.

panel_2.add(new JScrollPane(table));

This just adds a component to the GUI but the size of the component is (0, 0). When you add a component to a visible GUI you need code like:

panel.add(...); panel.revalidate(); panel.repaint(); // sometimes needed

Then the layout manager will be invoked on the panel and the added component will be displayed in the appropriate position.

However, the better solution is to update/replace the existing model in the displayed table as suggested by Xabster.

Upvotes: 1

Xabster
Xabster

Reputation: 3720

Don't create a new JTable each time. Instead, get the model and replace/edit the data (best), or give the table a new model ("ok").

After a model's data has been changed, you need to call a "fireTableXXX" method.

You can call .fireTableDataChanged() which will reload all data. There are also methods for specifying which rows or cells were changed, so that it doesn't have to reload it all.

Upvotes: 4

Related Questions