I'm trying create a JTable that creates the table based on information from an ArrayList. The ArrayList is filled with information that the user enters in the GUI. Every time the user presses a JButton it should add a new row of data to the table.
After googling it seems that the best way to do this is to create a custom table model. I cannot find a decent tutorial on how to do this. I've looked at the official documentation, and a few random sites and other postings. Hopefully one of you can point me in the right direction.
Here's a picture of my current GUI. The JTable should populate the center region:
And here is some of my code:
class dataModel extends AbstractTableModel
{
private String[] columnName = {"Emp Num", "Base Pay", "Hours Worked", "Pay Amt"};
public int getColumnCount()
{
return 4;
}
public int getRowCount()
{
return empData.size();
}
public Object getValueAt(int row, int col)
{
return new Integer(row*col);
}
}
The class that occurs on button click.
class listener implements ActionListener
{
@SuppressWarnings("unchecked")
public void actionPerformed(ActionEvent e)
{
ArrayList empData = new ArrayList();
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;
}
double payAMT = calculatePay(hourlyRate, hoursWorked);
empData.add(empNum);
empData.add(hourlyRate);
empData.add(hoursWorked);
empData.add(payAMT);
}