How to use hashMap with JTable

I have a hashMap that I would like its data to be viewed in JTable, so that I would not be able to get the number of hashMap columns and rows and the displayed data. I have a hashmap that accepts an account identifier as a key and a student object in which each student has their own data, such as name, identifier, age, etc., although referring to JTable documents, he says that I need ints for row and column and multidimensional array of type Object. How should I do it? can i change myhMap in a multidimensional array?

- To edit, I edited my question so that it could be more clear, I'm pretty new to Java. I really don’t understand what some of you posted, especially since the work that I do is very OO related and captures OO Concepts - my biggest problem,

/ I have a dataStorage class, the registered user is added to the HashMap with the key input of his username, which is getUser. /

import java.util.*;

public class DataStorage 
{
    HashMap<String, Student> students = new HashMap<String, Student>();  
    HashMap<String, Staff> staffMembers = new HashMap<String, Staff>();  
    //Default constructor
    public DataStorage(){
    }

    public void addStaffMember(Staff aAcc) 
    {
     staffMembers.put(aAcc.getUser(),aAcc);
    }

    public void addStudentMember(Student aAcc)
    {
     students.put(aAcc.getUser(),aAcc);
    }

   public Staff getStaffMember(String user)
   {
   return   staffMembers.get(user);
   }

   public Student getStudent(String user)
   {
    return students.get(user);
   }

   public int getStudentRows()
   {
        return students.size();
   }


}

/ **** This is a class of students that expands the score *** /

public class Student extends Account {

    private String studentNRIC;
    private String diploma;
    private String gender;
    private double level;
    private int credits;
    private int age;
    private boolean partTime;
    private boolean havePc;
    private boolean haveChild;

    public Student(String n, String nr, String id, String dep, String user, String pass)
    {
        super(n, dep, user, pass, id);
        studentNRIC = nr;
    }

    public void setPartTime(boolean state)
    {
        if(state == true)
        {
            partTime = true;
        }
        else
        {
            partTime = false;
        }
    }

    public boolean getPartTime()
    {
        return partTime;
    }

    public void setHavePc(boolean state)
    {
        if(state == true)
        {
            havePc = true;
        }
        else
        {
            havePc = false;
        }
    }

    public boolean getHavePc()
    {
        return havePc;
    }

    public void setHaveChild(boolean state)
    {
        if(state == true)
        {
            haveChild = true;
        }
        else
        {
            haveChild = false;
        }
    }

    public boolean getHaveChild()
    {
        return haveChild;
    }
    public void setDiploma(String dip)
    {
        diploma = dip;
    }

    public String getDiploma()
    {
        return diploma;
    }

    public void setCredits(String cre)
    {
        credits = Integer.parseInt(cre);
    }

    public int getCredits()
    {
        return credits;
    }

    public void setGender(String g)
    {
        gender = g;
    }

    public String getGender()
    {
        return gender;
    }

    public void setAge(String a)
    {
        age = Integer.parseInt(a);
    }

    public int getAge()
    {
        return age;
    }
    public void setLevel(String lvl)
    {
        level = Double.parseDouble(lvl);
    }

    public double getLevel()
    {
        return level;
    }
    public void setStudentNRIC(String nr)
    {
        studentNRIC = nr;
    }

    public String getStudentNRIC()
    {
        return studentNRIC;
    }

}

/ **** This is a superclass of class *** /

public class Account {

    private String name;
    private String department;
    private String username;
    private String password;
    private String accountID;
    public Account()
    {
    }   
    public Account(String nm,String dep,String user,String pass, String accID) 
    {
        name = nm;
        department = dep;
        username = user;
        password = pass;
        accountID = accID;

    }

    public void setName(String nm)
    {
        name = nm;
    }

    public String getName()
    {
        return name;
    }

    public void setDep(String d)
    {
        department = d;
    }

    public String getDep()
    {
        return department;
    }

    public void setUser(String u)
    {
        username = u;
    }
    public String getUser()
    {
        return username;
    }

    public void setPass(String p)
    {
        password = p;
    }

    public String getPass()
    {
        return password;
    }

    public void setAccID(String a)
    {
        accountID = a;
    }

    public String getAccID()
    {
        return accountID;
    }
}
+5
source share
6 answers

. , , TableModel HashMap , , accountID Student, , . , , . HashMap, "".

:

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

numberOfColumns .

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++;
}

, , HashMap, Student .

, TableModel HashMap . :)

+7
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;
}
}

Jtable . toString Student .

+6

, , JTable ( Object), ? , , , , , ( JTable).

:

, - , . , , . .

GUI ( , HTML ), .

+3

- TableModel (aka SortedMap). TableModel , Swing JTable . TableModel .

JTable :

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

, SortedMap<String, Student> , StudentRegistration, SortedMap<String, Student>.

/**
 * 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: , , . , . , .

+2

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

}
+2

DataStorage StudentRegistration, .

 // 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()

, Student Account. - ? () () ? / ? , , . . , - () - ? ( ()? , SortedMap? . ?

Is the name parameter unique (by which you place the student on the map)?

Programming is a bit more than learning a programming language. Once you understand the OO language, it’s good to read some more general programming books. In your particular case, I would say we start with Domain Driven Design . And then continue with books such as Test Driven Development , Refactoring for Templates, and Design Templates .

0
source

All Articles