0

Actually I am making a program which takes .properties file and show the value in GUI. I am already done with reading and writing. Now, at this point I dont how to implement this add/remove rows functionality. I want to add a row on run-time. I am using abstract table How can I add and Delete rows.

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

public class StackoverflowStuff implements TableModelListener {

    public static void main(String[] args) {
        Vector<Vector> data = new Vector<>();
        String strState[] = new String[2];
        strState[0] = "Property";
        strState[1] = "value";
//        Vector<String> columnNames = new Vector<>();
        Vector<String> columnNames = new Vector<String>(Arrays.asList(strState));

        String line;
        try {
            FileInputStream fis = new FileInputStream("C:/properties/spanish.properties");
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            StringTokenizer st1 = new StringTokenizer(br.readLine(), "=");

            while (st1.hasMoreTokens()) {
                Vector row = new Vector();
                row.addElement(st1.nextToken());
                data.add(row);
            }
            while ((line = br.readLine()) != null) {
                if (line.contains("###") && (line.contains("#"))) {
                    continue;
                }
                StringTokenizer st2 = new StringTokenizer(line, "=");
                while (st2.hasMoreTokens()) {
                    Vector row1 = new Vector();
                    row1.addElement(st2.nextToken());
                    data.add(row1);

                }
                System.out.println("Selected ::  " + data);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        final int rows = data.size();
//        System.out.println("Selected ::  " + data.size());
//        final int columns = 2;
//        for (int i = 0; i < columns; i++) {
//            int dataas;
//            dataas = data.size() - 1;
//            System.out.println("Selected ::  " + dataas);
//            if (dataas % 2 == 0) {
//                columnNames.add("Property");
//            } else {
//                columnNames.add("Value");
//            }
//        }

//        for (int i = 0; i < rows; i++) {
//            Vector row = new Vector();
//            for (int j = 0; j < columns; j++) {
//                row.add(j);
//            }
//            data.add(row);
//        }
        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        final JTable table = new JTable(model);
        JButton saveBtn = new JButton("Save");

        JScrollPane jsPane;
        jsPane = new JScrollPane(table);
        JPanel panel = new JPanel();
        panel.add(jsPane, BorderLayout.CENTER);
        panel.add(saveBtn);
        JButton addRowbtn = new JButton("Add Row");
        panel.add(addRowbtn, BorderLayout.PAGE_START);
        try {
            addRowbtn.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent arg0) {

//                    myModel.setValueAt(table, table.getRowCount() + 1, 0);
//                    myModel.setValueAt(table, table.getRowCount(), 1);
                    System.out.println("sadasdasd");

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

        try {
            saveBtn.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent arg0) {

                    try {
                        BufferedWriter bfw = new BufferedWriter(new FileWriter("C:/properties/cwqesdb.properties"));
                        for (int i = 0; i < table.getRowCount(); i++) {
                            bfw.newLine();
                            for (int j = 0; j < 1; j++) {
                                if (j == 0) {
                                    bfw.write((String) (table.getValueAt(i, j)));
                                    System.out.println("Selected data: MouseDragged ::  " + table.getValueAt(i, j));

                                } else {
//                                    bfw.write((String) (table.getValueAt(i, j)));
//                                    bfw.write("=");
//                                    System.out.println("Selected data: MouseDragged ::  " + table.getValueAt(i, j));
                                }
                            }

                        }
                        bfw.flush();
                        bfw.close();
                        JOptionPane.showMessageDialog(null, "File Successfully Saved.");
                    } catch (IOException ex) {

                    }

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JOptionPane.showMessageDialog(null, panel);
    }

    @Override
    public void tableChanged(TableModelEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
}

here is my file contents spanisch.properties

username=Benutzername
password=Kennwort
gender=Geschlecht
male=männlich
female=weiblich
age=alter
### ewflmkdsajfaef ####sdasdfasdf
asfsadfsimpleasdf ####
asdas = asdashdash
address=Anschrift
submit=einreichen
message=Erfolgreich abgegeben ...

1 Answers1

1

"Kindly tell me how take out file reading stuff from the model"

In your model, you have two Vectors, one for the data, and one for the columns. Read the data to the vectors, then just create a DefaultTableModel with them. Though what may be messing you up, is that for the data you are using a single Vector for the data. The data should be two dimensional, so you would want a Vector<Vector>, just like if you were to use arrays for the data, it would be Object[][] data. So you may want to change your implementation to something like

Vector<Vector> data = new Vector<>();
Vector<String> columnName = new Vector();
...
while ((line = reader.nextLine()) != null) {
    Vector row = new Vector();
    // tokenize and add the `row`
    data.add(row);
}

DefaultTableModel model = new DefaultTableModel(data, columnsNames);
JTable table = new JTable(model);

See the DefaultTableModel API documentation for more methods you can use to manipulate the data.

Here's a simple example

import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class StackoverflowStuff {

    public static void main(String[] args) {
        Vector<Vector> data = new Vector<>();
        Vector<String> columnNames = new Vector<>();

        final int rows = 10;
        final int columns = 4;
        for (int i = 0; i < columns; i++) {
            columnNames.add("Col");
        }

        for (int i = 0; i < rows; i++) {
            Vector row = new Vector();
            for (int j = 0; j < columns; j++) {
                row.add(j);
            }
            data.add(row);
        }

        DefaultTableModel model = new DefaultTableModel(data, columnNames);
        JTable table = new JTable(model);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JOptionPane.showMessageDialog(null, new JScrollPane(table));
    }  
}

If you later want to add a row to the model, you can simply use the addRow method of DefaultTableModel, which is overloaded to accept a Vector or an Object[] array


UPDATE

What you are doing is

Vector<Vector> data = new Vector();
while (... ) {
    while(...) {
       Vector row = new Vector();
       String data = ...
       row.add(data);
       data.add(row);
    }
}

You adding a new row for each token, when you should be creating the row vector outside the loop, and adding the tokens inside the loop, then adding the row outside the loop

Vector<Vector> data = new Vector();
while (... ) {
    Vector row = new Vector();
    while(...) { 
       String data = ...
       row.add(data);
    }
    data.add(row);
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Thanku @peeskillet But now i got an error incompatible types: String cannot be converted to Vector while saving StringTokenizer to vector. – Jawad Satti Dec 01 '14 at 11:34
  • Seems like you forgot to create new `Vector` for each row and add that `Vector` the Vector. You may be trying to add a String to `Vector` – Paul Samsotha Dec 01 '14 at 11:39
  • here is [my code](http://pastebin.com/jVPJXaGA). I want to save the values as for example name=jawad I want to read this line and save "name" is column one and "jawad" in column 2. – Jawad Satti Dec 01 '14 at 12:50
  • I have a problem linking to pastebin. Edit your post with a snippet of the file – Paul Samsotha Dec 01 '14 at 12:54
  • I think you missed the part where I said I have a problem linking to pastebin. Edit your original post with a snippet of the file – Paul Samsotha Dec 01 '14 at 12:57
  • Did you also miss the part about the file snippet. I don't know what the contents of the file looks like. name=jawad tells me nothing – Paul Samsotha Dec 01 '14 at 13:01
  • You file has no consistent format whatsoever, so I won't even try anything with it. I can only suggest that you look at your logic. For each token, you are creating a Vector, adding one element to it, then adding the Vector to a the data Vector. Each Vector you add to the data Vector, will be a new row. Look at your code and debug using that knowledge – Paul Samsotha Dec 01 '14 at 13:12
  • plus one, but table.setPreferredScrollableViewportSize(table.getPreferredSize()); is only for reasonable numbers of columns & rows (success in this case) – mKorbel Dec 01 '14 at 13:19
  • @mKorbel Yeah I know I was going to post an image and didn't want to be to big, but then I got lazy and didn't post it :-) – Paul Samsotha Dec 01 '14 at 13:21
  • @JawadSatti look at my example code. I create the Vector inside the loop that creates each row, and outside the loop that creates each column – Paul Samsotha Dec 01 '14 at 13:23
  • Now I am getting this error. Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Vector. Can anybody please guide me. I am doing this final DefaultTableModel model = new DefaultTableModel(data, columnNames);. – Jawad Satti Dec 02 '14 at 09:46