how to use hashMap with JTable

前端 未结 6 1870
深忆病人
深忆病人 2021-01-03 02:13

i have a hashMap which i would like its data to be viewed in a JTable how ever i am having trouble getting the hashMap amount of columns and rows and the data to be displaye

相关标签:
6条回答
  • 2021-01-03 02:47

    The way to do this is by implementing the TableModel interface for the student register (aka SortedMap). The TableModel is the table model representation of how the Swing JTable expects its data. The TableModel interface, gives full flexibilty of providing that data.

    Once that implementation is created, creating a JTable is straight on:

    // As StudentRegistration class
    new JTable(new StudentTableModel(studentRegistration));
    // Or as SortedMap<String, Student>
    new JTable(new StudentTableModel(students));
    

    In this scenario I expect that the plain SortedMap<String, Student> is not directly given, but a instance of StudentRegistration, which contains a SortedMap<String, Student> like that.

    /**
     * Models the {@link Student} entries as a Swing TableModel. 
     */
    final public class StudentTableModel implements TableModel {
        /** The TableModel column names. */
        public final String columnNames[] = 
                new String[] {
                    "Name", "Identification", "Age"
                };
        /** The list of TableModelListeners. */
        private final ArrayList<TableModelListener> tableModelListenerList = new ArrayList<TableModelListener>();
        /** The manager containing all the Student instances. */
        private final StudentRegistration register;
    
    
        public StudentTableModel(StudentRegistration register) {
            super();
            this.register = register;
        }
    
    
        public Class<?> getColumnClass(int columnIndex) {
            return null;
        }
    
    
        public int getColumnCount() {
            return columnNames.length;
        }
    
        public String getColumnName(int columnIndex) {
            return (columnIndex < columnNames.length) ? columnNames[columnIndex] : null;
        }
    
        public int getRowCount() {
            return register.getStudents().size();
        }
    
    
        public Object getValueAt(int rowIndex, int columnIndex) {
            // One solution
            String identification = register.getStudentIds().toArray()[rowIndex];
            Student student = register.getStudent(identification);
            // Other option
            SortedMap<String, Student> studentMap = register.getStudents();
            String[] studentIdArray = studentMap.keySet().toArray(new String[studentMap.keySet().size()]);
            Student student = studentMap.get(studentIdArray[rowIndex]);
            final Object result;
            switch (columnIndex) {
                case 0:
                    result = student.getName();
                    break;
                case 1:
                    result = student.getIdentification();
                    break;
                case 2:
                    result = student.getAge();
                    break;
                default:
                    result = null;
            }
            return result;
        }
    
    
        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return false;
        }
    
        public void setValueAt(Object value, int rowIndex, int columnIndex) {
            // Just ignore, model is read only.
        }   
    
    
        public void addTableModelListener(TableModelListener tml) {
            if (! tableModelListenerList.contains(tml)) {
                tableModelListenerList.add(tml);
            }
        }
    
        public void removeTableModelListener(TableModelListener tml) {
            tableModelListenerList.remove(tml);
        }
    
    }
    

    PS: This sample comes partly from some other implementation, I just updated it to your scenario as described above. So it is quite possible that it contains some code glitzes. It is just provided to give you an idea on how a solution could look.

    0 讨论(0)
  • 2021-01-03 02:49

    Going off of Emil's answer, but to support older version (tested with Java 1.3).

    import javax.swing.*;
    import java.util.*;
    import javax.swing.table.*;
    
    public class HashMapToJtable {
     public static void main(String[] args) {
      final Map st = new TreeMap();
      st.put("1","one");
      st.put("2","two");
      st.put("3","three");
      JTable t=new JTable(toTableModel(st));
      JPanel p=new JPanel();
      p.add(t);
      JFrame f=new JFrame();
      f.add(p);
      f.setSize(200,200);
      f.setVisible(true);
     }
    
     public static TableModel toTableModel(Map map) {
         DefaultTableModel model = new DefaultTableModel (
       new Object[] { "Key", "Value" }, 0
      );
      for (Iterator it = map.entrySet().iterator(); it.hasNext();) {
       Map.Entry entry = (Map.Entry)it.next();
       model.addRow(new Object[] { entry.getKey(), entry.getValue() });
      }
      return model;
     }
    
    }
    
    0 讨论(0)
  • 2021-01-03 02:56
    public class HashMapToJtable {
    public static void main(String[] args) {
        final Map<String,String> st=new TreeMap<String, String>();
        st.put("1","one");
        st.put("2","two");
        st.put("3","three");
        JTable t=new JTable(toTableModel(st));
        JPanel p=new JPanel();
        p.add(t);
        JFrame f=new JFrame();
        f.add(p);
        f.setSize(200,200);
        f.setVisible(true);
    }
    public static TableModel toTableModel(Map<?,?> map) {
        DefaultTableModel model = new DefaultTableModel(
            new Object[] { "Key", "Value" }, 0
        );
        for (Map.Entry<?,?> entry : map.entrySet()) {
            model.addRow(new Object[] { entry.getKey(), entry.getValue() });
        }
        return model;
    }
    }
    

    This is a sample code for populating a Jtable from a map.For your purpose you will have to override the toString method in your Student and Staff classes.

    0 讨论(0)
  • 2021-01-03 03:07

    Why not create an object that implements an interface in the fashion that JTable desires (an Object array), and provides a bridge to your existing map of Students ? So you can keep your existing data structure that is obviously working for you, and you're simply providing an adaptor for the benefit of the view (the JTable).

    From the link:

    An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface. The adapter translates calls to its interface into calls to the original interface, and the amount of code necessary to do this is typically small. The adapter is also responsible for transforming data into appropriate forms.

    I would try not to change a working data structure to fit with a particular GUI component (what happens if at a later stage you want to display via HTML or similar) but adapt to each view as a requirement comes up.

    0 讨论(0)
  • 2021-01-03 03:07

    Your DataStorage is like the StudentRegistration is used in the sample code.

     // TIP: It can be handy to place the student in some order in the Map 
        //      (therefore using the sorted map).
        private SortedMap students = new TreeMap();  
    
        // QUESTION: Why not use argument name 'student'?
        public void addStudentMember(Student aAcc)
        {
            students.put(aAcc.getUser(),aAcc);
        }
        // Updated implementation
        public void addStudent(Student student)
        {
            students.put(student.getAccID(), student);
        }
    
     // QUESTION: Would a method name 'getNumberOfStudents' not be better?  
        public int getStudentRows()
    

    For me it is a little unclear why Student extends from Account. The account identification, is that an unique-id, through the hole system? Do staff (users) and student (users) all have that as unique identification? Where / who creates them? If not the system self, it can never be guranteed that they also enter correctly into your system. Even when checking on uniqueness within your system, helps. But who say not someone else (by accedent) used someone else his/her unique id? (How are the student and staff (accounts) created? If these id's are indeed unique, why not use those for placing the student into a SortedMap? If the sorting is not important. Why not just use a List of students?

    Is the name parameter unique (by which you place the student in the Map)?

    Programming is little more then learning a programming language. As once understanding the OO-language Java it is good to read some more general programming books. In your specific case I would say start with Domain Driven Design. And then continue with books like these Test Driven Development, Refactoring to Patterns and Design Patterns.

    0 讨论(0)
  • 2021-01-03 03:09

    You have several options available to you here. I would probably build my own TableModel and convert the HashMap into a List, but that would require that accountID was part of Student and I cannot tell if it is from your post. So probably easier to create a multi dimensional array. To do this you need to examine every object in your HashMap and to do this we would use a 'loop'.

    First create the array to hold your data:

    Object[][] tableData = new Object[students.keySet().size()][numberOfColumns];
    

    Replace numberOfColumns with the number of columns your table has.

    int index = 0;
    for (String key : students.keySet())
    {
        Student student = students.get(key);
        tableData[index][0] = student.getXXX
        tableData[index][1] = student.getYYY
        tableData[index][2] = student.getZZZ
        // and so forth
        index++;
    }
    

    So what we do here is create a loop that will examine every key in the students HashMap and with that key we retrieve the Student object and populate the array with the correct data.

    This is to answer your question, but I would recommend that you take a look at the TableModel interface and build one around your HashMap of Students. More manly :)

    0 讨论(0)
提交回复
热议问题