当前位置: 首页 > 知识库问答 >
问题:

如何解决我的java程序中的java.lang.ArrayIndexOutOfBoundsException:1>=0错误?[副本]

钮晟
2023-03-14

我的Java程序出错了。我认为发生这种情况是因为构造函数没有正确地内部化。

public class Hello {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        try
        {
            ScrollPaneRefresh scp=new ScrollPaneRefresh();
            scp.First();
            scp.createAndShowGui();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}
            package policyreader;

        import java.sql.*;
        import javax.swing.event.*;
        import javax.swing.*;
        import java.awt.event.*;
        import java.awt.*;
        import javax.swing.table.*;
        import java.util.*;
        import javax.swing.JComboBox;
        import javax.swing.SwingUtilities;
        import java.awt.event.ActionEvent;
        import java.awt.event.ActionListener;
        import javax.swing.JButton;
        import javax.swing.JPanel;
        import java.awt.GridLayout;
        import javax.swing.JFrame;
        import java.io.IOException;

        public class ScrollPaneRefresh extends JPanel {

        private static final int PREF_W = 600;
        private static final int PREF_H = 200;
        int b = 0;
        private String[][] newData = {
            {"", ""}
        };
        private String[] columnName = {"S.NO", "SOLUTIONS"};
        static Vector columnNames = new Vector();
        static Vector data = new Vector();
        static Vector columnNames56 = new Vector();
        static Vector data56 = new Vector();

        public static void First() {

            try {
                DefaultTableCellRenderer cent = new DefaultTableCellRenderer();
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

                Connection connect = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=conflictresolve.mdb;DriverID=22}", "", "");
                String sql = "Select * from geteffect";
                Statement stmt = connect.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
                ResultSetMetaData md = rs.getMetaData();
                int columns = md.getColumnCount();
                for (int i = 1; i <= columns; i++) {
                    columnNames.addElement(md.getColumnName(i));
                }
                while (rs.next()) {
                    Vector row = new Vector(columns);
                    for (int i = 1; i <= columns; i++) {
                        row.addElement(rs.getObject(i));
                    }
                    data.addElement(row);
                }
                rs.close();
                stmt.close();

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        public static void Second() {


            Vector columnNames = new Vector();
            Vector data = new Vector();
            Vector columnNames1 = new Vector();
            Vector columnNames2 = new Vector();
            Vector data1 = new Vector();
            Vector few = new Vector();
            Vector com = new Vector();
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                Connection connect = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=conflictresolve.mdb;DriverID=22}", "", "");

                String sql = "Select * from allsolutiontable";
                Statement stmt = connect.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
                ResultSetMetaData md = rs.getMetaData();

                String sql2 = "Select * from allsolutiontable";
                Statement stmt2 = connect.createStatement();
                ResultSet rs2 = stmt2.executeQuery(sql2);
                ResultSetMetaData md2 = rs2.getMetaData();

                String sql1 = "Select * from seteffect";
                Statement stmt1 = connect.createStatement();
                ResultSet rs1 = stmt1.executeQuery(sql1);
                ResultSetMetaData md1 = rs1.getMetaData();

                int columns = md.getColumnCount();

                for (int i = 1; i <= columns; i++) {
                    columnNames.addElement(md.getColumnName(i));
                }
                int columns1 = md1.getColumnCount();
                for (int i = 1; i <= columns1; i++) {
                    columnNames1.addElement(md1.getColumnName(i));
                }

                int columns2 = md2.getColumnCount();
                for (int i = 1; i <= columns2; i++) {
                    columnNames2.addElement(md2.getColumnName(i));
                }

                while (rs.next()) {
                    Vector row = new Vector();


                    for (int i = 1; i <= 2; i++) {
                        row.addElement(rs.getObject(i));
        //System.out.println(row);

                    }
                    data.addElement(row);
                }
                rs.close();
                stmt.close();
                while (rs2.next()) {

                    Vector large = new Vector();
        //for (int i = 1; i <=columns; i++) {
                    large.addElement(rs2.getObject(3));
        //}
                    few.addElement(large);
                }




                while (rs1.next()) {
                    Vector row1 = new Vector();
                    for (int i = 1; i <= 2; i++) {
                        row1.addElement(rs1.getObject(i));
                    }
                    data1.addElement(row1);
                }

                rs1.close();
                stmt1.close();
                rs2.close();
                stmt2.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        //System.out.println(columnNames);
        //System.out.println(columnNames1);
            System.out.println(data);
            System.out.println(data1);
            System.out.println(few);
            for (int i = 0; i < data.size(); i++) {
                for (int j = 0; j < data1.size(); j++) {
                    if (data.get(i).toString().compareTo(data1.get(j).toString()) == 0) {
                        com.addElement(few.get(i));
                        System.out.println("Solution" + few.get(i).toString());
                    }
                }
            }
            Connection co;
            Statement st1, st2;
            ResultSet rs1;
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                co = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=conflictresolve.mdb;DriverID=22}", "", "");
                st1 = co.createStatement();
                rs1 = st1.executeQuery("select * from conflictsolution");
                //st1=co.createStatement();

                for (int i = 0; i < com.size(); i++) {
                    String rr = "insert into conflictsolution values('" + com.get(i) + "')";
                    st1.executeUpdate(rr);
                }
                st1.close();
            } catch (Exception e) {
                System.out.println("there was some error in establishing connection : " + e);
            }

            try {
                DefaultTableCellRenderer cent = new DefaultTableCellRenderer();
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

                Connection connect = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=conflictresolve.mdb;DriverID=22}", "", "");
                String sql = "Select * from conflictsolution";
                Statement stmt = connect.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
                ResultSetMetaData md = rs.getMetaData();
                int columns = md.getColumnCount();
                for (int i = 1; i <= columns; i++) {
                    columnNames56.addElement(md.getColumnName(i));
                }
                while (rs.next()) {
                    Vector row = new Vector(columns);
                    for (int i = 1; i <= columns; i++) {
                        row.addElement(rs.getObject(i));
                    }
                    data56.addElement(row);
                }
                rs.close();
                stmt.close();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        public TablePanel gregsPanel = new TablePanel("SET THE EFFECTS FOR THE RULES", data, columnNames);       // line 208
        private TablePanel myPanel = new TablePanel("SOLUTIONS", data56, columnNames56, b);

        public ScrollPaneRefresh() {

            gregsPanel.setButtonAction(new AbstractAction("SUBMIT") {

                @Override
                public void actionPerformed(ActionEvent evt) {


                    gregsPanel.store();
                    Second();
                    myPanel.setTableModelDataVector(data56, columnNames56);


                }
            });
            setLayout(new GridLayout(0, 1));
            add(gregsPanel.getMainPanel());
            add(myPanel.getMainPanel());
        }

        @Override // so scrollbars will show
        public Dimension getPreferredSize() {
            return new Dimension(PREF_W, PREF_H);
        }

        public static void createAndShowGui() {
            ScrollPaneRefresh mainPanel = new ScrollPaneRefresh();
            try {
                JFrame frame = new JFrame("CONFLICT RESOLUTION FOR POLICYSET LEVEL");
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frame.getContentPane().add(mainPanel);
                frame.pack();
                frame.setBounds(10, 10, 1200, 600);
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            } catch (Exception ex) {
                ex.printStackTrace();
            }

        }

        public static void main(String[] args) throws Exception {
            SwingUtilities.invokeLater(new Runnable() {

                public void run() {
                    First();
                    createAndShowGui();
                }
            });
        }
        }

        class TablePanel {

        private JPanel mainPanel = new JPanel();
        private DefaultTableModel dm;
        private JTable table = new JTable();
        private JTable table1 = new JTable();
        private JButton changeTableBtn = new JButton();
        private JScrollPane scrollpane = new JScrollPane(table);
        private JScrollPane scrollpane1 = new JScrollPane(table1);

        public TablePanel(String title, Vector data, Vector columnNames) {
            try {
                dm = new DefaultTableModel(data, columnNames);
                table.setModel(dm);
                table.setRowHeight(30);

                TableColumn column = table.getColumnModel().getColumn(1); //  line 279
                //TableColumnModel tcm = table.getColumnModel();
                //tcm.getColumn(1).setPreferredWidth(10);
                column.setCellRenderer(new ComboBoxCellRenderer());
                column.setCellEditor(new ComboBoxCellEditor());
                // cent.setHorizontalAlignment(JLabel.CENTER);

                JPanel btnPanel = new JPanel();
                btnPanel.add(changeTableBtn);

                mainPanel.setBorder(BorderFactory.createTitledBorder(title));
                mainPanel.setLayout(new BorderLayout(5, 5));
                mainPanel.add(scrollpane, BorderLayout.CENTER);
                mainPanel.add(btnPanel, BorderLayout.PAGE_END);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        public TablePanel(String title, Vector data, Vector columnNames, int a) {
            dm = new DefaultTableModel(data, columnNames);
            table1.setModel(dm);
            JPanel btnPanel = new JPanel();
            //btnPanel.add(changeTableBtn);

            mainPanel.setBorder(BorderFactory.createTitledBorder(title));
            mainPanel.setLayout(new BorderLayout(5, 5));
            mainPanel.add(scrollpane1, BorderLayout.CENTER);
            mainPanel.add(btnPanel, BorderLayout.PAGE_END);
        }

        public void store() {
            Connection conn;
            Statement s;
            try {
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");           // Establish a connection
                conn = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=conflictresolve.mdb;DriverID=22}", "", "");
                System.out.println("Databse Connected");

                s = conn.createStatement();
                String sql = "INSERT INTO seteffect VALUES (?, ?)";
                PreparedStatement ps = conn.prepareStatement(sql);

                TableModel tm = table.getModel();

                int nRow = tm.getRowCount(), nCol = tm.getColumnCount();
                System.out.println(" rows:" + nRow + "columns:" + nCol);
                for (int r = 0; r < nRow; r++) {
                    for (int c = 1; c <= nCol; c++) {
                        //ps.setObject(c, tm.getValueAt(r, (nCol-1)));
                        if (c == 1) {
                            ps.setString(c, tm.getValueAt(r, c - 1).toString());

                        } /* else if(c==2)
                        {
                        ps.setString(c, tm.getValueAt(r, c-1).toString());
                        }*/ else {
                            ps.setString(c, tm.getValueAt(r, nCol - 1).toString());
                        }

                    }

                    ps.executeUpdate();
                }




                conn.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        public void setButtonAction(Action action) {
            changeTableBtn.setAction(action);
        }

        public void setTableModelDataVector(Vector data, Vector columnNames) {
            dm.setDataVector(data, columnNames);
        }

        public void fireTableDataChanged() {
            dm.fireTableDataChanged();
        }

        public JScrollPane getScrollPane() {
            return scrollpane;
        }

        public JComponent getMainPanel() {
            return mainPanel;
        }
        }

        class ComboBoxPanel extends JPanel {

        private String[] m = new String[]{"Permit", "Deny"};
        protected JComboBox<String> comboBox = new JComboBox<String>(m) {

            @Override
            public Dimension getPreferredSize() {
                Dimension d = super.getPreferredSize();
                return new Dimension(70, d.height);
            }
        };

        public ComboBoxPanel() {
            super();
            setOpaque(true);
            comboBox.setEditable(true);
            add(comboBox);
        }
        }

        class ComboBoxCellRenderer extends ComboBoxPanel
            implements TableCellRenderer {

        public ComboBoxCellRenderer() {
            super();
            setName("Table.cellRenderer");
        }

        @Override
        public Component getTableCellRendererComponent(
                JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            setBackground(isSelected ? table.getSelectionBackground()
                    : table.getBackground());
            if (value != null) {
                comboBox.setSelectedItem(value);
            }
            return this;
        }
        }

        class ComboBoxCellEditor extends ComboBoxPanel
            implements TableCellEditor {

        public ComboBoxCellEditor() {
            super();
            comboBox.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    fireEditingStopped();
                }
            });
            addMouseListener(new MouseAdapter() {

                @Override
                public void mousePressed(MouseEvent e) {
                    fireEditingStopped();
                }
            });
        }

        @Override
        public Component getTableCellEditorComponent(
                JTable table, Object value, boolean isSelected, int row, int column) {
            this.setBackground(table.getSelectionBackground());
            comboBox.setSelectedItem(value);
            return this;
        }

        //Copid from DefaultCellEditor.EditorDelegate
        @Override
        public Object getCellEditorValue() {
            return comboBox.getSelectedItem();
        }

        @Override
        public boolean shouldSelectCell(EventObject anEvent) {
            if (anEvent instanceof MouseEvent) {
                MouseEvent e = (MouseEvent) anEvent;
                return e.getID() != MouseEvent.MOUSE_DRAGGED;
            }
            return true;
        }

        @Override
        public boolean stopCellEditing() {
            if (comboBox.isEditable()) {
                comboBox.actionPerformed(new ActionEvent(this, 0, ""));
            }
            fireEditingStopped();
            return true;
        }
        //Copid from AbstractCellEditor
        protected EventListenerList listenerList = new EventListenerList();
        transient protected ChangeEvent changeEvent = null;

        @Override
        public boolean isCellEditable(EventObject e) {
            return true;
        }

        @Override
        public void cancelCellEditing() {
            fireEditingCanceled();
        }

        @Override
        public void addCellEditorListener(CellEditorListener l) {
            listenerList.add(CellEditorListener.class, l);

        }

        @Override
        public void removeCellEditorListener(CellEditorListener l) {
            listenerList.remove(CellEditorListener.class, l);
            System.out.println(listenerList);
        }

        public CellEditorListener[] getCellEditorListeners() {
            return listenerList.getListeners(CellEditorListener.class);
        }

        protected void fireEditingStopped() {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            // Process the listeners last to first, notifying
            // those that are interested in this event
            for (int i = listeners.length - 2; i >= 0; i -= 2) {
                if (listeners[i] == CellEditorListener.class) {
                    // Lazily create the event:
                    if (changeEvent == null) {
                        changeEvent = new ChangeEvent(this);
                    }
                    ((CellEditorListener) listeners[i + 1]).editingStopped(changeEvent);
                }
            }
        }

        protected void fireEditingCanceled() {
            // Guaranteed to return a non-null array
            Object[] listeners = listenerList.getListenerList();
            // Process the listeners last to first, notifying
            // those that are interested in this event
            for (int i = listeners.length - 2; i >= 0; i -= 2) {
                if (listeners[i] == CellEditorListener.class) {
                    // Lazily create the event:
                    if (changeEvent == null) {
                        changeEvent = new ChangeEvent(this);
                    }
                    ((CellEditorListener) listeners[i + 1]).editingCanceled(changeEvent);
                }
            }
        }
        }
        java.lang.ArrayIndexOutOfBoundsException: 1 >= 0
at java.util.Vector.elementAt(Vector.java:470)
at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:294)
at policyreader.TablePanel.<init>(ScrollPaneRefresh.java:279)
at policyreader.ScrollPaneRefresh.<init>(ScrollPaneRefresh.java:208)
at policyreader.Hello.main(Hello.java:20)

共有1个答案

壤驷华美
2023-03-14

您只需读取堆栈跟踪。异常在scrollpanerefresh.java:279处引发:

TableColumn column = table.getColumnModel().getColumn(1);

因此,您试图访问表的第二列。此表的模型是使用以下方法初始化的:

dm = new DefaultTableModel(data, columnNames);

这是由ScrollPaneRefResh的初始化调用的:

at policyreader.ScrollPaneRefresh.<init>(ScrollPaneRefresh.java:208)
public TablePanel gregsPanel = new TablePanel("SET THE EFFECTS FOR THE RULES", data, columnNames);
private TablePanel myPanel = new TablePanel("SOLUTIONS", data56, columnNames56, b);
static Vector columnNames = new Vector();
static Vector data = new Vector();
static Vector columnNames56 = new Vector();
static Vector data56 = new Vector();

所以一切都是空的。

坦率地说,您的代码一团糟。它使用公共字段,静态方法(应该是实例方法),所有东西都在一个文件中,JDBC代码与Swing代码混合在一起。在继续之前,您最好学会将单个职责分配给单个类,学习静态方法和实例方法之间的区别,并尊重Java命名约定。

 类似资料:
  • 我正在编写一个简单的Java代码,在输入第一个输入之后,我得到了这个错误: 代码:

  • 错误:(16,0)最小支持的渐变版本为3.3。当前版本为2.14.1。如果使用gradle包装器,请尝试将/var/www/html/pedometer-mass/gradle/wrapper/gradle-wrapper.properties中的distributionUrl编辑为gradle-3.3-all.zip

  • 我知道这个问题不是第一次讨论,但他们没有帮助我,请帮助(最好是详细的)。我已经在intellij IDEA上创建了一个EE web项目。与MySQL连接(下图),然后在index.jsp中编写此代码 运行后我出现了这个错误 “无法识别服务器时区值'ãåííàëüíà+±çèè(çèüà)'或代表多个时区。如果要利用时区支持,必须配置服务器或JDBC驱动程序(通过serverTimezone配置属性

  • 本文向大家介绍解决0-1背包问题的C ++程序,包括了解决0-1背包问题的C ++程序的使用技巧和注意事项,需要的朋友参考一下 在0-1背包问题中,给出了一组项目,每个项目都有一个权重和一个值。我们需要确定要包含在集合中的每个项目的数量,以使总重量小于或等于给定的限制,并且总值尽可能大。 输入项 输出结果 算法 范例程式码 输出结果

  • 最近,我在Flutter中遇到了一个错误: 谢谢。

  • 我知道有很多与此类似的问题,但它们并没有涵盖我的情况:“1.-”,其中不是占位符或负数,而是错误日志所述的内容。 我尝试了几种解决问题的方法,这些方法包含描述什么源发布无效的确切数字,但都不起作用。它昨天也工作正常,在我重启IntelliJ后停止工作。