1

I'm trying to replace one Jtable already defined with tis correponding Vector of vector data by other with the same carateristics stored in a file. Here my code:

   else if (e.getActionCommand().equals("import"))
        {
            JFileChooser file = new JFileChooser();
            int i = file.showOpenDialog(this);

            if(i == JFileChooser.APPROVE_OPTION)
            {
                File f = file.getSelectedFile();
                String filePath = f.getPath();

                try
                {
                    ObjectInputStream input = new ObjectInputStream(new FileInputStream(filePath));
                    Vector vectorData = (Vector)input.readObject();
                    data = new DefaultTableModel(vectorData, columNames);
                    table = new JTable(data);

                    labelStatus.setText("Archivo exitosamente importado.");

                } catch (FileNotFoundException e1)
                {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } 

Problem here is that when i make the import and select the file that contains the Jtable data the Actual Table no change by the Imported one, how can i make the Switch?

Here code where the Jtable is added into ContentPane(Jpanel):

 //data & columnNames are the data tha i used originally with the old Jtable
DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model);

        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model); //Sorter Descending or Ascending the  data.
        table.setRowSorter(sorter);

        JScrollPane scrollTable = new JScrollPane(table);
        scrollTable.setBounds(22, 78, 764, 177);
        scrollTable.setViewportView(table);

        contentPane.add(scrollTable);

Note: I'm using a single Jtable, DefaaultTableModel using it as Global Variable and referencing from the Import method to change the odl one by the new one but using the same .

New Update, whole functional code:

public class Demo extends JFrame implements ActionListener
{

    private JPanel contentPane;
    DefaultTableModel data;
    JTable table;
    Vector<String> dataRow;
    Vector<String> columnNames;
    JScrollPane scrollTable;

public Demo() throws FileNotFoundException, IOException, ClassNotFoundException
    {
        columnNames = new Vector<>();
        columnNames.addElement("Name");
        columnNames.addElement("Cc");
        columnNames.addElement("Age");
        columnNames.addElement("Phone");
        columnNames.addElement("Date");
        columnNames.addElement("Amount");

        ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:/Users/Harry/Desktop/AA gym Database.txt"));
        Vector data = (Vector)in.readObject(); //Add try catch instead of THROWS DECLARATION.

                                                     //rowData
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        table = new JTable(model);



        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model); //Sorter Descending or Ascending the  data.
            table.setRowSorter(sorter);

            scrollTable = new JScrollPane(table);
            scrollTable.setBounds(22, 78, 764, 177);
            scrollTable.setViewportView(table);

            contentPane.add(scrollTable);

public void actionPerformed(ActionEvent e)
    {
        else if (e.getActionCommand().equals("import"))
        {
            JFileChooser file = new JFileChooser();
            int i = file.showOpenDialog(this);

            if(i == JFileChooser.APPROVE_OPTION)
            {
                File f = file.getSelectedFile();
                String filePath = f.getPath();

                try
                {

                    ObjectInputStream input = new ObjectInputStream(new FileInputStream(filePath));
                    Vector vectorData = (Vector)input.readObject();
                    data = new DefaultTableModel(vectorData, columnNames);
                    table.setModel(data);
}
}
}
}
Volazh
  • 126
  • 2
  • 13
  • Can you show the code where you're adding the new `JTable` to your `JFrame` please? – Dawood ibn Kareem Aug 14 '16 at 01:13
  • So, you're adding a table to the frame when it's drawn. Later on, you create a new table. Where do you add this _new_ table to the frame? – Dawood ibn Kareem Aug 14 '16 at 01:22
  • Please post a [mcve] or a [sscce](http://sscce.org/), as is we don't have enough information to see what's wrong; please note we don't need your whole code, but the minimal one, that still runs and shows your issue and we can copy-paste it into our IDE w/o modifications and we can see it. Also note that it's unclear what you're asking, please be more specific and clear while explaining your question – Frakcool Aug 14 '16 at 01:24
  • Good. So _that's_ the code I'm asking about. You haven't shown the code where you add the _new_ table to the frame. – Dawood ibn Kareem Aug 14 '16 at 01:25
  • No i'm not adding a new Table to the frame, instead i'm using the existing one, by replacing it – Volazh Aug 14 '16 at 01:25
  • The code that you've shown creates a new table. When it does that, the existing table is still in the frame. Where is the code to add the new table to the frame? Or haven't you written it yet? – Dawood ibn Kareem Aug 14 '16 at 01:26
  • 1
    @DavidWallace from what I understand, what OP is trying to do is update the data of the model from a file, not 100% sure but that's what I've understood so far – Frakcool Aug 14 '16 at 01:27
  • 1
    Thanks, @Frakcool. I am trying to make the OP understand what he has failed to do, by asking him questions. – Dawood ibn Kareem Aug 14 '16 at 01:28
  • yes @Frakcool is right, i'm trying to update the old jtable data by a new one stored into a file – Volazh Aug 14 '16 at 01:29
  • It's not "Francool", it's Frakcool, read again my name please and read the link I provided, and follow the suggestions – Frakcool Aug 14 '16 at 01:30
  • @Volazh. Do you understand that the code you have been written doesn't update the old JTable? You're making a new DefaultTableModel and a new JTable. You're not updating the old one at all. Unfortunately, there's no code to actually display your new JTable. – Dawood ibn Kareem Aug 14 '16 at 01:32
  • @DavidWallace So, from this code do I can't update the table? – Volazh Aug 14 '16 at 01:34
  • Try the suggestions [here](http://stackoverflow.com/a/12626327/230513). – trashgod Aug 14 '16 at 01:42
  • @Volazh As I said, the code you've shown here doesn't change the existing table. You need to do something different from what you're doing. You could either (1) replace the model with a new one (as per camickr's excellent answer), or (2) replace the table within the GUI (probably not as good), or (3) remove and add rows in the existing model. But just changing the value of a variable that the GUI can't see is NOT going to do it for you. – Dawood ibn Kareem Aug 14 '16 at 02:39

1 Answers1

2
data = new DefaultTableModel(vectorData, columNames);
table = new JTable(data);

You are creating a new TableModel and a new JTable.

The problem is you never add the new table to the GUI. You can't just change the reference to the "table" variable and expect the table to be added to the GUI.

So the solution is to NOT create a new JTable. Instead you just reset the TableModel of the existing JTable:

data = new DefaultTableModel(vectorData, columNames);
table.setModel( data );

Basically you should not be creating new Swing components when you want to change the data. Just change the model.

Edit:

Check out Saving content of Interactive JTable to .txt file to read it upon next run for a solution that will allow your to save/restore a table.

Community
  • 1
  • 1
camickr
  • 321,443
  • 19
  • 166
  • 288
  • I tried but an : java.lang.ArrayIndexOutOfBoundsException: 5 >= 5 error throws me – Volazh Aug 14 '16 at 02:04
  • @-Camickr .I had published the whole functional code, which already implements your suggestion but still throws an error. – Volazh Aug 14 '16 at 02:13
  • @Volazh, `I tried but... ` I have no idea what statement is causing that problem. `I had published the whole functional code,` no you haven't. We can't execute the code you posted. We don't have access to your input file. Check out my edit for a better way to save data in a table. – camickr Aug 14 '16 at 05:39
  • @-Camickr, thanks for your support it really helps me a lot, i already found the problem, it was cuz i was creating a new DefaultTableModel without referencing the existing JTable.getModel. so i solved my problem by implementing this: DefaultTableModel tmodel = (DefaultTableModel)table.getModel(); tmodel.setDataVector(vectorData, columnNames); tmodel.fireTableDataChanged(); – Volazh Aug 14 '16 at 14:57
  • @Volazh, `i was creating a new DefaultTableModel without referencing the existing JTable.getModel` - no that is not the problem, There is no need to reference the existing TableModel. You can replace the data in the model (as you say you have done) **OR** you can create a completely new table model and use the setModel(...) method as long as you have a proper reference to the table. Both approaches should work. Also you should never invoke fireTableDataChanged() directly, that is the job of the table model. – camickr Aug 14 '16 at 17:05