How to display records in a JTable from an arraylist .TXT file in java MVC?

一曲冷凌霜 提交于 2019-12-25 03:54:26

问题


Currently, this is my main screen: (

) I have 2 files: “patient.txt” and “treatment.txt” which hold records of multiple patients and treatments.

What I’m trying to do is to display all of those records in a nice JTable whenever I click “Display Treatments” or “Display Patients”, in a screen like so:

I am using an MVC model for this Hospital Management System (with HMSGUIModel.java, HMSGUIView.java, HMSGUIController.java, HMSGUIInterface.java files), and add records using the following code:

 FileWriter tfw = new FileWriter(file.getAbsoluteFile(), true); 
                BufferedWriter tbw = new BufferedWriter(tfw);
                tbw.write(this.view.gettNumber() + "," + this.view.gettName() + "," +     this.view.gettDoctor() + "," + this.view.gettRoom());
                tbw.newLine();
                tbw.flush();
                JOptionPane.showMessageDialog(null, "Successfully added treatment!"); }

Please help on how I can add a reader as well, to display all the records from the text file to a table?

Many thanks in advance!!


回答1:


Keeping in line with your MVC, you could create a TableModel which knew how to read a give patient record.

Personally though, I'd prefer to separate the management of the patient data from the view, so the view didn't care about where the data came from.

To this end, I would start by creating a Patient object and a Treatment object, these would hold the data in a self contained entity, making the management simpler...

You would need to read this data in and parse the results...

List<Treatment> treatments = new ArrayList<Treatment>(25);
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    String text = null;
    while ((text = br.readline()) != null) {
        String parts[] = text.split(",");
        Treatmeant treament = new Treatment(parts[0],
            parts[1],
            parts[2],
            parts[3]);
        treatments.add(treament);
    }
} // Handle exception as required...

I'd wrap this into a readTreatments method in some utility class to make it easier to use...

Around about here, I'd be considering using a stand alone database or even an XML document, but that's just me.

Once you have this, you can design a TableModel to support it...

public class TreatmentTableModel extends AbstractTableModel {

    protected static final String[] COUMN_NAMES = {
        "Treatment-Number", 
        "Treatment-Name",
        "Doctor-in-charge",
        "Room-No",
    };
    protected static final Class[] COLUMN_CLASSES = new Class[]{
        Integer.class, 
        String.class,
        Doctor.class,
        Integer.class,
    };
    private List<Treatment> treatments;

    public TreatmentTableModel() {
        this.treatments = new ArrayList<>();
    }

    public TreatmentTableModel(List<Treatment> treatments) {
        this.treatments = new ArrayList<>(treatments);
    }

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

    @Override
    public int getColumnCount() {
        return 4;
    }

    @Override
    public String getColumnName(int column) {
        return COUMN_NAMES[column];
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return COLUMN_CLASSES[columnIndex];
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Treatment treatment = treatments.get(rowIndex);
        Object value = null;
        switch (columnIndex) {
            case 0:
                value = treatment.getNumber();
                break;
            case 1:
                value = treatment.getName();
                break;
            case 2:
                value = treatment.getDoctor();
                break;
            case 3:
                value = treatment.getRoomNumber();
                break;
        }
        return value;
    }

}

Then you simply apply it to what ever JTable you need...

private JTable treatments;

//...
treatments = new JTable(new TreatmentTableModel());
add(new JScrollPane(treatments));

Then, we you need to, you would load the List of Treatments and apply it to the table...

File file = new File("...");
treatments.setModel(new TreatmentTableModel(TreatmentUtilities.readTreatments(file)));



回答2:


Depending on your needs for the table, you can look at using the DefaultTableModel and populating your data using that model. The downside to that is, you may want special capability from your table, like not being able to edit cells, store more than strings, etc... in which case you might look in to extending AbstractTableModel and defining your own behavior for the model.

A simple thing to do would be to start with the default model and expand on that.

String[] myColumns = {"Treatment-Number","Treatment-Name", "Doctor-in-charge", "Room-No"};
// init a model with no data and the specified column names
DefaultTableModel myModel = new DefaultTableModel(new Object[myList.size()][4](), myColumns);

// assuming you have a list of lists...
int i = 0;
int j = 0;
for (ArrayList<Object> list : myList) {
    for ( Object o : list ) {
        myModel.setValueAt(o, i, j);  // set the value at cell i,j to o
        j++;
    }
    i++;
} 

JTable myTable = new JTable(myModel);  // make a new table with the specified data model
// ... do other stuff with the table

If you want to access the table data, you use myTable.getModel() and update the data. This will automatically update the view of the table (completing the MVC connection)

Look here for more info on using tables.



来源:https://stackoverflow.com/questions/24817251/how-to-display-records-in-a-jtable-from-an-arraylist-txt-file-in-java-mvc

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