1

I created a class named EmployeeGUI that is able to create any amount of user Employee objects and add them to an arraylist. The problem i have is that i have a JTable at the bottom of my GUI that i want to display all the objects that i've created but in my case the GUI Creates a new Table Object each time it goes through a for loop with the details of an object but as the for loop goes on the new details overwrites the old details rather than being added to the bottom of a jtable. Can anyone help me debug my errors?

Here is my Code

import java.awt.event.*;

public class EmployeeGUI extends JFrame implements ActionListener{

/**
 * @param args
 */
JFrame frame;
JButton button1, button2, button3, button4;
JTextField box1, box2, box3;
JLabel label1, label2, label3;
JTable table1;
int length = 0;
ArrayList<Employee> empArray = new ArrayList<Employee>();

public static void main(String[] args) {
    // TODO Auto-generated method stub
    EmployeeGUI empG = new EmployeeGUI();
    empG.frame.setVisible(true);
}

public EmployeeGUI()
{
    initialize();
}

public void initialize() {
    // TODO Auto-generated method stub
    frame = new JFrame("A Sample Window");
    frame.setBounds(50,50,680,400);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

    label1 = new JLabel("F-Name:");
    label1.setBounds(30,33,54,25);
    frame.getContentPane().add(label1);

    box1 = new JTextField();
    box1.setBounds(94, 35, 128,20);
    frame.getContentPane().add(box1);

    label2 = new JLabel("S-Name:");
    label2.setBounds(250,33,54,25);
    frame.getContentPane().add(label2);

    box2 = new JTextField();
    box2.setBounds(305, 35, 128,20);
    frame.getContentPane().add(box2);

    label3 = new JLabel("Phone:");
    label3.setBounds(461,33,54,25);
    frame.getContentPane().add(label3);

    box3 = new JTextField();
    box3.setBounds(500, 35, 128,20);
    frame.getContentPane().add(box3);

    button1 = new JButton("Add Employee");
    button1.addActionListener(this);
    button1.setBounds(71,131,113,39);
    frame.getContentPane().add(button1);

    button2 = new JButton("Remove Employee");
    button2.addActionListener(this);
    button2.setBounds(194,131,128,39);
    frame.getContentPane().add(button2);

    button3 = new JButton("Display Employee");
    button3.addActionListener(this);
    button3.setBounds(332,131,128,39);
    frame.getContentPane().add(button3);

    button4 = new JButton("Quit Program");
    button4.addActionListener(this);
    button4.setBounds(475,131,113,39);
    frame.getContentPane().add(button4);

    table1 = new JTable();
    table1.setBounds(0,184,664,178);
    frame.getContentPane().add(table1);
}

@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    String action = ((JButton) e.getSource()).getActionCommand();
    if(action.equals("Add Employee"))
    {
        String fName = box1.getText();
        String lName = box2.getText();
        String pNo = box3.getText();

        int mobile = Integer.parseInt(pNo);

        Employee ee = new Employee(fName,lName,mobile);
        empArray.add(ee);
        length++;
        JOptionPane.showMessageDialog(null, "Employee Added");
    }
    if(action.equals("Remove Employee"))
    {
        String fName = box1.getText(), lName = box2.getText(); 
        int mobile = Integer.parseInt(box3.getText());
        Employee ee = new Employee(fName,lName,mobile);
        if(length>0)
        {
            for(int i=0; i<empArray.size(); i++)
            {
                if(empArray.get(i).getLName() == ee.getLName())
                {
                    empArray.remove(i);
                    JOptionPane.showMessageDialog(null, "Employee Removed");
                }
            }
        }
        else{       
            throw new ListEmptyException("List is Empty");
        }
    }
    if(action.equals("Display Employee"))
    {
        for(int i = 0; i <empArray.size(); i++)
        {
            table1.setModel(new DefaultTableModel(
                    new Object[][] {
                            {empArray.get(i).getFName(),empArray.get(i).getLName(),empArray.get(i).getMobile()}
                    },
                    new String[] {
                        "First Name", "Surname", "Phone Number"
                    }
                ));
        }
    }
    if(action.equals("Quit Program"))
    {
        System.exit(0);
    }
}
}

and the Employee Class

public class Employee {
private String fName,lName;
private int mobile;

public Employee(String fName, String lName, int mobile)
{
    setFName(fName);
    setLName(lName);
    setMobile(mobile);
}

private void setMobile(int mobile) {
    // TODO Auto-generated method stub
    this.mobile = mobile;
}

public void setLName(String lName) {
    // TODO Auto-generated method stub
    this.lName = lName;
}

public void setFName(String fName) {
    // TODO Auto-generated method stub
    this.fName = fName;
}

public String getFName()
{
    return fName;
}

public String getLName()
{
    return lName;
}

public int getMobile()
{
    return mobile;
}

public String toString()
{
    return getFName()+" "+getLName()+" "+getMobile();
}

public void print()
{
    System.out.println(toString());
}
}
2
  • Ouch on that System.exit(0)... You reset the Table model everytime. Use a custom MutableTableModel and model.fireTableDataChanged() instead. Commented Jul 24, 2014 at 12:00
  • 1
    You're creating a new TableModel with each iteration of the for loop -- so you shouldn't be surprised that your code is doing what it's doing. Solution: don't do that. Create one model before the for loop, and fill it with items from inside the for loop. This isn't Java, it's common sense. Also, you need to get rid of the setBounds and use layout managers. Commented Jul 24, 2014 at 12:00

3 Answers 3

2

only comment, longer

  • see number of table1.setModel(new DefaultTableModel( created in loop for(int i = 0; i <empArray.size(); i++)

  • new Object[][] {{empArray.get(i).getFName(), empArray.get(i).getLName(),empArray.get(i).getMobile()}}, is converted to DataVector, you lost, haven't access to this array

  • (if is there reason to hold two the same arrays in your program then) use array based on util.List in AbstractTableModel

Sign up to request clarification or add additional context in comments.

Comments

1

the new details overwrites the old details rather than being added to the bottom of a jtable.

First add all the record in a List then set the model just once otherwise it will override the last one in loop.

sample code:

if (action.equals("Display Employee")) {
    List<Object[]> list = new ArrayList<Object[]>();
    for (int i = 0; i < empArray.size(); i++) {
        list.add(new Object[] { 
                                  empArray.get(i).getFName(), 
                                  empArray.get(i).getLName(),
                                  empArray.get(i).getMobile() 
                              });

    }
    table1.setModel(new DefaultTableModel(list.toArray(new Object[][] {}), 
                        new String[] {"First Name", "Surname", "Phone Number"}));
}

2 Comments

@Braj you are like my guardian angel, This works perfectly, but i had to change "List<Object[]> list = new ArrayList<Object[]>();" to "ArrayList<Object[]> list = new ArrayList<Object[]>();" For the Code to work, but dude thanks for your input, Again :)
always try to code with interface. what about if in future you want to change it to other implementation of List interface.
0

You can use the addRow() method of the DefaultTableModel, like this:

((DefaultTableModel)table1.getModel()).addRow(new Object[] { 
     empArray.get(i).getFName(),
     empArray.get(i).getLName(),
     empArray.get(i).getMobile()
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.