如何在Jtable中添加一行

时间:2014-11-28 13:59:49

标签: java swing vector jtable abstracttablemodel

实际上我正在创建一个程序,它接受.properties文件并在GUI中显示值。我已经完成了阅读和写作。现在,在这一点上,我不知道如何实现这个添加/删除行功能。我想在运行时添加一行。我正在使用抽象表如何添加和删除行。

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

这是我的文件内容 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 个答案:

答案 0 :(得分:1)

  

“请告诉我如何从模型中取出文件读取内容”

在您的模型中,您有两个Vectors,一个用于数据,另一个用于列。将数据读取到向量,然后用它们创建DefaultTableModel。虽然可能会让您感到困惑,但对于您使用单个Vector数据的数据而言。数据应该是二维的,所以你需要Vector<Vector>,就像你使用数组一样,它就是Object[][] data。因此,您可能希望将实现更改为

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

有关可用于操作数据的更多方法,请参阅DefaultTableModel API文档。

这是一个简单的例子

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

如果您以后想要在模型中添加行,则只需使用DefaultTableModel Vector方法,该方法已重载以接受Object[]或{{1} } array


更新

你在做什么

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

为每个标记添加一个新行,当你应该在循环外创建行向量,并在循环内添加标记,然后在循环外添加行

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