自定义AbstractTableModel无法正确显示数据

时间:2013-03-30 21:44:30

标签: java swing jtable abstracttablemodel

我想根据我使用AbstractTableModel指定的列从数据库中的表中提取数据。表中有8列,但只想显示8列中的3列。

例如:

数据库包含以下列:ID,First_Name,Last_Name,....,Phone_Number。如果我指定要在表中显示First_Name,Last_Name,Phone_Number,则会显示ID,First_Name和Last_Name。我想我应该从数据库中指定列名的索引以显示正确的列,但不知道如何在我的自定义AbstractTableModel类中实现它。

public class PhysicianModelController extends AbstractTableModel 
{
    PhysicianBroker pb = PhysicianBroker.getPhysicianBroker();

private String[] columnNames =  {"First Name", "Last Name", "Phone Number"};

private ArrayList<Physician> ph = pb.getAllPhysicians();

@Override
public int getRowCount() {
    return ph.size();
}

@Override
public int getColumnCount() {
    return columnNames.length;
}

@Override
public String getColumnName(int col)
{
    System.out.println(col);
    return columnNames[col];
}   

@Override
public String getValueAt(int rowIndex, int columnIndex) {  
    System.out.println(rowIndex + " : " + columnIndex);
    Physician p = ph.get(rowIndex);
    switch (columnIndex)
    {
        case 0:
            return Integer.toString(p.getEmployeeId());                
        case 1:
            return p.getFirstName();
        case 2:
            return p.getLastName();
        case 3:
            return p.getBirthDate();
        case 4:
            return p.getStartDate();
        case 5:
            return p.getEndDate();
        case 6:
            return p.getAddress();
        case 7:
            return p.getPhoneNumber();
        default:
            return "Incorrect input";                          
    }
}

public void addRow(Physician p) 
{
    ph.add(p);
    int row = ph.size();
    fireTableRowsInserted(row,row);
    fireTableDataChanged();
}

@Override
public Class getColumnClass(int c)
{
    return getValueAt(0,c).getClass();
}

}

我已经用我的实现覆盖了getRowCount(),getColumnCount(),getColumnName(),getValueAt()和getColumnClass()方法。一旦我提供了数据库表中的所有列,一切都能正常工作。

有人愿意帮我解释如何做到这一点吗?

由于

1 个答案:

答案 0 :(得分:1)

观看您的getValueAt方法。你只有三列。所以你应该根据它返回值。发生了什么,对于第0列,您获得了员工ID,而您想要Firstname..So on ...

@Override
public String getValueAt(int rowIndex, int columnIndex) {  
    System.out.println(rowIndex + " : " + columnIndex);
    Physician p = ph.get(rowIndex);
    switch (columnIndex)
    {

        case 0:
            return p.getFirstName();
        case 1:
            return p.getLastName();
        case 2:
            return p.getPhoneNumber();
        default:
            return "Incorrect input";                          
    }
}

<强>更新
这是一个在JTable中添加行的代码演示。看看它:

import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
import java.util.*;
class Person
{
    String name;
    String roll;
    String subject;
    public Person(String name,String roll,String subject)
    {
        this.name = name;
        this.roll = roll;
        this.subject = subject;
    }
    public String getName()
    {
        return name;
    }
    public String getRoll()
    {
        return roll;
    }
    public String getSubject()
    {
        return subject;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public void setRoll(String roll)
    {
        this.roll = roll;
    }
    public void setSubject(String subject)
    {
        this.subject = subject;
    }
}
class TableRowAdd extends JFrame  
{
    private JTable table;
    private JScrollPane jsPane;
    private MyModel myModel;
    private JPanel dialogPanel;
    private JTextField tf[];
    private JLabel     lbl[];
    private JButton    button;
    JDialog dialog;
    public void prepareAndShowGUI()
    {
        myModel = new MyModel();
        table = new JTable(myModel);
        jsPane = new JScrollPane(table);
        button = new JButton("Add");
        button.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent evt)
            {
                dialog.setVisible(true);
            }
        });
        getContentPane().add(button,BorderLayout.SOUTH);
        getContentPane().add(jsPane);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        prepareDialogPanel();
        pack();
        setVisible(true);

    }
    private void prepareDialogPanel()
    {
        dialogPanel = new JPanel();
        int col = table.getColumnCount();
        dialogPanel.setLayout(new GridLayout(col,2));
        tf = new JTextField[col];
        lbl = new JLabel[col];
        for (int i = 0; i < col; i++)
        {
            lbl[i] = new JLabel(table.getColumnName(i));
            tf[i] = new JTextField(10);
            dialogPanel.add(lbl[i]);
            dialogPanel.add(tf[i]);
        }
        dialog = new JDialog(this,"Enter details",true);
        dialog.getContentPane().add(dialogPanel);
        JButton okButton = new JButton("OK");
        dialog.getContentPane().add(okButton,BorderLayout.SOUTH);
        okButton.addActionListener( new ActionListener()
        {
            public void actionPerformed(ActionEvent evt)
            {
                dialog.dispose();
                myModel.addRow(new Person(tf[0].getText(),tf[1].getText(),tf[2].getText()));
            }
        });
        dialog.pack();
    }
    private class MyModel extends AbstractTableModel 
    {
        String[] columns = {
                            "Roll No.",
                            "Name",
                            "Subject"
                            };
        ArrayList<Person> inData = new ArrayList<Person>()
                            {
                                {
                                    add(new Person("1","Anthony Hopkins","CS01"));
                                    add(new Person("2","James William","CS02"));
                                    add(new Person("3","Mc. Donald","CS03"));
                                }
                            };
        @Override
        public void setValueAt(Object value, int row, int col)
        {
            Person person = inData.get(row);
            switch(col)
            {
                case 0: 
                    person.setRoll((String)value);
                    break;
                case 1:
                    person.setName((String)value);
                    break;
                case 2:
                    person.setSubject((String)value);
                    break;
                default:
                    System.out.println("Invalid col");

            }
            fireTableCellUpdated(row,col);
        }
        @Override
        public Object getValueAt(int row, int col)
        {
            Person person = inData.get(row);
            switch(col)
            {
                case 0: 
                    return person.getRoll();
                case 1:
                    return person.getName();
                case 2:
                    return person.getSubject();
                default:
                    return null;
            }
        }
        @Override
        public int getColumnCount()
        {
            return columns.length;
        }
        @Override 
        public int getRowCount()
        {
            return inData.size();
        }
        @Override
        public String getColumnName(int col)
        {
            return columns[col];
        }
        @Override
        public boolean isCellEditable(int row ,int col)
        {
            return true;
        }
        //This method adds a row to the table
        public void addRow(Person person)
        {
            inData.add(person);
            fireTableRowsInserted(inData.size() - 1 ,inData.size() - 1);
        }
    }
    public static void main(String st[])
    {
        SwingUtilities.invokeLater( new Runnable()
        {
            @Override
            public void run()
            {
                TableRowAdd td = new TableRowAdd();
                td.prepareAndShowGUI();
            }
        });
    }
}