简体   繁体   中英

How to add a row in Jtable

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 ...

"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);
}

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