JComboBox中。从MYSQL填充数据

时间:2015-02-04 16:28:58

标签: java jcombobox

嗨,我正在研究Java应用程序。我有一些问题。当我第一次运行app时没有任何问题。我想在选择教员时清除以前的部门和小组信息并加载新的结果。但是当我选择教员时我会遇到一些错误......我无法解决这个问题......请帮我解决一下......

以下是代码和错误。

import java.awt.EventQueue;

import javax.swing.JFrame;

import java.awt.BorderLayout;
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;

import net.miginfocom.swing.MigLayout;

import javax.swing.UIManager;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JPopupMenu;

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

import javax.swing.JMenuItem;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;


public class showStudentSection {

    private String db;
    private String db_user;
    private String db_pass;

    private JFrame frmStudents;
    private JTable table;

    private Lang lang = new Lang();
    private Theme theme = new Theme();
    private doSpecificOperations ops = new doSpecificOperations();
    private getTables getTable = new getTables();

    private JComboBox<String> comboGroup;
    private JComboBox<String> comboDepartment;
    private JComboBox<String> comboFaculty;
    private ArrayList<Integer> groupID = new ArrayList<Integer>();
    private ArrayList<Integer> depID = new ArrayList<Integer>();
    private ArrayList<Integer> facultyID = new ArrayList<Integer>();

    private Boolean first_time_fac = true;
    private Boolean first_time_dep = true;
    private Boolean first_time_grp = true;

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (Throwable e) {
            e.printStackTrace();
        }
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    showStudentSection window = new showStudentSection();
                    window.frmStudents.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public showStudentSection() {
        initialize();
    }


    private void initialize() {
        getDB();

        frmStudents = new JFrame();
        frmStudents.getContentPane().setBackground(theme.setColor(1));
        frmStudents.setTitle("Students");
        frmStudents.setBounds(100, 100, 909, 473);
        frmStudents.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frmStudents.getContentPane().setLayout(new BorderLayout(0, 0));

        JPanel upPanel = new JPanel();
        upPanel.setBorder(new LineBorder(theme.setColor(3)));
        upPanel.setBackground(theme.setColor(1));
        frmStudents.getContentPane().add(upPanel, BorderLayout.NORTH);

        JLabel lblFaculty = new JLabel("Faculty:");
        lblFaculty.setBackground(theme.setColor(1));
        lblFaculty.setForeground(theme.setColor(2));
        upPanel.add(lblFaculty);

        comboFaculty = new JComboBox<String>();
        comboFaculty.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {

                if(first_time_fac==false){
                    LoadDepartments(facultyID.get(comboFaculty.getSelectedIndex()));

                }

                first_time_fac=false;
            }
        });
        comboFaculty.setBackground(theme.setColor(1));
        upPanel.add(comboFaculty);

        JLabel lblDepartment = new JLabel("Department:");
        lblDepartment.setBackground(theme.setColor(1));
        lblDepartment.setForeground(theme.setColor(2));
        upPanel.add(lblDepartment);

        comboDepartment = new JComboBox<String>();
        comboDepartment.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                if(first_time_dep==false){
                    LoadGroups(depID.get(comboDepartment.getSelectedIndex()));
                }

                first_time_dep=false;
            }
        });
        comboDepartment.setBackground(theme.setColor(1));
        upPanel.add(comboDepartment);

        JLabel lblGroup = new JLabel("Group:");
        lblGroup.setBackground(theme.setColor(1));
        lblGroup.setForeground(theme.setColor(2));
        upPanel.add(lblGroup);

        comboGroup = new JComboBox<String>();
        comboGroup.setBackground(theme.setColor(1));
        upPanel.add(comboGroup);

        JPanel downPanel = new JPanel();
        downPanel.setBorder(new LineBorder(theme.setColor(3)));
        downPanel.setBackground(theme.setColor(1));
        frmStudents.getContentPane().add(downPanel, BorderLayout.SOUTH);

        JButton btnClose = new JButton("Close");
        btnClose.setBackground(theme.setColor(1));
        btnClose.setForeground(theme.setColor(2));
        downPanel.add(btnClose);

        JPanel leftPanel = new JPanel();
        leftPanel.setBackground(theme.setColor(1));
        frmStudents.getContentPane().add(leftPanel, BorderLayout.WEST);
        leftPanel.setLayout(new MigLayout("", "[]", "[][][][][][][]"));

        JLabel lblStudentOperations = new JLabel("Student operations");
        lblStudentOperations.setBackground(theme.setColor(1));
        lblStudentOperations.setForeground(theme.setColor(2));
        leftPanel.add(lblStudentOperations, "cell 0 0,growx");

        JButton btnAddStudent = new JButton("Add student");
        btnAddStudent.setBackground(theme.setColor(1));
        btnAddStudent.setForeground(theme.setColor(2));
        leftPanel.add(btnAddStudent, "cell 0 1,growx");

        JButton btnDeleteStudent = new JButton("Delete student");
        btnDeleteStudent.setBackground(theme.setColor(1));
        btnDeleteStudent.setForeground(theme.setColor(2));
        leftPanel.add(btnDeleteStudent, "cell 0 2,growx");

        JButton btnEditStudent = new JButton("Edit student");
        btnEditStudent.setBackground(theme.setColor(1));
        btnEditStudent.setForeground(theme.setColor(2));
        leftPanel.add(btnEditStudent, "cell 0 3,growx");

        JLabel lblOperations = new JLabel("Other operations");
        lblOperations.setBackground(theme.setColor(1));
        lblOperations.setForeground(theme.setColor(2));
        leftPanel.add(lblOperations, "cell 0 4,growx");

        JButton btnFindStudent = new JButton("Find student");
        btnFindStudent.setBackground(theme.setColor(1));
        btnFindStudent.setForeground(theme.setColor(2));
        leftPanel.add(btnFindStudent, "cell 0 5,growx");

        JButton btnSaveTable = new JButton("Save table (xls)");
        btnSaveTable.setBackground(theme.setColor(1));
        btnSaveTable.setForeground(theme.setColor(2));
        leftPanel.add(btnSaveTable, "cell 0 6,growx");

        JPanel center = new JPanel();
        frmStudents.getContentPane().add(center, BorderLayout.CENTER);
        center.setLayout(new BorderLayout(0, 0));

        JScrollPane scrollPane = new JScrollPane();
        center.add(scrollPane, BorderLayout.CENTER);

        table = new JTable();
        table.setSelectionBackground(theme.setColor(5));
        table.setShowVerticalLines(true);
        table.setShowHorizontalLines(true);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        scrollPane.setViewportView(table);

        JPopupMenu popupMenu = new JPopupMenu();
        addPopup(table, popupMenu);

        JMenuItem mntmSeeStudentInformation = new JMenuItem("See student information");
        popupMenu.add(mntmSeeStudentInformation);

        LoadFaculties();
        LoadDepartments(facultyID.get(comboFaculty.getSelectedIndex()));
        LoadGroups(depID.get(comboDepartment.getSelectedIndex()));

        LoadStudents("WHERE facultyID="+facultyID.get(comboFaculty.getSelectedIndex())+" AND depID="+depID.get(comboDepartment.getSelectedIndex()) + " AND groupID="+groupID.get(comboGroup.getSelectedIndex()));

    }

    private void LoadStudents(String query)
    {

        DefaultTableModel model = new DefaultTableModel(){

            private static final long serialVersionUID = 1L;

            @Override
            public boolean isCellEditable(int row, int column)
            {
                return false;
            }

        };
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection elaqe = DriverManager.getConnection(db,db_user,db_pass);
            Statement sorgu = elaqe.createStatement();
            ResultSet netice = sorgu.executeQuery("SELECT * FROM students " + query);
            int c_count = netice.getMetaData().getColumnCount();

            model.addColumn(lang.translate("student_no"));
            model.addColumn(lang.translate("name_surname"));
            model.addColumn(lang.translate("sex"));
            model.addColumn(lang.translate("birthday"));
            model.addColumn(lang.translate("birth_place"));
            model.addColumn(lang.translate("admission_year"));
            model.addColumn(lang.translate("profession"));
            model.addColumn(lang.translate("phone"));
            model.addColumn(lang.translate("e_mail"));
            model.addColumn(lang.translate("education_status"));

            while(netice.next())
            {
                Object[] row = new Object[c_count];
                row[0] = netice.getString("studentNO");
                row[1] = netice.getString("name");
                row[2] = netice.getString("gender");
                row[3] = netice.getString("date_birth");
                row[4] = netice.getString("place_birth");
                row[5] = netice.getString("admission_date");
                row[6] = getTable.getStudentProfessionText(netice.getString("profession"));
                row[7] = netice.getString("phone");
                row[8] = netice.getString("e_mail");
                row[9] = getTable.getStudentStatusText(netice.getString("education_status"));

                model.addRow(row);
            }

            elaqe.close();
            sorgu.close();

            table.setModel(model);
        } catch (Exception e) {
            ops.createInfoMessage(lang.translate("error"),lang.translate("db_error")+" (" + e.toString().substring(0, 40) + ")");
        }
    }

    private void LoadFaculties()
    {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection elaqe = DriverManager.getConnection(db,db_user,db_pass);
            Statement sorgu = elaqe.createStatement();
            ResultSet netice = sorgu.executeQuery("SELECT * FROM faculties");

            while(netice.next())
            {
                comboFaculty.addItem(netice.getString("name"));
                facultyID.add(netice.getInt("facultyID"));
            }

            elaqe.close();
            sorgu.close();
        } catch (Exception e) {
            ops.createInfoMessage(lang.translate("error"),lang.translate("db_error")+" (" + e.toString().substring(0, 40) + ")");
        }
    }

    private void LoadDepartments(int facultyID)
    {       
        comboDepartment.removeAllItems();
        depID.clear();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection elaqe = DriverManager.getConnection(db,db_user,db_pass);
            Statement sorgu = elaqe.createStatement();
            ResultSet netice = sorgu.executeQuery("SELECT * FROM department WHERE facultyID="+facultyID);

            while(netice.next())
            {
                comboDepartment.addItem(netice.getString("name"));
                depID.add(netice.getInt("depID"));
            }

            elaqe.close();
            sorgu.close();
        } catch (Exception e) {
            ops.createInfoMessage(lang.translate("error"),lang.translate("db_error")+" (" + e.toString().substring(0, 40) + ")");
        }
    }

    private void LoadGroups(int depID)
    {   
        comboGroup.removeAllItems();
        groupID.clear();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection elaqe = DriverManager.getConnection(db,db_user,db_pass);
            Statement sorgu = elaqe.createStatement();
            ResultSet netice = sorgu.executeQuery("SELECT * FROM groups WHERE depID="+depID);

            while(netice.next())
            {
                comboGroup.addItem(netice.getString("name"));
                groupID.add(netice.getInt("groupID"));
            }

            elaqe.close();
            sorgu.close();
        } catch (Exception e) {
            ops.createInfoMessage(lang.translate("error"),lang.translate("db_error")+" (" + e.toString().substring(0, 40) + ")");
        }
    }

    private void getDB()
    {
        try {
            BufferedReader bf = new BufferedReader(new FileReader(".\\mysql.db"));
            db = ops.decodeText(bf.readLine());
            db_user = ops.decodeText(bf.readLine());
            db_pass = ops.decodeText(bf.readLine());

            bf.close();
        } catch (Exception e) {
            ops.createInfoMessage(lang.translate("error"),lang.translate("cant_get_db_info")+" (" + e.toString().substring(0, 40) + ")");
        }
    }

    private static void addPopup(Component component, final JPopupMenu popup) {
        component.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    showMenu(e);
                }
            }
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    showMenu(e);
                }
            }
            private void showMenu(MouseEvent e) {
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        });
    }
}

和错误

Exception in thread "AWT-EventQueue-0"  java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.elementData(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at showStudentSection$3.actionPerformed(showStudentSection.java:133)
at javax.swing.JComboBox.fireActionEvent(Unknown Source)
at javax.swing.JComboBox.contentsChanged(Unknown Source)
at javax.swing.JComboBox.intervalRemoved(Unknown Source)
at javax.swing.AbstractListModel.fireIntervalRemoved(Unknown Source)
at javax.swing.DefaultComboBoxModel.removeAllElements(Unknown Source)
at javax.swing.JComboBox.removeAllItems(Unknown Source)
at showStudentSection.LoadDepartments(showStudentSection.java:310)
at showStudentSection.access$4(showStudentSection.java:308)
at showStudentSection$2.actionPerformed(showStudentSection.java:112)
at javax.swing.JComboBox.fireActionEvent(Unknown Source)
at javax.swing.JComboBox.setSelectedItem(Unknown Source)
at javax.swing.JComboBox.setSelectedIndex(Unknown Source)
at javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(Unknown Source)
at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at javax.swing.plaf.basic.BasicComboPopup$1.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)**strong text**

1 个答案:

答案 0 :(得分:3)

只需阅读堆栈跟踪...

在第310行清除comboBox时:

comboDepartment.removeAllItems();

您可以调用您组合的actionListener,然后在第133行调用

LoadGroups(depID.get(comboDepartment.getSelectedIndex()));

刚刚清除了组合,getSelectedIndex()返回-1并且get失败。

结论:如果getSelectedIndex()等于-1,则不加载组。