Displaying the values of an Arraylist with a JTable

情到浓时终转凉″ 提交于 2020-01-06 04:24:05

问题


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());
}
}

回答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:


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




回答3:


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()
});


来源:https://stackoverflow.com/questions/24932977/displaying-the-values-of-an-arraylist-with-a-jtable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!