addrow method in DefaultTableModel is not adding rows

时间:2018-07-24 10:19:35

标签: java netbeans jtable defaulttablemodel

I have some data in MySQL which has to be retrieved and showed in JTable. Code I wrote for that is as follows

PreparedStatement ps = con.prepareStatement("select * from " + chosenClass     
                                          + " where subjects=?;");
ps.setString(1, selectedGroup);
rs = ps.executeQuery();
rs.next();
subjects[0] = rs.getString("sub1");
subjects[1] = rs.getString("sub2");
subjects[2] = rs.getString("sub3");
subjects[3] = rs.getString("sub4");
subjects[4] = rs.getString("sub5");
subjects[5] = "H.V";

tableModel.setColumnIdentifiers(new Object[]{"RollNo", "Name", subjects[0], subjects[1], 
subjects[2], subjects[3], subjects[4], subjects[5]});

tableModel = (DefaultTableModel) StuMarks_TBL.getModel();
//I tried this after some help from internet

String classToGet = "";
if (chosenClass.matches("class12subjects")) {
    classToGet = "XII";
} else if (chosenClass.matches("class11subjects")) {
    classToGet = "XI";
}

 Query = "select sd.rollno, name, sub1, sub2, sub3, sub4, sub5, sub6  "
       + "from stu_details sd join stu_marks sm "
       + "where sm.rollno = sd.rollno "
       + " and sd.optionalSubject='" + selectedGroup + "' and sd.class='"      
       + classToGet + "';";

rs = st.executeQuery(Query);

i = 0;
while (rs.next()) {
     tableModel.addRow(new Object[]{
                    rs.getString("rollno"),
                    rs.getString("name"),
                    rs.getString("sub1"),
                    rs.getString("sub2"),
                    rs.getString("sub3"),
                    rs.getString("sub4"),
                    rs.getString("sub5"),
                    rs.getString("sub6")});


                //tableModel.setValueAt(1, 1, 4);
                //When this is written, i am able to see 1 row in the output and then an array index out of exception    

     System.out.println(rs.getString("rollno")
                        + rs.getString("name")
                        + rs.getString("sub1")
                        + rs.getString("sub2")
                        + rs.getString("sub3")
                        + rs.getString("sub4")
                        + rs.getString("sub5")
                        + rs.getString("sub6"));
            }

        }

I am able to print all the details in the output panel by using the System.out.println. But it is not getting added into the table.

As you can see the exception near //tableModel.setValueAt(1, 1, 4); i.e., array index out of bound with one row (zero th row) being displayed. I feel the rows are being added and then being deleted some how. I am not able figure it out. Can some one help me in this regard?

1 个答案:

答案 0 :(得分:0)

我不太确定您要完成什么,因为您的代码段并未显示所有必要的数据。您的问题实际上是2个问题,如何在表格中添加一行以及如何打印表格的内容。 随附的代码是我编写的用于完成其他目的的方法,该方法已经过编辑,以删除多余的材料并使表通用。它将创建一个包含5列和6行数据的表,该表可以添加或删除行,并使用System.out.println(…。)打印出每行所有元素的内容。作为单独的行。 我希望这个对你有用。 将代码导入到IDE中,您可以根据需要进行编译,执行和编辑。 米切尔(R. Mitchell)

import java.awt.BorderLayout;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

class ModelJTable extends JFrame {

    /**
     * This application will create a table with 5 columns (0 to 4) and 6 rows
     * (0 to 5). It will allow the removal of any or all rows individually. It
     * will add row(s) as determined by commenting/uncommenting code. It will
     * print the contents of all of the displayed rows as individual lines. 
     * That is:
     * line 0, column 0 (line feed) line 0, column 1 (line feed) etc. Some of 
     * the comments are probably not applicable and most were for my 
     * information when I wrote the app.
     */
    /**
     * class variables
     */
    public DefaultTableModel model;
    public JTable table;
    /**
     * Table rows redefined to match column names. Not required. Automatically
     * appends nulls.
     */
    String[] rowZero = {"R0-C0", "R0-C1", "R0-C2", "R0-C3", "R0-C4"};
    String[] rowOne = {"R1-C0", "R1-C1", "R1-C2", "R1-C3", "R1-C4"};
    String[] newRow; // undefined String[]

    public ModelJTable() {
        super();
        /**
         * Redefined column names.
         */
        model = new DefaultTableModel();
        model.addColumn("Column 0");
        model.addColumn("Column 1");
        model.addColumn("Column 2");
        model.addColumn("Col 3");
        model.addColumn("Col 4");

        /**
         * moved to class variable to demonstrate that the row entry can be
         * defined as a class variable. String[] rowZero = {"R0-C0", "R0-C1",
         * "R0-C2", "R0-C3", "R0C4"};
         */
        // model.addRow(socrates);
        model.addRow(rowZero);
        /**
         * moved to class variable to demonstrate that the row entry can be
         * defined as a class variable. String[] rowOne = {"R1-C0", "R1-C1",
         * "R1-C2", "R1-C3", "R1-C4"};
         */
        model.addRow(rowOne);
        String[] rowTwo = {"R2-C0", "R2-C1", "R2-C2", "R2-C3", "R2-C4"};
        model.addRow(rowTwo);

        String[] rowThree = {"R3-C0", "R3-C1", "R3-C2", "R3-C3", "R3-C4"};
        model.addRow(rowThree);

        String[] rowFour = {"R4-C0", "R4-C1", "R4-C2", "R4-C3", "R4-C4"};
        model.addRow(rowFour);

        String[] rowFive = {"R5-C0", "R5-C1", "R5-C2", "R5-C3", "R5-C4"};
        model.addRow(rowFive);

        /**
         * emptyRow elements must be "" NOT "null" or any other string.
         */
        // String[] emptyRow = {"", "", "", "", ""};
        // model.addRow(emptyRow);
        table = new JTable(model, (TableColumnModel) table);

        TableColumn nameColumn = table.getColumnModel().getColumn(0);
        nameColumn.setPreferredWidth(75);
        TableColumn surNameColumn = table.getColumnModel().getColumn(1);
        surNameColumn.setPreferredWidth(75);
        TableColumn datesColumn = table.getColumnModel().getColumn(2);
        datesColumn.setPreferredWidth(300);
        TableColumn column4 = table.getColumnModel().getColumn(3);
        column4.setPreferredWidth(30);
        TableColumn column5 = table.getColumnModel().getColumn(4);
        column5.setPreferredWidth(30);

        JButton quitButton = new JButton("Quit");
        quitButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                System.exit(0);
            }
        });

        JButton printTableButton = new JButton("Print Table");
        printTableButton.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent event) {
                printFile(); // go to print file method
            }
        });

        JButton addButton = new JButton("Add Row");
        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                addNewRow();
            }
        });

        JButton removeButton = new JButton("Remove Row");
        removeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                try {
                    model.removeRow(table.getSelectedRow());
                } catch (Exception e) {
                    System.out.println("Nothing selected to remove.");
                }
            }
        });

        JPanel inputPanel = new JPanel();
        inputPanel.add(quitButton);
        inputPanel.add(printTableButton);
        inputPanel.add(addButton);
        inputPanel.add(removeButton);
        JPanel southernPanel = new JPanel();
        Container container = getContentPane();
        container.add(inputPanel, BorderLayout.SOUTH);
        container.add(southernPanel, BorderLayout.NORTH);
        container.add(new JScrollPane(table), BorderLayout.CENTER);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(600, 600);
        this.setUndecorated(true);
        this.setResizable(false);
        this.setLocationRelativeTo(null);
        setVisible(true);
    } // end of  public ModelJTable() method

    public void addNewRow() {
        String[] addRow = {"New Row", "New Row", "New Row", "New Row",
            "New Row"};
        model.addRow(addRow);
    }

    /**
     * public static void main(String args[]) { new ModelJTable(); } // end of
     * main()
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ModelJTable().setVisible(true);
            }
        });
    }

    public void printFile() {
        int rowCount = model.getRowCount(); // rowCount is decimal (1 to X)
        int columnNumber = 0;
        int rowNumber = 0;
        String rowElement = "";
        // System.out.println("Printing the rows of the table.");
        // System.out.println("rowCount = " + rowCount);
        /**
         * Row numbering is zero to X. rowCount is decimal (1 to X).
         */
        int elementNumber = 0; // initialize elementNumber
        /**
         * There are 5 elements (0 to 4) in each row. There are rowCount rows (1
         * to rowCount) in the table. Therefore there are rowCount * 5 elements
         * to be printed.
         */
        int endOfLoop = 5 * rowCount;
        //System.out.println("Number of elements in the table = " + endOfLoop);
        for (int i = 0; i < endOfLoop; i++) {
            System.out.println(model.getValueAt(rowNumber, elementNumber)
                    .toString());
            if (elementNumber == 4) {
                elementNumber = 0;
                rowNumber++;
            } else {
                elementNumber++;
            }
        }
    }
} // end of class ModelJTable