我从用户输入创建JTable。 GUI中有一系列单选按钮,当选择一个时,它需要更新表中列的所有值。
我得到一个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)
你需要在0开始你的JTable迭代。行和JTable的列是基于0的。当你从1开始 for 循环时,你并没有像你想象的那样从第一行开始,你实际上是从第2行开始。你也陷入困惑的地方是 JTable.getRowCount()方法。此方法将返回JTable中当前包含的实际行数,因此您需要调整其值(减去1)以便将其用于迭代,例如:
int cnt = outputTable.getRowCount();
if(oneRadio.isSelected() && cnt > 0) {
payAMT = payAMT * .01;
for(int i = 0; i < cnt - 1; i++) {
outputTable.setValueAt(payAMT, i, 4);
}
}