获取JTable的选定行不起作用?

时间:2015-06-07 03:07:39

标签: java mysql swing nullpointerexception jtable

我无法从JTable中获取所选行,然后运行SQL Query以根据membId删除该行。我被困在这个上大约6个小时!

我使用TableModel来包含来自另一个文件的表 - 意思是我可以在任何地方使用该表。文件名:MemTableModel.Java

我得到了这个例外 - 我想我已经将它缩小到一行member m = memberTableModel.getRow(selectedRow); - 但我看不出错误是什么,我在整个谷歌搜索试图找到解决方案,但我可以'找到一个。

这可能是数据库问题,我知道我的数据库正在运行,因为它正确打印到JTable并且adding into the database works所以我不认为这是问题。

public class searchAll extends JFrame implements ActionListener {
    private MemTableModel memberTableModel;
    private int selectedRow;

    //GUI RELATED
    private JTable table = new JTable();

    //JButtons
    private JButton btnDelete = new JButton("Delete");
    private JButton btnEdit = new JButton("Edit");

    //Containers, panels
    Container mainCon = this.getContentPane();
    JPanel formPanel = new JPanel();

    //Form GUI Components
    //Buttons
    private static JButton submitMember = new JButton("Add Member");


    /*TEXT FIELDS BOXES *******************************/
    private JLabel lblName = new JLabel("Name: ");
    private JTextField txtName = new JTextField("", 15);

    private JLabel lblEmail = new JLabel("Email: ");
    private JTextField txtEmail = new JTextField("", 15);

    private JLabel lblDescription = new JLabel("Description about you: ");
    private JTextArea txtDescription = new JTextArea("", 5, 15);
    /*TEXT FIELDS BOXES *******************************/

    /*COMBO BOXES *******************************/
    private JLabel lblCountry = new JLabel();
    private JComboBox comCountry = new JComboBox();

    private JLabel lblGenre = new JLabel();
    private JComboBox comGenre = new JComboBox();
    /*COMBO BOXES *******************************/

    /*RADIO BUTTONS *******************************/
    private JLabel lblMaleFemale = new JLabel("Gender: ");
    private JRadioButton radMale = new JRadioButton("Male: ");
    private JRadioButton radFemale = new JRadioButton("Female: ");
    private ButtonGroup buttonGroupMF = new ButtonGroup();

    private JLabel lblFreePaid = new JLabel("Membership Type: ");
    private JRadioButton radFree = new JRadioButton("Free: ");
    private JRadioButton radPaid = new JRadioButton("Paid: ");
    private ButtonGroup buttonGroupFP = new ButtonGroup();
    /*RADIO BUTTONS *******************************/


    /*PAID MEMBER STUFF *******************************/
    private JLabel lblCardNo = new JLabel("Card Number: ");
    private JTextField txtCardNo = new JTextField("", 15);

    private JLabel lblExpiry = new JLabel();
    private JComboBox comExpiry = new JComboBox();
    /*PAID MEMBER STUFF *******************************/



    public searchAll(){
        super("Search/Edit/Delete");
        this.setBounds(400, 500, 854,400);
        this.setVisible(true);
        MemTableModel tblMembers = new MemTableModel();

        //Add table and GUI components
        mainCon.add(formPanel);
        formPanel.add(table);
        formPanel.add(btnDelete);
        formPanel.add(btnEdit);

        //Add action listeners

        btnEdit.addActionListener(this);
        btnDelete.addActionListener(this);
        table.setModel(tblMembers);

        //Set Selection model for table
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        ListSelectionModel rowSM = table.getSelectionModel();
        rowSM.addListSelectionListener(new ListSelectionListener()  {
            @Override
            public void valueChanged(ListSelectionEvent e){
                ListSelectionModel lsm = (ListSelectionModel) e.getSource();
                selectedRow = lsm.getMinSelectionIndex();
            }
        });

    }


    //Connection Method
    public Connection getConnection(){
        Connection conDB = null;
         /****** DEFAULT MYSQL DRIVERS **************************/
            String url = connection.geturl();
            String username = connection.getUsername();
            String password = connection.getPassword();
        try{
            //load the MYSQL driver
            Class.forName(connection.getDriver());
            conDB = DriverManager.getConnection(url, username, password);
        }
        catch(Exception e){
            System.out.println("Error was: " + e);
        }
         return conDB;
    }




    /*-------ACTION PERFORMED ------------------------------*/
    public void actionPerformed(ActionEvent e) {
        Connection conDB = null;
        Statement stmt = null;
        ResultSet r = null;
        System.out.println("After result set variables");
        //Get the selected row everytime theres an action
        member m = memberTableModel.getRow(selectedRow);
        System.out.println("AFTER get row from tableModel");

        if(e.getSource() == btnDelete){
            try{
            //Connection + Statement
            conDB = getConnection();
            stmt = conDB.createStatement();
            String sqlDeleteMem = "delete from members where membId = " + m.getmembId();
//            String sqlDeletePlay = "delete from playlist where membId = " + m.getmembId();

            stmt.executeUpdate(sqlDeleteMem);
//            stmt.executeUpdate(sqlDeletePlay);
//            stmt.executeUpdate(sqlDeletePlay);
            conDB.close();

            }
            catch(SQLException er){
                System.out.println("Error was: " + er);
            }
            memberTableModel.LoadTableFromDB();
            memberTableModel.fireTableRowsDeleted(selectedRow, selectedRow);

        }
        if(e.getSource() == btnEdit){
            showInputFields();
        }
        if(e.getSource() == submitMember){
            System.out.println("Submitted");
        }

    }








    //Add in later -- 
    public void showInputFields(){
        formPanel.setLayout(new FlowLayout());


         /*TEXT FIELDS BOXES *******************************/
        formPanel.add(lblName);
        formPanel.add(txtName);

        formPanel.add(lblEmail);
        formPanel.add(txtEmail);

        formPanel.add(lblDescription);
        formPanel.add(txtDescription);
        /*TEXT FIELDS BOXES *******************************/



        /*COMBO BOXES *******************************/

        //Combo Box ( Countrys )
        formPanel.add(lblCountry);
        formPanel.add(comCountry);
        comCountry.addItem("Australia");
        comCountry.addItem("New Zealand");
        comCountry.addItem("Tasmania");
        comCountry.addActionListener(this);
        //Combo Box ( Fav Genre )
        formPanel.add(lblGenre);
        formPanel.add(comGenre);
        comGenre.addItem("Pop");
        comGenre.addItem("Rock");
        comGenre.addItem("Alternative");
        comGenre.addItem("Jazz");
        comGenre.addItem("Hip/Hop");

        comGenre.addActionListener(this);

        /*COMBO BOXES *******************************/

        /*RADIO BUTTONS BOXES *******************************/
        //Radio Buttons (Male/Female)
        buttonGroupMF.add(radMale);
        buttonGroupMF.add(radFemale);

        formPanel.add(radMale);
        formPanel.add(radFemale);

        radMale.addActionListener(this);
        radFemale.addActionListener(this);

        //Free or paid members ------ 
        buttonGroupFP.add(radFree);
        buttonGroupFP.add(radPaid);

        formPanel.add(radFree);
        formPanel.add(radPaid);

        radFree.addActionListener(this);
        radPaid.addActionListener(this);
        //Free or paid members ------ 


        /*RADIO BUTTONS BOXES *******************************/


        /*PAID MEMBER GUI *******************************/


        formPanel.add(lblCardNo);
        formPanel.add(txtCardNo);
        //Hide
        lblCardNo.setVisible(true);
        txtCardNo.setVisible(true);


        formPanel.add(lblExpiry);
        formPanel.add(comExpiry);
        comExpiry.addItem("2017");
        comExpiry.addItem("2018");
        comExpiry.addItem("2019");
        //Hide
        lblExpiry.setVisible(true);
        comExpiry.setVisible(true);
        comExpiry.addActionListener(this);

        /*PAID MEMBER GUI *******************************/

        //Add the button after everything
        formPanel.add(submitMember);
        submitMember.addActionListener(this);
    }
}

MembTableModel.Java

public class MemTableModel extends AbstractTableModel{
    private ArrayList<member> members = new ArrayList<member>();
    private String[] columnNames = {"ID", "Name", "Email", "Country", "Genre",
            "Gender", "Description", "Type", "Limit", "Card No", "Expiry Date"};

    public MemTableModel(){
        LoadTableFromDB();
    }
    public int getRowCount(){
        return members.size();
    }
    public int getColumnCount(){
        return columnNames.length;
    }

    public Object getValueAt(int row, int col){
        //Get the row from the about get method
        member f = members.get(row);
        switch(col){
            case 0: return f.getmembId();
            case 1: return f.getname();
            case 2: return f.getemail();
            case 3: return f.getcountry();
            case 4: return f.getfavGenre(); 
            case 5: return f.getgender();
            case 6: return f.getdescription();
            case 7: return f.getmemberType();
            case 8: return f.getsongLimit();
            case 9: return f.getcard_no();
            case 10: return f.getexpiry_date();
        }
        return null;
    }
    public String getColumnName(int col){
        return columnNames[col];
    }
    public member getRow(int row){
        member c = members.get(row);
       return c;
    }
    public Connection getConnection(){
        Connection conDB = null;
         /****** DEFAULT MYSQL DRIVERS **************************/
            String url = connection.geturl();
            String username = connection.getUsername();
            String password = connection.getPassword();
        try{
            //load the MYSQL driver
            Class.forName(connection.getDriver());
            conDB = DriverManager.getConnection(url, username, password);
        }
        catch(Exception e){

        }
         return conDB;
    }
    //Load all DB values into ARRAY
    public void LoadTableFromDB(){
        Connection conDB = null;
        Statement stmt = null;
        ResultSet r = null;
        try{
            //Connection + Statement
            conDB = getConnection();
            stmt = conDB.createStatement();
            //Queries
            String sqlSelectAll = "SELECT * FROM members";
            r = stmt.executeQuery(sqlSelectAll);

            members.clear();
            //Loop through the resultset
            while(r.next()){
            members.add(new member(r.getInt("membId"), r.getString("name"), 
                r.getString("email"), r.getString("country"), r.getString("favGenre"),
                r.getString("gender"), r.getString("description"), r.getString("memberType"),
                r.getString("songLimit"), r.getString("card_no"), r.getString("expiry_date")));
            }
            conDB.close();  // Close the DB connection


        }//End of TRY
        catch(Exception er){
            System.out.println("Error was: " + er);
        }
    }
}

我得到的例外:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at GUI.searchAll.actionPerformed(searchAll.java:164)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6527)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
    at java.awt.Component.processEvent(Component.java:6292)
    at java.awt.Container.processEvent(Container.java:2234)
    at java.awt.Component.dispatchEventImpl(Component.java:4883)
    at java.awt.Container.dispatchEventImpl(Container.java:2292)
    at java.awt.Component.dispatchEvent(Component.java:4705)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
    at java.awt.Container.dispatchEventImpl(Container.java:2278)
    at java.awt.Window.dispatchEventImpl(Window.java:2739)
    at java.awt.Component.dispatchEvent(Component.java:4705)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
    at java.awt.EventQueue.access$400(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:697)
    at java.awt.EventQueue$3.run(EventQueue.java:691)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:719)
    at java.awt.EventQueue$4.run(EventQueue.java:717)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at GUI.searchAll.actionPerformed(searchAll.java:164)

0 个答案:

没有答案