从JTable获取每一行值

时间:2014-12-05 05:51:10

标签: java swing jtable

我在JTable中显示数据库值,我想得到每一行的值。我试过addListSelectionListener但我得到空指针异常下面是我的源代码,我错了。

public class mainFrame extends javax.swing.JFrame {

static JTable table;
static Connection connection;
static Statement statement;
static JTable jTable1;
static int count;
static String r;
static DefaultTableModel model;

public mainFrame() {
    super();
    initComponents();
    setLocation(500, 180);
    try {
        //----------database
        final String queryCheck = "SELECT count(*) from test";
        final PreparedStatement ps = connection.prepareStatement(queryCheck);
        // ps.setString(1, name);
        final ResultSet resultSet = ps.executeQuery();
        if (resultSet.next()) {
            count = resultSet.getInt(1);
            System.out.println(count);

        }
        String read = "select * from test";
        ResultSet rs = statement.executeQuery(read);
        Object[][] data = new String[count][2];
        int i = 0;
        while (rs.next()) {

            for (int c = 0; c < 2; c++) {
                data[i][c] = rs.getString("namexcel");
            }
            i++;

        }
        String[] headers = {"Name"};           
        model = new DefaultTableModel(data, headers);
        jTable2.setModel(model);

        ListSelectionModel s = jTable2.getSelectionModel();
        s.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        s.addListSelectionListener(new RowListener(this));

        //     pack();
    } catch (Exception e) {

    }

}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {       //..
    pack();
}// </editor-fold>                        

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    try {
        String link = jTextField1.getText();
        System.out.println("" + link + "");
        jTextField1.setText("");
        File f = new File("" + link + "");
        if (!f.exists()) {
            JOptionPane.showMessageDialog(null, "File Doesnt Exist....!!");
            mainFrame frame = new mainFrame();
            frame.invalidate();
            frame.validate();
            //  frame.revalidate();
        } else {
            FileInputStream file = new FileInputStream(f);
            XSSFWorkbook workbook = new XSSFWorkbook(file);
            String name = workbook.getSheetName(0);
            System.out.println("----" + name);
            final String queryCheck = "SELECT count(*) from test WHERE namexcel = ?";
            final PreparedStatement ps = connection.prepareStatement(queryCheck);
            ps.setString(1, name);
            final ResultSet resultSet = ps.executeQuery();
            if (resultSet.next()) {
                final int count = resultSet.getInt(1);
                if (count == 0) {
                    JOptionPane.showMessageDialog(null, "thank you");

                    statement.executeUpdate("insert into test (namexcel) values('" + name + "')");
                    DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
                    Vector newRow = new Vector();
                    newRow.add(name);
                    Object[][] data1 = {{name},};
                    model.addRow(newRow);

                } else {
                    JOptionPane.showMessageDialog(null, "Name Already exist please select diffrent name of excel");
                }
            }

        }

    } catch (Exception r) {

    }
}                                        


public static void main(String args[]) throws Exception {
    Class.forName("org.sqlite.JDBC");
    connection = null;
    connection = DriverManager.getConnection("jdbc:sqlite:excel.db");
    statement = connection.createStatement();
    statement.executeUpdate("CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY , namexcel string)");
}


private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
public static javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable2;
private javax.swing.JTextField jTextField1;                   

}



class RowListener implements ListSelectionListener {

mainFrame readRow;
JTable table;

public RowListener(mainFrame rar) {
    readRow = rar;
    table = readRow.table;
}

public void valueChanged(ListSelectionEvent e) {
    if (!e.getValueIsAdjusting()) {
        ListSelectionModel model = table.getSelectionModel();
        int lead = model.getLeadSelectionIndex();
        displayRowValues(lead);
    }
}

private void displayRowValues(int rowIndex) {
    int columns = table.getColumnCount();
    String s = "";
    for (int col = 0; col < columns; col++) {
        Object o = table.getValueAt(rowIndex, col);
        s += o.toString();
        if (col < columns - 1) {
            s += ", ";
        }
    }  
    System.out.println(s);
}
}

1 个答案:

答案 0 :(得分:1)

JTable table;
TableModel tModel=table.getModel();
int columnCount=tModel.getColumnCount();
int rowNumber;//you will have to know this
Object[] row=new Object[columnCount];
//Loop through the model and get the values by tModel.getValueAt(row,column);

如果您的TableModel是DefaultTableModel,您可以使用getDataVector并找到所需的行。