Home > Mobile >  JTable error: I'm trying to display the selected row values from a JTable in the textfield but
JTable error: I'm trying to display the selected row values from a JTable in the textfield but

Time:11-28

JTable error: I'm trying to display the selected row values from a JTable in the textfield but I keep getting this error, I honestly can't trace it.

This is the code: package Banner;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.JRadioButton;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import java.awt.Choice;
import javax.swing.ButtonGroup;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ModifyUserInfo {

    private JFrame ModifyLbl;
    private JTable table;
    private JTextField IDField;
    private JTextField nameField;
    private JTextField EmailField;
    private JTextField MobileField;
    private JTextField PasswordtextField;
    private final ButtonGroup buttonGroup = new ButtonGroup();
    private JRadioButton StudentRadioBtn;
    private JRadioButton InstructorRadioBtn;
    private JComboBox MajorBox;
    
    

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ModifyUserInfo window = new ModifyUserInfo();
                    window.ModifyLbl.setVisible(true);
                    
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public ModifyUserInfo() {
        initialize();
        showUser();
    }
    
    public ArrayList<User> userList()
    {
        ArrayList<User> usersList = new ArrayList<>();

        try {
            Connection con = con();
            
            String query1 = "select * from userslist;";
            Statement st;
            
            st = con.createStatement();
            ResultSet rs = st.executeQuery(query1);
            User user;
            while(rs.next()) {
                user = new User(rs.getInt("ID"), rs.getString("Full Name"), rs.getString("User Type"), rs.getString("Major"), rs.getString("Personal Email"), rs.getString("Mobile"), rs.getString("Password"));
                usersList.add(user);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return usersList;

    }
    
    public void showUser()
    {
        ArrayList<User> list = userList();
        DefaultTableModel model = (DefaultTableModel) table.getModel();
        Object [] row = new Object[7];
        
        for(int i = 0; i<list.size(); i  ) {
            row[0] = list.get(i).getID();
            row[1] = list.get(i).getFullName();
            row[2] = list.get(i).getUserType();
            row[3] = list.get(i).getMajor();
            row[4] = list.get(i).getEmail();
            row[5] = list.get(i).getMobile();
            row[6] = list.get(i).getPassword();
            
            model.addRow(row);
            
        }
    }

    /**
     * Initialize the contents of the frame.
     */
    /**
     * 
     */
    private void initialize() {
        ModifyLbl = new JFrame();
        ModifyLbl.addWindowListener(new WindowAdapter() {
            @Override
            public void windowOpened(WindowEvent e) {
                
            }
        });
        ModifyLbl.setTitle("Modify User Info");
        ModifyLbl.setBounds(100, 100, 998, 617);
        ModifyLbl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ModifyLbl.getContentPane().setLayout(null);
        
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
    
                
            }
        });
        scrollPane.setBounds(313, 10, 661, 560);
        ModifyLbl.getContentPane().add(scrollPane);
        
        table = new JTable();
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int i = table.getSelectedRow();
                TableModel model = table.getModel();
                
                IDField.setText(model.getValueAt(i, 1).toString());     
                nameField.setText(model.getValueAt(i, 2).toString());
                PasswordtextField.setText(model.getValueAt(i, 7).toString());
                String usertype = model.getValueAt(i, 3).toString();
                if(usertype.equals("Student"))
                {
                    StudentRadioBtn.setSelected(true);
                }
                else
                {
                    InstructorRadioBtn.setSelected(true);
                }
                
                String major = model.getValueAt(i, 4).toString();
                switch (major)
                {
                case "Select":
                    MajorBox.setSelectedIndex(0);
                    break;
                    
                case "ECCE": 
                    MajorBox.setSelectedIndex(1);
                    break;
                    
                case "MEEN": 
                    MajorBox.setSelectedIndex(2);
                    break;
                    
                case "ISYE": 
                    MajorBox.setSelectedIndex(3);
                    break;
                    
                case "CHEG": 
                    MajorBox.setSelectedIndex(4);
                    break;
                    
                case "GERN": 
                    MajorBox.setSelectedIndex(5);
                    break;
                }
                
                
                

                EmailField.setText(model.getValueAt(i, 5).toString());
                MobileField.setText(model.getValueAt(i, 6).toString());
                
                
                
            }
        });
        table.setModel(new DefaultTableModel(
            new Object[][] {
            },
            new String[] {
                "ID", "Full Name", "UserType", "Major", "Personal Email", "Mobile", "Password"
            }
        ));
        table.getColumnModel().getColumn(4).setPreferredWidth(105);
        scrollPane.setViewportView(table);
        
        JLabel TitleLabel = new JLabel("Modify User Information");
        TitleLabel.setFont(new Font("Tahoma", Font.PLAIN, 14));
        TitleLabel.setBounds(10, 10, 217, 29);
        ModifyLbl.getContentPane().add(TitleLabel);
        
        JLabel IDLabel = new JLabel("Identification Number:");
        IDLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
        IDLabel.setBounds(20, 49, 133, 13);
        ModifyLbl.getContentPane().add(IDLabel);
        
        IDField = new JTextField();
        IDField.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                
            }
        });
        IDField.setBounds(161, 47, 125, 19);
        ModifyLbl.getContentPane().add(IDField);
        IDField.setColumns(10);
        
        JLabel UserNameLabel = new JLabel("Full Name:");
        UserNameLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
        UserNameLabel.setBounds(20, 88, 133, 13);
        ModifyLbl.getContentPane().add(UserNameLabel);
        
        nameField = new JTextField();
        nameField.setColumns(10);
        nameField.setBounds(161, 86, 125, 19);
        ModifyLbl.getContentPane().add(nameField);
        
        JLabel UserTypeLabel = new JLabel("Personal Email:");
        UserTypeLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
        UserTypeLabel.setBounds(20, 319, 133, 13);
        ModifyLbl.getContentPane().add(UserTypeLabel);
        
        StudentRadioBtn = new JRadioButton("Student");
        buttonGroup.add(StudentRadioBtn);
        StudentRadioBtn.setBounds(20, 191, 103, 21);
        ModifyLbl.getContentPane().add(StudentRadioBtn);
        
        InstructorRadioBtn = new JRadioButton("Instructor");
        buttonGroup.add(InstructorRadioBtn);
        InstructorRadioBtn.setBounds(183, 191, 103, 21);
        ModifyLbl.getContentPane().add(InstructorRadioBtn);
        
        JLabel MajorLabel = new JLabel("Major:");
        MajorLabel.setFont(new Font("Tahoma", Font.PLAIN, 12));
        MajorLabel.setBounds(20, 245, 133, 13);
        ModifyLbl.getContentPane().add(MajorLabel);
        
        MajorBox = new JComboBox();
        MajorBox.setModel(new DefaultComboBoxModel(new String[] {"Select", "ECCE", "MEEN", "ISYE", "CHEG", "GERN"}));
        MajorBox.setBounds(163, 242, 123, 21);
        ModifyLbl.getContentPane().add(MajorBox);
        
        JLabel UserTypeLabel_1 = new JLabel("Select User Type:");
        UserTypeLabel_1.setFont(new Font("Tahoma", Font.PLAIN, 12));
        UserTypeLabel_1.setBounds(20, 166, 133, 13);
        ModifyLbl.getContentPane().add(UserTypeLabel_1);
        
        EmailField = new JTextField();
        EmailField.setColumns(10);
        EmailField.setBounds(161, 317, 125, 19);
        ModifyLbl.getContentPane().add(EmailField);
        
        MobileField = new JTextField();
        MobileField.setColumns(10);
        MobileField.setBounds(161, 359, 125, 19);
        ModifyLbl.getContentPane().add(MobileField);
        
        JLabel lblMobileNumber = new JLabel("Mobile Number:");
        lblMobileNumber.setFont(new Font("Tahoma", Font.PLAIN, 12));
        lblMobileNumber.setBounds(20, 361, 133, 13);
        ModifyLbl.getContentPane().add(lblMobileNumber);
        
        JLabel lblPassword = new JLabel("Password");
        lblPassword.setFont(new Font("Tahoma", Font.PLAIN, 12));
        lblPassword.setBounds(20, 127, 133, 13);
        ModifyLbl.getContentPane().add(lblPassword);
        
        PasswordtextField = new JTextField();
        PasswordtextField.setColumns(10);
        PasswordtextField.setBounds(161, 125, 125, 19);
        ModifyLbl.getContentPane().add(PasswordtextField);
        
        JLabel contactlbl = new JLabel("Contact Information");
        contactlbl.setFont(new Font("Tahoma", Font.PLAIN, 12));
        contactlbl.setBounds(10, 284, 133, 13);
        ModifyLbl.getContentPane().add(contactlbl);
        
        JButton SaveBtn = new JButton("Save");
        SaveBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

                try {
                    Connection con = con();
                    
                    String query = "insert into userslist values (?, ?, ?, ?, ? ,? ,?)";
                    PreparedStatement pSt = con.prepareStatement(query);
                    pSt.setString(1, IDField.getText());
                    pSt.setString(2, nameField.getText());
                    
                    if(StudentRadioBtn.isSelected())
                        pSt.setString(3, "Student");
                    else if(InstructorRadioBtn.isSelected())
                        pSt.setString(3, "Instructor");
                    
                    String major = MajorBox.getSelectedItem().toString();
                    pSt.setString(4, major);
                    
                    pSt.setString(5, EmailField.getText());
                    pSt.setString(6, MobileField.getText());
                    pSt.setString(7, PasswordtextField.getText());
                    pSt.executeUpdate();
                    
                    DefaultTableModel model = (DefaultTableModel) table.getModel();
                    model.setRowCount(0);
                    showUser();
                
                    JOptionPane.showMessageDialog(null, "Registered Successfully!");
                    
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                
            }
        });
        SaveBtn.setBounds(153, 477, 133, 40);
        ModifyLbl.getContentPane().add(SaveBtn);
        
        JButton EditBtn = new JButton("Edit");
        EditBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                
                IDField.setText("");        
                nameField.setText("");
                PasswordtextField.setText("");
                buttonGroup.clearSelection();
                MajorBox.setSelectedIndex(0);
                EmailField.setText("");
                MobileField.setText("");

                
            }
        });
        EditBtn.setBounds(153, 427, 133, 40);
        ModifyLbl.getContentPane().add(EditBtn);
        
        JButton ResetBtn_1 = new JButton("Reset");
        ResetBtn_1.setBounds(10, 427, 133, 40);
        ModifyLbl.getContentPane().add(ResetBtn_1);
        
        JButton DeleteBtn = new JButton("Delete");
        DeleteBtn.setBounds(10, 477, 133, 40);
        ModifyLbl.getContentPane().add(DeleteBtn);
    }
    
    static Connection con()
    {
        try {

            Class.forName("com.mysql.cj.jdbc.Driver");
              Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/usersdatabase", "root", "fatima2002");
              return c;
              
        }
        catch(Exception e)
        {
            System.out.println("Connection Failed"  e);
        }
        return null;
    }
}
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 7 >= 7
    at java.base/java.util.Vector.elementAt(Vector.java:466)
    at java.desktop/javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:661)
    at Banner.ModifyUserInfo$4.mouseClicked(ModifyUserInfo.java:206)
    at java.desktop/java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:278)
    at java.desktop/java.awt.Component.processMouseEvent(Component.java:6620)
    at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
    at java.desktop/java.awt.Component.processEvent(Component.java:6382)
    at java.desktop/java.awt.Container.processEvent(Container.java:2264)
    at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:4993)
    at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2322)
    at java.desktop/java.awt.Component.dispatchEvent(Component.java:4825)
    at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4934)
    at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4572)
    at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4504)
    at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2308)
    at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2773)
    at java.desktop/java.awt.Component.dispatchEvent(Component.java:4825)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
    at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
    at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 7 >= 7
    at java.base/java.util.Vector.elementAt(Vector.java:466)
    at java.desktop/javax.swing.table.DefaultTableModel.getValueAt(DefaultTableModel.java:661)
    at Banner.ModifyUserInfo$4.mouseClicked(ModifyUserInfo.java:206)
    at java.desktop/java.awt.AWTEventMulticaster.mouseClicked(AWTEventMulticaster.java:278)
    at java.desktop/java.awt.Component.processMouseEvent(Component.java:6620)
    at java.desktop/javax.swing.JComponent.processMouseEvent(JComponent.java:3342)
    at java.desktop/java.awt.Component.processEvent(Component.java:6382)
    at java.desktop/java.awt.Container.processEvent(Container.java:2264)
    at java.desktop/java.awt.Component.dispatchEventImpl(Component.java:4993)
    at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2322)
    at java.desktop/java.awt.Component.dispatchEvent(Component.java:4825)
    at java.desktop/java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4934)
    at java.desktop/java.awt.LightweightDispatcher.processMouseEvent(Container.java:4572)
    at java.desktop/java.awt.LightweightDispatcher.dispatchEvent(Container.java:4504)
    at java.desktop/java.awt.Container.dispatchEventImpl(Container.java:2308)
    at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2773)
    at java.desktop/java.awt.Component.dispatchEvent(Component.java:4825)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
    at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
    at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

And this is what happens when I select a row from the JTable

Image

Please help it's frustrating

CodePudding user response:

The error says that getValueAt() is using an index that is out of bounds. Remember that indexes start at 0.

You have 7 columns in your table (I think, looking at the picture), that would be indexes 0 - 6. But you have this in your code:

PasswordtextField.setText(model.getValueAt(i, 7).toString());

I believe all of your indexes are off by 1 because you are starting at 1 rather than 0.

  • Related