编辑后,Java JTable无法从文件加载

时间:2016-05-06 11:24:49

标签: java swing jtable

我正在制作一个Java程序 - 一个数据库旅游机构。我已经把它从文件加载到表中的位置,你可以添加新信息并保存它,你可以计算平均价格,你可以编辑表中的信息并将其保存到文件中,但这是我得到的点问题。

  • 当我编辑单元格时,它会编辑.txt文件中的信息,但是当我尝试在编辑后再次加载文件时,它只删除文件中的所有内容。

编辑表时的表监听器。

    jTable1.getModel().addTableModelListener(new TableModelListener() {
            public void tableChanged(TableModelEvent e) {
                try {
                    saveTable();
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        });

保存表格功能

     public void saveTable()throws Exception
     {

    StringBuffer fileContent = new StringBuffer();
    TableModel tModel = jTable1.getModel();
    for (int row = 0; row < jTable1.getRowCount(); row++) {
        for (int col = 0; col < jTable1.getColumnCount(); col++) {
            Object cellValue = tModel.getValueAt(row, col) + ", ";
            fileContent.append(cellValue);
        }
        fileContent.append("\n");
    }

    FileWriter fileWriter = new FileWriter(new File("/home/nauris/Desktop/mydata.txt"));
    fileWriter.write(fileContent.toString());
    fileWriter.flush();
    fileWriter.close();
    }

加载表格功能

public void loadTable()throws Exception
{
    DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    model.setRowCount(0);
    BufferedReader br;
    try {
        br = new BufferedReader(new FileReader("/home/nauris/Desktop/mydata.txt"));
        String line = br.readLine();
        while (line != null ) {
            model.addRow(line.split(", "));
            line = br.readLine();
        }

    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
}
  • 第二件事是,我需要搜索价格较低的行,然后我放入文本字​​段。

        JTextField searchField = new JTextField();
    
        searchField.setPreferredSize(new Dimension(50, 24));
        buttonPanel.add(searchField, gbc);
    
        JButton searchButton = new JButton("Atrast");
        buttonPanel.add(searchButton, gbc);
    
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    
        searchButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int text = Integer.parseInt(searchField.getText());
                if (String.valueOf(text) == null) {
                    //sorter.setRowFilter(null);
                } else {
                    int rowsCount = jTable1.getRowCount();
                    int value= 0;
                    for(int i = 0; i < rowsCount; i++){
                        value = Integer.parseInt(jTable1.getValueAt(i, 3).toString());
                        if(value<text) {
                            model.removeRow(i);
                        }
                    }
                }
            }
        });
    

但它给了我错误

Exception in thread "AWT-EventQueue-0" java.lang.IndexOutOfBoundsException: Invalid index

1 个答案:

答案 0 :(得分:0)

从上面给出的代码中,您尝试根据搜索值过滤行。如果您使用RowFilter而不是从模型中删除行,那会更好。

        TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<DefaultTableModel>(model);
        RowFilter<DefaultTableModel, Integer> rf = RowFilter.numberFilter(RowFilter.ComparisonType.BEFORE, searchValue, 0);
        sorter.setRowFilter(rf);

参考:http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TableFilterDemoProject/src/components/TableFilterDemo.java

编辑12月5日

我已经提供了完整的代码清单。它按预期工作。

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package testtable;

import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author user
 */
public class MyFrame extends javax.swing.JFrame {

    private DefaultTableModel model = null;

    TableRowSorter<DefaultTableModel> sorter = null;

    /**
     * Creates new form MyFrame
     */
    public MyFrame() {
        initComponents();
        model = new DefaultTableModel(null, new String[]{
            "Name", "age", "salary"
        });
        jTable1.setModel(model);
        model.addRow(new Object[]{"Beniton", 34, 10000});
        model.addRow(new Object[]{"Joema", 33, 10000});
        sorter = new TableRowSorter<DefaultTableModel>(model);
        jTable1.setRowSorter(sorter);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jLabel1 = new javax.swing.JLabel();
        searchBox = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jLabel1.setText("Search");
        getContentPane().add(jLabel1, new java.awt.GridBagConstraints());

        searchBox.setMaximumSize(new java.awt.Dimension(150, 20));
        searchBox.setMinimumSize(new java.awt.Dimension(150, 20));
        searchBox.setName("searchField"); // NOI18N
        searchBox.setPreferredSize(new java.awt.Dimension(150, 20));
        searchBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchBoxActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        getContentPane().add(searchBox, gridBagConstraints);
        searchBox.getAccessibleContext().setAccessibleName("");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        getContentPane().add(jScrollPane2, gridBagConstraints);

        pack();
    }// </editor-fold>                        

    private void searchBoxActionPerformed(java.awt.event.ActionEvent evt) {                                          
        if (searchBox.getText().length() > 0) {
            Integer value = Integer.parseInt(searchBox.getText());
            // Checking the age as Index is 1
            RowFilter<DefaultTableModel, Integer> rf = RowFilter.numberFilter(RowFilter.ComparisonType.BEFORE, value, 1);
            sorter.setRowFilter(rf);
        } else {
            sorter.setRowFilter(null);
        }
    }                                         

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MyFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MyFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField searchBox;
    // End of variables declaration                   
}