【发布时间】:2017-04-01 01:55:19
【问题描述】:
我正在根据用户输入创建一个 JTable。 There is a selection of radio buttons in the GUI and when a one is selected it needs to update all values of a column in the table.
我收到了一个 arrayIndexOutofBounds 错误。不完全确定我做错了什么。任何输入都将不胜感激,因为这是我第一次使用 jtable,而且比我想象的要难。
出现错误的代码:
class RadioListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(oneRadio.isSelected())
{
payAMT = payAMT * .01;
for(int i = 1; i < outputTable.getRowCount(); i++)
{
outputTable.setValueAt(payAMT,i,4);
}
}
代码:
//JTableCreation
model = new DefaultTableModel(new String[] {"Emp Num", "Base Pay", "Hours Worked", "Pay Amt"}, 0);
outputTable = new JTable();
outputTable.setModel(model);
JScrollPane scroll = new JScrollPane(outputTable);
更多代码 //向JTable添加条目
class clickListener implements ActionListener
{
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent e)
{
int empNum = 0;
double hourlyRate = 0;
double hoursWorked = 0;
try
{
empNum = Integer.parseInt(empNumField.getText());
}
catch(NumberFormatException event)
{
JOptionPane.showMessageDialog(null, "Invalid entry.\n\nPlease enter a number for the Employee ID.", "Error", JOptionPane.WARNING_MESSAGE);
return;
}
try
{
hourlyRate = Double.parseDouble(basePayField.getText());
}
catch(NumberFormatException event)
{
JOptionPane.showMessageDialog(null, "Invalid entry.\n\nPlease enter a number for the Hourly Pay Rate.", "Error", JOptionPane.WARNING_MESSAGE);
return;
}
try
{
hoursWorked = Double.parseDouble(hrsField.getText());
}
catch(NumberFormatException event)
{
JOptionPane.showMessageDialog(null, "Invalid entry.\n\nPlease enter a number for the Hours Worked.", "Error", JOptionPane.WARNING_MESSAGE);
return;
}
payAMT = calculatePay(hourlyRate, hoursWorked);
Object[] newRecord = {empNum,hourlyRate,hoursWorked,payAMT};
model.addRow(newRecord);
totalPayAMT += payAMT;
totalPayLabel.setText("Total Employee Pay: "+totalPayAMT);
}
}
【问题讨论】:
-
也许您想从索引 0 而不是 1 开始循环?
-
我在发帖前两种方式都试过了。同样的错误。
-
所以给我们一个具体的场景,当这段代码产生这个错误时。当列表为空时会发生这种情况吗?当它只有一个元素时会发生吗?当有很多元素时会发生这种情况吗?当您在调试器中单步调试代码时,您发现了哪些相关信息?由于您没有显示堆栈跟踪,您如何确定您指出的代码行是问题所在?
-
当 JTable 中没有条目时,不会发生错误。当 i = 1 时,仅当 JTable 中有 2 个或更多条目时才会发生错误。如果我设置 i=0,它会在 JTable 中有任何条目时发生。
标签: java arrays radio-button jtable