-1

该程序必须从 MySQL 数据库下载数据。并填写 JList。我想绑定这些数据。

在这里你有一个代码:

        Connection connection = null;
        String dbtime;
        String query = "Select * FROM EMP";
        String[] celDatas = null;
        String[] celNames = null;
        try {

            (...)

            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            ResultSetMetaData rsmd = rs.getMetaData();

            int NumOfCol = rsmd.getColumnCount();
            celNames = new String[NumOfCol];
            celDatas = new String[NumOfCol];

            for(int weq=1; weq<=NumOfCol; weq++) {
                System.out.println(rsmd.getColumnName(weq));
                celNames[weq] = rsmd.getColumnName(weq);
                while (rs.next()) {
                    dbtime = rs.getString(weq);
                    System.out.println(dbtime);
                    celDatas[weq] = dbtime;
                }
                rs = stmt.executeQuery(query);
                System.out.println();
            }
        } catch (ClassNotFoundException e) {

        } catch (SQLException e) {

        }


    final JList source = new JList(celDatas,celNames);
    JScrollPane pane = new JScrollPane(source);
    pane.setSize(f.getSize().width-60,300);
    pane.setLocation(30,20);

如您所见,这些字符串数组位于 try 括号中,这可能是问题的根源。

当我编译我的程序时,它显示:

at Application2.run(Application2.java:261)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:682)
at java.awt.EventQueue.access$000(EventQueue.java:85)
at java.awt.EventQueue$1.run(EventQueue.java:643)
at java.awt.EventQueue$1.run(EventQueue.java:641)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:652)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

Application2.java:261 是 celNames[weq] = rsmd.getColumnName(weq);

如何解决问题?

4

1 回答 1

0

您正在索引celNames[]cellDatas[]using ,它通过inclusiveweq迭代值,而数组是 size ,因此您将它们索引到了边界之外。1NumOfCol NumOfCol

相反,像这样索引你的数组:

celNames[weq - 1]
celDatas[weq - 1]

顺便说一句,按照惯例,变量名应该以小写字母开头,所以NumOfCol应该是numOfCol.

于 2012-04-15T01:22:43.433 回答