我有多個JSpinner
其中有項1-10和一個JTable
。點擊JSpinner
後,該值將被添加到JTable
。我想獲得行號,所以我可以在setValueAt
上使用它。但當JSpinner
點擊超過一次時,我會收到錯誤消息。java.lang.ArrayIndexOutOfBoundsException
代碼
public void stateChanged(ChangeEvent e) { // when JSpinner clicked
int quantity = (int) ((JSpinner) e.getSource()).getValue();
int rows = table.getRowCount();
for (int i = 0; i < ELEMENTS; i++) {
if (numspinner[i] == e.getSource()) {
if (quantity == 1) {
System.out.println("Row"+rows);
dtm.addRow(new Object[] { foodLabel[i].getText(), quantity, price[i] * quantity });
} else {
System.out.println("Row"+rows);
dtm.setValueAt(quantity, rows, 3);
}
}
}
}
我點擊了相同的JSpinner,曾多次和得到這個輸出
Row1
Row2
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
at java.util.Vector.elementAt(Unknown Source)
at javax.swing.table.DefaultTableModel.setValueAt(Unknown Source)
at gui.FoodOrdering.stateChanged(FoodOrdering.java:250)
at javax.swing.JSpinner.fireStateChanged(Unknown Source)
at javax.swing.JSpinner$ModelListener.stateChanged(Unknown Source)
at javax.swing.AbstractSpinnerModel.fireStateChanged(Unknown Source)
at javax.swing.SpinnerNumberModel.setValue(Unknown Source)
at javax.swing.JSpinner.setValue(Unknown Source)
at javax.swing.plaf.basic.BasicSpinnerUI$ArrowButtonHandler.actionPerformed(Unknown Source)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
任何幫助,將不勝感激。
我還可以將一些代碼,並在此最新
public void stateChanged(ChangeEvent e) {
int quantity = (int) ((JSpinner) e.getSource()).getValue();
int rows = 0;
for (int i = 0; i < ELEMENTS; i++) {
if (numspinner[i] == e.getSource()) {
if (quantity == 1) {
System.out.println("Row"+rows);
rows = table.getRowCount();
dtm.addRow(new Object[] { foodLabel[i].getText(), quantity, price[i] * quantity });
} else {
System.out.println(" The Row"+rows);
dtm.setValueAt(quantity, rows, 1); // obj,column,row
}
}
}
}
如果數量爲1,它增加了行預期。再次單擊相同的JSpinner時,它始終顯示0!
隨着從零開始的指數,像'JTable' /'TableModel','getRowCoun()'返回的行數,比最後一行的指數大。 EG如果你有3行,它們索引爲0; 1; 2.沒有索引3 ... –
@UsagiMiyamoto我以爲2是列? – Tony
stacktrace顯示調用了'setValueAt()'方法,並調用了'Vector.elementAt()',這引發了異常。調用'setValueAt()'方法的列值爲常量3 ... –