Search code examples
javaswingjframejoptionpane

Displaying a list of records in a Message Dialog


Here is the situation , i have a doctor record array where there are attributes such as first name , doctor id , contact number , etc. I am trying to display all the registered doctors ids and their contact numbers in a JOptionPane Message Dialog, I want this to happen when i press a button. It should be displayed as a list.

Is this possible ? I have tried it but i only managed to get one record displayed, other records are all jumbled.

Thank you for your time.


Solution

  • It should be straig forward

    sample:

    doctor class

    package com.doc;
    
    public class Doctor {
    
        private String name;
        private int id;
    
        public Doctor(String name, int id) {
            super();
            this.name = name;
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    }
    

    doctor demo

    package com.doc;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.swing.JOptionPane;
    
    public class DoctorDemo {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            List<Doctor> doctors = new ArrayList<Doctor>();
    
            // populate from database
            // im hard coding
            doctors.add(new Doctor("Test", 1));
            doctors.add(new Doctor("Test2", 2));
            doctors.add(new Doctor("Test3", 3));
            String message = "\n Doctor records \n ";
            for (Doctor doc : doctors) {
                message += "\n\n\n" + "Name:" + doc.getName() + "Id:" + doc.getId();
            }
            JOptionPane.showMessageDialog(null, message);
        }
    }
    

    This shows how to display in joption message dialog.