java - Jtable与mysql连接时出错 "java.lang.NullPointerException"

标签 java mysql jtable

当我尝试将应用程序与 MySQL 连接时,抛出异常:java.lang.NullPointerException

应用程序随后在没有数据库的情况下启动。我调试了程序,错误在:md.addRow(a)

代码是:

    package inmobiliaria;

    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import java.awt.Point;

    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.border.EmptyBorder;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    import javax.swing.JSlider;
    import javax.swing.JTextField;
    import javax.swing.JLabel;
    import javax.swing.RowFilter;
    import javax.swing.RowSorter;
    import javax.swing.SwingConstants;
    import javax.swing.JComboBox;
    import javax.swing.DefaultComboBoxModel;

    import java.awt.Font;

    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JMenuBar;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JButton;

    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;

    import javax.swing.JTable;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableModel;
    import javax.swing.table.TableRowSorter;

    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.event.KeyAdapter;

    import javax.swing.JFormattedTextField;

    import java.awt.Component;

    import javax.swing.Box;
    import javax.swing.JRadioButton;

    import java.awt.Toolkit;
    import java.awt.event.FocusAdapter;
    import java.awt.event.FocusEvent;
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.Vector;

    public class Ventana extends JFrame {

private JPanel contentPane;
private JTextField txtNumero;
private JTextField txtNombreDelInquilino;
private JTextField txtNombreDelPropietario;
private JTextField txtDomicilio;
private JTextField txtCantidad;
private JTextArea taObservacionesDos;
private JTable table;
DefaultTableModel md;
String dataaa[][] = {};
String columnasss[] = {"NUMERO", "FECHA DE ENTRADA", "FECHA DE VENCIMIENTO", "NOMBRE DEL INQUILINO", "NOMBRE DEL PROPIETARIO", "DOMICILIO", "CANTIDAD", "OBSERVACIONES"};
private JTextField txtFiltro;
private TableRowSorter<TableModel> trsfiltro;

private Connection connect = null;
private Statement statement = null;


                            //Autor Martìn Sànchez
                            //FACEBOOK: http://www.facebook.com/martin98sanchez
    public void run() {
            try {
                Ventana frame = new Ventana();
                frame.setVisible(true);
                frame.setLocationRelativeTo(null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
/**
 * Create the frame.
 */
public Ventana() {
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
   JOptionPane.showMessageDialog(null, e.getMessage());
        return;
    }

    try {
        connect = DriverManager.getConnection("jdbc:mysql://127.0.0.1/inmobiliaria", "root", "");
    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
    return;
    }

    try {
        ResultSet rs = connect.getMetaData().getCatalogs();

    } catch (SQLException e) { }

    try {
        statement = connect.createStatement();
        ResultSet rs = statement.executeQuery("SELECT * FROM usuarios");

        // get columns info
        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();





        // add rows to table
        while (rs.next()) {
            String[] a = new String[columnCount];
            for(int i = 0; i < columnCount; i++) {
                a[i] = rs.getString(i+1);
            }
        md.addRow(a);
        }

        // Close ResultSet and Statement
        rs.close();
        statement.close();
    } catch (Exception ex) { 
        JOptionPane.showMessageDialog(this, ex, ex.getMessage(), WIDTH, null);
    }

    setTitle("Inmobiliaria");
    //setIconImage(Toolkit.getDefaultToolkit().getImage(Ventana.class.getResource("/imagenes/inmobiliaria.png")));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 1325, 727);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);


    txtNumero = new JTextField();
    txtNumero.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent e) {
            if (!Character.isDigit(e.getKeyChar())){
                e.consume();
            }
        }
    });
    txtNumero.setBounds(88, 26, 86, 20);
    contentPane.add(txtNumero);
    txtNumero.setColumns(10);

    JLabel lblNumero = new JLabel("N\u00FAmero");
    lblNumero.setBounds(22, 23, 56, 26);
    contentPane.add(lblNumero);

    JLabel lblFechaDeEntregaUno = new JLabel("Fecha de");
    lblFechaDeEntregaUno.setHorizontalAlignment(SwingConstants.CENTER);
    lblFechaDeEntregaUno.setBounds(22, 60, 56, 26);
    contentPane.add(lblFechaDeEntregaUno);

    JLabel lblFechaDeEntregaDos = new JLabel("ENTREGA");
    lblFechaDeEntregaDos.setHorizontalAlignment(SwingConstants.CENTER);
    lblFechaDeEntregaDos.setBounds(22, 82, 56, 14);
    contentPane.add(lblFechaDeEntregaDos);

    JComboBox cbDiaE = new JComboBox();
    cbDiaE.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"}));
    cbDiaE.setBounds(98, 66, 50, 20);
    contentPane.add(cbDiaE);

    JComboBox cbMesE = new JComboBox();
    cbMesE.setModel(new DefaultComboBoxModel(new String[] {"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Setiembre", "Octubre", "Noviembre", "Diciembre"}));
    cbMesE.setBounds(158, 66, 76, 20);
    contentPane.add(cbMesE);

    JComboBox cbAnioE = new JComboBox();
    cbAnioE.setModel(new DefaultComboBoxModel(new String[] {"2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030"}));
    cbAnioE.setBounds(244, 66, 56, 20);
    contentPane.add(cbAnioE);

    JLabel lblFechaDeVencimientoUno = new JLabel("Fecha de");
    lblFechaDeVencimientoUno.setHorizontalAlignment(SwingConstants.CENTER);
    lblFechaDeVencimientoUno.setBounds(22, 107, 56, 26);
    contentPane.add(lblFechaDeVencimientoUno);

    JLabel lblFechaDeVencimientoDos = new JLabel("VENCIMIENTO");
    lblFechaDeVencimientoDos.setHorizontalAlignment(SwingConstants.CENTER);
    lblFechaDeVencimientoDos.setBounds(22, 129, 76, 14);
    contentPane.add(lblFechaDeVencimientoDos);

    JComboBox cbDiaV = new JComboBox();
    cbDiaV.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"}));
    cbDiaV.setBounds(98, 113, 50, 20);
    contentPane.add(cbDiaV);

    JComboBox cbMesV = new JComboBox();
    cbMesV.setModel(new DefaultComboBoxModel(new String[] {"Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Setiembre", "Octubre", "Noviembre", "Diciembre"}));
    cbMesV.setBounds(158, 113, 76, 20);
    contentPane.add(cbMesV);

    JComboBox cbAnioV = new JComboBox();
    cbAnioV.setModel(new DefaultComboBoxModel(new String[] {"2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030"}));
    cbAnioV.setBounds(244, 113, 56, 20);
    contentPane.add(cbAnioV);

    JLabel lblNombreDelInquilino = new JLabel("Nombre del Inquilino");
    lblNombreDelInquilino.setBounds(22, 154, 109, 14);
    contentPane.add(lblNombreDelInquilino);

    JLabel lblNombreDelPropietario = new JLabel("Nombre del Propietario");
    lblNombreDelPropietario.setBounds(22, 189, 137, 14);
    contentPane.add(lblNombreDelPropietario);

    txtNombreDelInquilino = new JTextField();
    txtNombreDelInquilino.setBounds(158, 151, 130, 20);
    contentPane.add(txtNombreDelInquilino);
    txtNombreDelInquilino.setColumns(10);

    txtNombreDelPropietario = new JTextField();
    txtNombreDelPropietario.setBounds(158, 186, 129, 20);
    contentPane.add(txtNombreDelPropietario);
    txtNombreDelPropietario.setColumns(10);

    JLabel lblDomicilio = new JLabel("Domicilio");
    lblDomicilio.setBounds(22, 224, 76, 14);
    contentPane.add(lblDomicilio);

    txtDomicilio = new JTextField();
    txtDomicilio.setBounds(100, 221, 200, 20);
    contentPane.add(txtDomicilio);
    txtDomicilio.setColumns(10);

    JLabel lblCantidad = new JLabel("Cantidad");
    lblCantidad.setBounds(22, 255, 76, 14);
    contentPane.add(lblCantidad);

    txtCantidad = new JTextField();
    txtCantidad.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent e) {
            if (!Character.isDigit(e.getKeyChar())){
                //... no lo escribe
            e.consume();
            }
        }
    });
    txtCantidad.setBounds(100, 252, 200, 20);
    contentPane.add(txtCantidad);
    txtCantidad.setColumns(10);

    JLabel lblObservaciones = new JLabel("Observaciones");
    lblObservaciones.setBounds(22, 280, 86, 14);
    contentPane.add(lblObservaciones);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(110, 283, 204, 132);
    contentPane.add(scrollPane);

    JTextArea taObservaciones = new JTextArea();
    scrollPane.setViewportView(taObservaciones);

    JButton btnAceptar = new JButton("Aceptar");
    btnAceptar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            String numero = txtNumero.getText();
            String nombreInquilino = txtNombreDelInquilino.getText();
            String nombrePropietario = txtNombreDelPropietario.getText();
            String domicilio = txtDomicilio.getText();
            String cantidad = txtCantidad.getText();
            String observaciones = taObservaciones.getText();
            String dDE = cbDiaE.getSelectedItem().toString();
            String mDE = cbMesE.getSelectedItem().toString();
            String aDE = cbAnioE.getSelectedItem().toString();
            String dDV = cbDiaV.getSelectedItem().toString();
            String mDV = cbMesV.getSelectedItem().toString();
            String aDV = cbAnioV.getSelectedItem().toString();
            String fechaEntrada;
            String fechaVencimiento;


            fechaEntrada = dDE + " / " + mDE + " / " + aDE;
            fechaVencimiento = dDV + " / " + mDV + " / " + aDV;


            txtNumero.setText("");
            txtNombreDelInquilino.setText("");
            txtNombreDelPropietario.setText("");
            txtDomicilio.setText("");
            txtCantidad.setText("");
            taObservaciones.setText("");
            cbDiaE.setSelectedItem("1");
            cbMesE.setSelectedItem("Enero");
            cbDiaV.setSelectedItem("1");
            cbMesV.setSelectedItem("Enero");






        }
    });
    btnAceptar.setFont(new Font("Tahoma", Font.BOLD, 18));
    btnAceptar.setBounds(98, 446, 189, 58);
    contentPane.add(btnAceptar);
    md = new DefaultTableModel(dataaa, columnasss);

    JScrollPane scrollPane_1 = new JScrollPane();

    scrollPane_1.setBounds(344, 11, 955, 493);
    contentPane.add(scrollPane_1);

    table = new JTable();
    table.setAutoResizeMode(1);
    TableRowSorter<DefaultTableModel> sorter = new TableRowSorter<>(md);
    table.setRowSorter(sorter);
    scrollPane_1.setViewportView(table);
    table.setToolTipText("");
    table.setModel(new DefaultTableModel(
        new Object[][] {
        },
        new String[] {
            "NUMERO", "FECHA DE ENTRADA", "FECHA DE VENCIMIENTO", "NOMBRE DEL INQUILINO", "NOMBRE DEL PROPIETARIO", "DOMICILIO", "CANTIDAD", "OBSERVACIONES"
        }
    ));
        //String observacionesDos = (String) table.getValueAt(table.getSelectedRow(), 7);
            //taObservacionesDos.setText(observacionesDos);

    table.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent me) {
            JTable table2 =(JTable) me.getSource();
            Point p = me.getPoint();
            int row = table2.rowAtPoint(p);

            String observacionesDos = table.getValueAt(row, 7).toString();
            taObservacionesDos.setText(observacionesDos);

            /*if (me.getClickCount() == 2) {
                // your valueChanged overridden method 
            }*/
        }
    });
    table.setModel(md);

    JButton btnBorrarTodo = new JButton("Borrar Todo");
    btnBorrarTodo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
        }
    });
    btnBorrarTodo.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            int respuesta = JOptionPane.showConfirmDialog(null, "¿Desea borrar todos los datos guardados?", "Borrar Todo", JOptionPane.YES_NO_OPTION);
            if (respuesta == 0){
                if(md.getRowCount() == 0){
                    JOptionPane.showMessageDialog(null, "No hay ningùn archivo para borrar.");
                }else{
                    while (md.getRowCount() > 0){
                        md.removeRow(0);
                    }
                }

            }
        }
    });
    btnBorrarTodo.setFont(new Font("Tahoma", Font.BOLD, 15));
    btnBorrarTodo.setBounds(344, 515, 293, 62);
    contentPane.add(btnBorrarTodo);

    JButton btnBorrarDatoSeleccionado = new JButton("Borrar Dato Seleccionado");
    btnBorrarDatoSeleccionado.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try{
                md.removeRow(table.getSelectedRow());
            }catch(Exception x) {
                JOptionPane.showMessageDialog(null, "No se ha seleccionado ninguna fila aùn.");
            }




        }
    });
    btnBorrarDatoSeleccionado.setFont(new Font("Tahoma", Font.BOLD, 15));
    btnBorrarDatoSeleccionado.setBounds(926, 515, 373, 62);
    contentPane.add(btnBorrarDatoSeleccionado);

    txtFiltro = new JTextField();

    txtFiltro.addKeyListener(new KeyAdapter() {
        @SuppressWarnings("unchecked")
        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode()==KeyEvent.VK_ENTER){
                trsfiltro.setRowFilter(RowFilter.regexFilter(txtFiltro.getText()));
            }
        }
    });
    txtFiltro.setBounds(158, 538, 142, 20);
    txtFiltro.addKeyListener(new KeyAdapter() {
        public void keyReleased(final KeyEvent e) {
            String cadena = (txtFiltro.getText());
            txtFiltro.setText(cadena);
            repaint();
            filtro();
            }
            });
            trsfiltro = new TableRowSorter<TableModel>(table.getModel());
            table.setRowSorter(trsfiltro);
    contentPane.add(txtFiltro);
    txtFiltro.setColumns(10);

    JLabel lblFiltro = new JLabel("Filtro : ");
    lblFiltro.setBounds(102, 541, 46, 14);
    contentPane.add(lblFiltro);

    JScrollPane scrollPane_2 = new JScrollPane();
    scrollPane_2.setBounds(10, 590, 1289, 87);
    contentPane.add(scrollPane_2);

    taObservacionesDos = new JTextArea();
    taObservacionesDos.setEditable(false);
    scrollPane_2.setViewportView(taObservacionesDos);



}


public void filtro() {
    trsfiltro.setRowFilter(RowFilter.regexFilter("(?i)"+ txtFiltro.getText()));
    }
    }

最佳答案

您正在调用...

md.addRow(a);

在初始化 md 之前...

 md = new DefaultTableModel(dataaa, columnasss);

也就是说,先初始化,然后调用数据库,做你的工作。否则,您将尝试写入尚不存在的表。

关于java - Jtable与mysql连接时出错 "java.lang.NullPointerException",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31906846/

相关文章:

java - 集成测试对单元测试的依赖性 : A Nice/Deadly Unimplementable Strategy for Building JUnit Integration Tests?

java - 如何从使用在 "Classpath"中添加的 *.jar 文件的 eclipse java 项目创建 jar 文件

php - 生成并分离 PHP 进程而不共享任何数据库资源以便子进程可以退出?

java - 添加到ArrayList后刷新JTable

java - 如何创建一个像 Internet Download Manager 应用程序中使用的表一样的 JTable?

java - 使用 Spring MVC 通过 AJAX 发送 HTML 数据

java - 如何使用 Spring 将 null 作为方法参数连接?

php - 检查id是否存在于其他表中

php - 通过相同 id 通过其他表中的其他行的值更新表的行

java - 如何避免 jtable 中的指数值