ERRO java.lang.ArrayIndexOutOfBoundsException:

Estou fazendo um projeto de pesquisa de alunos , mas estou tendo um erro que gostaria muito de ajuda para resolver , quando selecionado algum item na tabela e tento pesquisar de novo apresentasse o erro

java.lang.ArrayIndexOutOfBoundsException

===========================================================================
AKI ESTA MEU CODIGO:

package pricipal;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Image;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.mysql.jdbc.Statement;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JLabel;

public class Pesquisa extends JFrame {

private JPanel contentPane;
private boolean action1 = false;
private boolean action2 = false;
private boolean action3 = false;
java.sql.Connection con;
String Servidor = "jdbc:mysql://localhost:3306/escola?useSSL=false";
String Usuario = "root";
String Senha = "";
private JTextField textField;
String nome;
String turma;
String codigo;
String turma1;
String codigo1;
String texto;
private JTable table;
DefaultTableModel var;
private PreparedStatement dados;
private ResultSet rs;
private DefaultTableModel val;

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

/**
 * Create the frame.
 */
public Pesquisa() {

    ImageIcon seta = new ImageIcon("C:/Users/André/Downloads/CEF04/src/imagens/reply.png");
    ImageIcon pesquisar = new ImageIcon("C:/Users/André/Downloads/CEF04/src/imagens/pesquisar.png");

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 827, 600);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setLocationRelativeTo(null);//Localização da janela
    setContentPane(contentPane);
    contentPane.setLayout(null);

    textField = new JTextField();
    textField.setFont(new Font("Tahoma", Font.BOLD, 13));
    textField.setBounds(26, 189, 99, 20);
    textField.setHorizontalAlignment(SwingConstants.CENTER);
    contentPane.add(textField);
    textField.setColumns(10);
    textField.requestFocus();

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(152, 94, 649, 456);
    contentPane.add(scrollPane);
    getContentPane().add(scrollPane);

    JTable table = new JTable();
    table.setToolTipText("");
    table.setFont(new Font("Tahoma", Font.BOLD, 14));
    table.setBounds(0, 157, 1264, 525);

    table.setBorder(null);
    scrollPane.setColumnHeaderView(table);
    scrollPane.setViewportView(table);
    table.setModel(new DefaultTableModel(new Object[][]{}, new String[]{"Código", "Nome", "Turma"}));

    JTableHeader tabela = table.getTableHeader();
    tabela.setBackground(Color.ORANGE);
    table.setBackground(Color.CYAN);
    table.getParent().setBackground(Color.WHITE);
    tabela.setFont(new Font("Tahoma", Font.BOLD, 16));
    table.getColumnModel().getColumn(0).setPreferredWidth(100);
    table.getColumnModel().getColumn(1).setPreferredWidth(500);
    table.getColumnModel().getColumn(2).setPreferredWidth(70);

    var = (DefaultTableModel) table.getModel();
    var.addRow(new String[]{codigo, nome, turma});
    textField.setText(null);

    JButton btnVoltar = new JButton("Voltar", seta);
    getContentPane().add(btnVoltar);
    btnVoltar.setBounds(32, 515, 99, 23);
    btnVoltar.setHorizontalTextPosition(SwingConstants.LEFT);
    btnVoltar.setBackground(new Color(255, 102, 102));
    btnVoltar.setFont(new Font("Tahoma", Font.BOLD, 13));
    btnVoltar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            dispose();

        }
    });

    JLabel lblFoto = new JLabel("");
    getContentPane().add(lblFoto);
    lblFoto.setBounds(18, 256, 124, 146);

    JLabel lblNewLabel = new JLabel("PESQUISANDO...");
    lblNewLabel.setForeground(Color.ORANGE);
    lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 45));
    lblNewLabel.setBounds(269, 11, 403, 65);
    contentPane.add(lblNewLabel);

    JLabel lblPesquisar = new JLabel("");
    getContentPane().add(lblPesquisar);
    lblPesquisar.setBounds(144, 11, 86, 65);
    ImageIcon icon = new ImageIcon("C:/Users/André/Downloads/CEF04/src/imagens/pesquisar.png");
    Image image = icon.getImage().getScaledInstance(lblPesquisar.getWidth(), lblPesquisar.getHeight(), 1);
    lblPesquisar.setIcon(new ImageIcon(image));

    textField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {

            while (table.getModel().getRowCount() - 1 > 0) {
                // ((DefaultTableModel) table.getModel()).removeRow(0);
                ((DefaultTableModel) table.getModel()).setRowCount(0);
            }
            try {
                ArrayList<String> codigos = new ArrayList<>();

                //if(e.getKeyCode()==KeyEvent.VK_BACK_SPACE) {
                //JOptionPane.showMessageDialog(null, "A");
                //while(table.getModel().getRowCount()-1>0) {
                //((DefaultTableModel)table.getModel()).removeRow(0);
                //((DefaultTableModel) table.getModel()).setRowCount(0);
                //	}
                //}
                if (textField.getText().matches("^[a-z,A-Z,0-9, ,]*")) {

                    try {
                        con = DriverManager.getConnection(Servidor, Usuario, Senha);// pedindo conexão
                        String query = "SELECT * FROM cadastro WHERE Turma like '" + textField.getText() + "%'"; // criando query
                        PreparedStatement dados = (PreparedStatement) con.prepareStatement(query);//preparando o texto;
                        ResultSet rs = dados.executeQuery(); // executa query;
                        while (rs.next()) {// resultado da requisição feita no banco de dados
                            codigo = rs.getString("Codigo");
                            nome = rs.getString("Aluno");
                            turma = rs.getString("Turma");

                            codigo1 = "    " + codigo;
                            turma1 = "     " + turma;

                            val = (DefaultTableModel) table.getModel();
                            val.addRow(new String[]{codigo1, nome, turma1});;
                        }

                        table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

                            @Override
                            public void valueChanged(ListSelectionEvent evt) {
                                if (evt.getValueIsAdjusting()) {
                                    return;
                                }
                                int selected = table.getSelectedRow();

                                Object codigo_aluno = table.getValueAt(selected, 0);
                                codigo_aluno = ((String) codigo_aluno).replaceAll(" ", ""); //tira os espaços em branco que foram utilizados para centralizar

                                ImageIcon icon = new ImageIcon("C:\\Users\\Douglas\\Desktop\\DIURNO - Copia\\" + codigo_aluno + ".JPG");
                                Image image = icon.getImage().getScaledInstance(lblFoto.getWidth(), lblFoto.getHeight(), 1);
                                lblFoto.setIcon(new ImageIcon(image));

                            }
                        });

                    } catch (Exception k) {
                        System.out.println(k.getMessage());

                    }

                }

                if (textField.getText().matches("^[a-z,A-Z, ,Ã]*$")) {

                    try {
                        con = DriverManager.getConnection(Servidor, Usuario, Senha);// pedindo conexão
                        String query = "SELECT * FROM cadastro WHERE Aluno like '" + textField.getText() + "%'"; // criando query
                        PreparedStatement dados = (PreparedStatement) con.prepareStatement(query);//preparando o texto;
                        ResultSet rs = dados.executeQuery(); // executa query;
                        while (rs.next()) {// resultado da requisição feita no banco de dados
                            codigo = rs.getString("Codigo");
                            nome = rs.getString("Aluno");
                            turma = rs.getString("Turma");

                            codigo1 = "    " + codigo;
                            turma1 = "     " + turma;

                            val = (DefaultTableModel) table.getModel();
                            val.addRow(new String[]{codigo1, nome, turma1});;
                        }

                    } catch (Exception k) {
                        System.out.println(k.getMessage());

                    }

                }

                if (textField.getText().matches("^[0-9]*$")) {

                    try {
                        con = DriverManager.getConnection(Servidor, Usuario, Senha);// pedindo conexão
                        String query = "SELECT * FROM cadastro WHERE Codigo like '" + textField.getText() + "%'"; // criando query
                        PreparedStatement dados = (PreparedStatement) con.prepareStatement(query);//preparando o texto;
                        ResultSet rs = dados.executeQuery(); // executa query;
                        while (rs.next()) {// resultado da requisição feita no banco de dados
                            codigo = rs.getString("Codigo");
                            nome = rs.getString("Aluno");
                            turma = rs.getString("Turma");

                            codigo1 = "    " + codigo;
                            turma1 = "     " + turma;

                            val = (DefaultTableModel) table.getModel();
                            val.addRow(new String[]{codigo1, nome, turma1});;
                        }

                        table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

                            @Override
                            public void valueChanged(ListSelectionEvent evt) {
                                if (evt.getValueIsAdjusting()) {
                                    return;
                                }
                                int selected = table.getSelectedRow();
                                Object codigo_aluno = table.getValueAt(selected, 0);
                                codigo_aluno = ((String) codigo_aluno).replaceAll(" ", ""); //tira os espaços em branco que foram utilizados para centralizar
                                ImageIcon icon = new ImageIcon("C:\\Users\\Douglas\\Desktop\\DIURNO - Copia\\" + codigo_aluno + ".JPG");
                                Image image = icon.getImage().getScaledInstance(lblFoto.getWidth(), lblFoto.getHeight(), 1);
                                lblFoto.setIcon(new ImageIcon(image));

                            }
                        });;

                    } catch (Exception k) {
                        System.out.println(k.getMessage());

                    }

                }
            } catch (ArrayIndexOutOfBoundsException ex) {
                System.out.println("ERRO: " + ex);
            }
        }

    });

}

}

1 curtida