Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use hashMap with JTable

Tags:

java

swing

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 displayed.i have a hashmap which takes a accountID as the key and a object of students in which each students have their data like name,id, age, etc.however referring to the JTable docs, it says i would need ints for the row and column and a multidimension array of type Object. how can i do it? can i change my hashMap into a multidimenion array?

--Edit i have edited my question so it could be more clear , i am fairly new to Java i do not really get what some of you have posted, especially since the work i am doing is quite related to OO and grasping OO concepts is my biggest challenge,

/I have a dataStorage class, the registered user is added to the HashMap with a 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 student class which extends Account***/

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 the Account superclass***/

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;
    }
}
like image 465
sutoL Avatar asked Feb 13 '10 11:02

sutoL


4 Answers

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 :)

like image 157
willcodejavaforfood Avatar answered Oct 13 '22 10:10

willcodejavaforfood


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.

like image 24
Emil Avatar answered Oct 13 '22 10:10

Emil


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.

like image 41
Brian Agnew Avatar answered Oct 13 '22 10:10

Brian Agnew


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

}
like image 27
Pyrite Avatar answered Oct 13 '22 11:10

Pyrite