Prevent adding duplicate data into JTable in Java - java

How to prevent adding duplicate data into Jtable.
This is my code.
try {
URL url = new URL("http://localhost:8080/webservice/rest/bdetails/get");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
String json = "";
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
json += output;
}
conn.disconnect();
java.lang.reflect.Type listType = new TypeToken<ArrayList<BDetails>>() {
}.getType();
List<BDetails> bList = new Gson().fromJson(json, listType);
for( BDetails adr : bList)
{
DefaultTableModel model = (DefaultTableModel) pTable.getModel();
Vector<String> row = new Vector<String>();
row.add(detail.getUserName());
row.add(detail.getFirstName());
row.add(detail.getLastName());
row.add(detail.getAddress();
model.addRow( row );
}
} catch (IOException | RuntimeException ex) {
System.out.println(ex);
}
When I run this method It add data to the table. When I run again It add same data to the table. And again it do the same. How can I fix that? Can anybody help me? Thanks in advance. Below I have added the BDetails Class.
BDetails Class
public class BDetails
{
private String username;
private String firstName;
private String lastName;
private String address;
public BDetails() {
}
public BDetails(String username, String firstName, String lastName, String address) {
this.username = username;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}

You can try this,
java.lang.reflect.Type listType = new TypeToken<ArrayList<BDetails>>() {
}.getType();
List<BDetails> bList = new Gson().fromJson(json, listType);
DefaultTableModel model = (DefaultTableModel) pTable.getModel();
model.setRowCount(0);
for( BDetails adr : bList)
{
Vector<String> row = new Vector<String>();
row.add(detail.getUserName());
row.add(detail.getFirstName());
row.add(detail.getLastName());
row.add(detail.getAddress();
model.addRow( row );
}
model.setRowCount(0) will clear all the rows before inserting data. It worked for me.

First, I took BDetails and used Netbeans to add the equals and hashcode methods. This is important, as it provides away to assess if two instances of an object are the same
public class BDetails {
private String username;
private String firstName;
private String lastName;
private String address;
public BDetails() {
}
public BDetails(String username, String firstName, String lastName, String address) {
this.username = username;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Override
public int hashCode() {
int hash = 7;
hash = 13 * hash + Objects.hashCode(this.username);
hash = 13 * hash + Objects.hashCode(this.firstName);
hash = 13 * hash + Objects.hashCode(this.lastName);
hash = 13 * hash + Objects.hashCode(this.address);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final BDetails other = (BDetails) obj;
if (!Objects.equals(this.username, other.username)) {
return false;
}
if (!Objects.equals(this.firstName, other.firstName)) {
return false;
}
if (!Objects.equals(this.lastName, other.lastName)) {
return false;
}
if (!Objects.equals(this.address, other.address)) {
return false;
}
return true;
}
}
I then create a custom TableModel (I'm bias, but I don't have much love for DefaultTableModel and it makes the next step easier)
public class BDetailsTableModel extends AbstractTableModel {
private List<BDetails> rows;
private String[] columnNames = {"User name", "First name", "Last Name", "Address"};
public BDetailsTableModel(List<BDetails> rows) {
this.rows = rows;
}
#Override
public int getRowCount() {
return rows.size();
}
#Override
public String getColumnName(int column) {
return columnNames[column];
}
#Override
public int getColumnCount() {
return 4;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
BDetails details = rows.get(rowIndex);
switch (columnIndex) {
case 0:
return details.getUsername();
case 1:
return details.getFirstName();
case 2:
return details.getLastName();
case 3:
return details.getAddress();
}
return null;
}
}
And finally...
List<BDetails> bList = new Gson().fromJson(json, listType);
//for (BDetails adr : bList) {
// DefaultTableModel model = (DefaultTableModel) pTable.getModel();
// Vector<String> row = new Vector<String>();
// row.add(detail.getUserName());
// row.add(detail.getFirstName());
// row.add(detail.getLastName());
// row.add(detail.getAddress();
// model.addRow(row);
//}
Set<BDetails> unquie = new HashSet<>(bList);
List<BDetails> rows = new ArrayList<>(unquie);
BDetailsTableModel model = new BDetailsTableModel(rows);
pTable.setModel(model);
Okay, all this does is adds the bList to Set, this will remove all duplicates from the list for us (using the hashcode of the objects), add the results to a ArrayList (because it has a get method) and then supplies that to our BDetailsTableModel
Now, if you don't want to replace the TableModel each time, but instead, add the results it becomes a little more difficult, as you need to manage the possibility that the new set of data might contain duplicates of the old set.
You could add the following to BDetailsTableModel...
public void add(BDetails details) {
int rowCount = getRowCount();
if (rows.contains(details)) {
return;
}
rows.add(details);
fireTableRowsInserted(rowCount, rowCount);
}
public void addAll(List<BDetails> newRows) {
Set<BDetails> rows = new HashSet<>(newRows);
addAll(rows);
}
public void addAll(Set<BDetails> newRows) {
Set<BDetails> allRows = new HashSet<>(rows);
allRows.addAll(newRows);
rows = new ArrayList<>(allRows);
fireTableDataChanged();
}
and instead of creating a new instance of BDetailsTableModel, simply use the existing instance (from pTable) and use the above functionality to add new rows

Related

Why is FileReader not reading beyond the end of the first line?

I'm trying to read in data from a text file using FileReader. There are four lines of text. Each line has the same attribute types (first name, last name, dob, ssn, etc.). I am trying to split the data read in by the " " delimiter into one long array and then assign the values to a record ArrayList. My logic (if you can even call it that), is that by doing this I'd have one giant array of String data which I could then assign to each of the record's 7 fields - 0-6 for the first record, 7-13 for the second record, 14-20 for the third... But it looks like my while loop is stopping at the end of line one. I feel really stupid here, but I cannot figure out how to get this to work. And yes, I know, there is a lot that is bad form in my code, but I'm just trying to get a feel for the functionality. Any advice here would be most appreciated. Thank you!
The text file looks like this:
John Smith 1996.03.07 123-45-6789 Chickenpox BedRest aspirin
Joe Blow 1996.03.07 123-45-6888 Smallpox BedRest Whiskey
Julie Wilson 1996.03.07 123-45-6999 Insomnia Exercise HotPeppers
Wayne Blaine 1942.07.07 123-45-6777 Measles WaitToGetBetter CodLiverOil
Here's my main.
public static void main(String [] args) throws Exception {
String line = "";
BlockRecord record0 = null;
BlockRecord record1 = null;
BlockRecord record2 = null;
BlockRecord record3 = null;
try {
ArrayList<String> data = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("BlockInput0.txt"));
while((line = reader.readLine()) != null) {
System.out.println(line);
data.add(line);
}
record0 = new BlockRecord();
record1 = new BlockRecord();
record2 = new BlockRecord();
record3 = new BlockRecord();
record0.setBlockID(new String(UUID.randomUUID().toString()));
record1.setBlockID(new String(UUID.randomUUID().toString()));
record2.setBlockID(new String(UUID.randomUUID().toString()));
record3.setBlockID(new String(UUID.randomUUID().toString()));
//manually set until more functionality is in place
data = line.split(" ");
record0.setFirstName(data[0]);
record0.setLastName(data[1]);
record0.setDob(data[2]);
record0.setSsn(data[3]);
record0.setDiagnosis(data[4]);
record0.setTreatment(data[5]);
record0.setRx(data[6]);
record1.setFirstName(data[7]);
record1.setLastName(data[8]);
record1.setDob(data[9]);
record1.setSsn(data[10]);
record1.setDiagnosis(data[11]);
record1.setTreatment(data[12]);
record1.setRx(data[13]);
record2.setFirstName(data[14]);
record2.setLastName(data[15]);
record2.setDob(data[16]);
record2.setSsn(data[17]);
record2.setDiagnosis(data[18]);
record2.setTreatment(data[19]);
record2.setRx(data[20]);
record3.setFirstName(data[21]);
record3.setLastName(data[22]);
record3.setDob(data[23]);
record3.setSsn(data[24]);
record3.setDiagnosis(data[25]);
record3.setTreatment(data[26]);
record3.setRx(data[27]);
}
}catch(Exception e) {
e.printStackTrace();
}
}
Here's my BlockRecord class:
class BlockRecord{
String firstName;
String lastName;
String ssn;
String dob;
String diagnosis;
String treatment;
String rx;
String seed;
String winner;
String blockID;
String previousHash;
String verificationID = "0";
String uuid = UUID.randomUUID().toString();
String winningHash;
public static KeyPair keyPair;
public static int recordCount;
public String getWinningHash() {
return winningHash;
}
public void setWinningHash(String winningHash) {
this.winningHash = winningHash;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getDiagnosis() {
return diagnosis;
}
public void setDiagnosis(String diagnosis) {
this.diagnosis = diagnosis;
}
public String getTreatment() {
return treatment;
}
public void setTreatment(String treatment) {
this.treatment = treatment;
}
public String getRx() {
return rx;
}
public void setRx(String rx) {
this.rx = rx;
}
public String getSeed() {
return seed;
}
public void setSeed(String seed) {
this.seed = seed;
}
public String getWinner() {
return winner;
}
public void setWinner(String winner) {
this.winner = winner;
}
public String getBlockID() {
return blockID;
}
public void setBlockID(String blockID) {
this.blockID = blockID;
}
public String getPreviousHash() {
return previousHash;
}
public void setPreviousHash(String previousHash) {
this.previousHash = previousHash;
}
public String getVerificationID() {
return verificationID;
}
public void setVerificationID(String verificationID) {
this.verificationID = verificationID;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
You read all the lines and add each on them to the list data in the loop:
while((line = reader.readLine()) != null) {
System.out.println(line);
data.add(line);
}
But then, you only split line, which is the last read line.
data = line.split(" ");
Quick fix:
Merge all the lines into one. Then split it.
String mergedLines = "";
while((line = reader.readLine()) != null) {
System.out.println(line);
mergedLines = mergedLines + line;
}
This is really dirty and uneffective as the file already provides separated records.
Better solution:
Create a BlockRecordfor each line without merging them. Then store the record in a list.
ArrayList<BlockRecord> allRecords = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("BlockInput0.txt"));
while((line = reader.readLine()) != null) {
System.out.println(line);
data = line.split(" ");
BlockRecord record = new BlockRecord()
record.setFirstName(data[0]);
record.setLastName(data[1]);
record.setDob(data[2]);
record.setSsn(data[3]);
record.setDiagnosis(data[4]);
record.setTreatment(data[5]);
record.setRx(data[6]);
allRecords.add(record)
}
This way, you don't even have to know how many records to declare before reading

MongoDb - How to sort and search multiple field in a collection using java

I am trying to implement a method in which i create a Hashmap of key as string and value as object. Using this hashmap i need to search and sort the collection of data present in Mongo.
Below is id class of mongo db file:
public class Oid{
String $oid;
public String get$oid() {
return $oid;
}
public void set$oid(String $oid) {
this.$oid = $oid;
}
}
Below is pojo java file:
public class AppUser {
private String password;
private String email;
private Date created_at;
private Date update_at;
Oid _id;
public AppUser() {
super();
// TODO Auto-generated constructor stub
}
public AppUser(String password, String email, Date created_at, Date update_at) {
super();
this.password = password;
this.email = email;
this.created_at = created_at;
this.update_at = update_at;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCreated_at() {
return created_at;
}
public void setCreated_at(Date created_at) {
this.created_at = created_at;
}
public Date getUpdate_at() {
return update_at;
}
public void setUpdate_at(Date update_at) {
this.update_at = update_at;
}
public Oid get_id() {
return _id;
}
public void set_id(Oid _id) {
this._id = _id;
}
}
I am using gson to convert this pojo and while fetching its get converted back to java object.
public class AppUserDao {
public List < AppUser > findMulitple(HashMap < String, Object > map) {
List < AppUser > appUsers = new ArrayList < > ();
MongoDatabase db = getDB();
BasicDBObject query = new BasicDBObject(map.keySet().iterator().next(), map.get(map.keySet().toArray()[0]));
int i = 0;
for (String key: map.keySet()) {
if (i != 0) {
query.append(key, map.get(key));
}
i++;
}
FindIterable < Document > filter = db.getCollection("sampleCollection").find(query);
MongoCursor < Document > cursor = filter.iterator();
try {
String obj = cursor.next().toJson();
System.out.println(obj);
AppUser appUser = gson.fromJson(obj, AppUser.class);
appUsers.add(appUser);
} catch (JsonSyntaxException jse) {
jse.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
cursor.close();
}
return appUsers;
}
}
in which i send a hashmap of key and its properties for filtering purpose.
Below is the unit test class for testing:
public class TestAppUser {
public static void main(String args[]) {
HashMap < String, Object > map = new HashMap < > ();
map.put("email", "berry.sanford#yahoo.com");
map.put("password", "Quo Lux");
AppUserDao appUserDao = new AppUserDao();
List < AppUser > appUsers = appUserDao.findMulitple(map);
for (AppUser appUser: appUsers) {
System.out.println(appUser.get_id().get$oid());
}
}
}
In this test class i am expecting to get a list of two records. First record will contain the email value as "berry.sanford#yahoo.com" and second record whose password values is Quo Lux
I would build the query filters and sort orders like below.
List<Bson> filters = map.entrySet().stream().map(entry->Filters.eq(entry.getKey(), entry.getValue())).collect(Collectors.toList());
List<Bson> sorts = map.keySet().stream().map(Sorts::ascending).collect(Collectors.toList());
FindIterable<Document> filter = db.getCollection("sampleCollection").find(Filters.and(filters)).sort(Sorts.orderBy(sorts));
MongoCursor<Document> cursor = filter.iterator();

Scan some text in a document, replace certain words(these words should be variables) and save in a new document using Apache POI in Java

I have json file from which I parse json objects to java objects using Gson library. The next step is to create main class in which with the help of Apache POI prepared docx file is read, some changes were made in the text and new document with changes is created. The problem I faced is that the text which should be changed need to be variable(from json file). I mean that "name" and "testName" both should be variables or methods, so I can call them from text.contains. Can you show my mistake and the right way to do the task. Thanks in advance.
Here is my code `
public class main {
public static void gson() {
Gson gson = new Gson();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("jsonn.json"));
Result result = gson.fromJson(br, Result.class);
if (result != null) {
result.getName();
result.getLastname();
System.out.println(result.getName());
System.out.println(result.getLastname());
for (Phone p : result.getPhones()) {
p.getType();
p.getNum();
System.out.println(p.getType() + ": " + p.getNum());
// System.out.println(p.getType()+" : "+p.getNum());
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}}
public class Result {
#SerializedName("name")
#Expose
private String name;
#SerializedName("lastname")
#Expose
private String lastname;
#SerializedName("phones")
#Expose
private List<Phone> phones = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public List<Phone> getPhones() {
return phones;
}
public void setPhones(List<Phone> phones) {
this.phones = phones;
}}
public class Phone {
#SerializedName("name")
#Expose
private String name;
#SerializedName("lastName")
#Expose
private String lastName;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#SerializedName("num")
#Expose
private String num;
#SerializedName("type")
#Expose
private String type;
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}}
public class Read {
public static void main(String[] args) throws InvalidFormatException,
IOException {
main.gson();
XWPFDocument doc = new XWPFDocument(OPCPackage.open("Шаблон.docx"));
Result res = new Result();
String replaceName = res.getName();
for (XWPFParagraph p : doc.getParagraphs()) {
List<XWPFRun> runs = p.getRuns();
if (runs != null) {
for (XWPFRun r : runs) {
String text = r.getText(0);
if (text != null && text.contains("name")) {
text = text.replace("name", "Alex");
r.setText(text, 0);
}
}
}
}
for (XWPFTable tbl : doc.getTables()) {
for (XWPFTableRow row : tbl.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
for (XWPFParagraph p : cell.getParagraphs()) {
for (XWPFRun r : p.getRuns()) {
String text = r.getText(0);
if (text != null && text.contains("name")) {
text = text.replace("name", "Alex");
r.setText(text, 0);
}
}
}
}
}
}
doc.write(new FileOutputStream("Пример.docx"));
}}
`
Here is json file:
{
"name":"testName",
"lastname":"testLastName",
"phones":[
{
"num":"9000000",
"type":"mobile"
},
{
"num":"1000000",
"type":"home"
} ]}

How do I return an object when I only have access to one field of it?

Sorry if this doesn't make sense, I can't think of a better way to phrase it. Hopefully my code illustrates my problem better.
So in this method I want to return a Myuser object. A Myuser object has about 8 string fields, one of which is userId.
As you can see, when this method is called, a string is passed in. If this string has the same value as the userId field in the Myuser object, then I want it to return the full Myuser object. Otherwise it returns null.
public Myuser getRecord(String userId) {
Connection cnnct = null;
PreparedStatement pStmnt = null;
Myuser myusr = null;
boolean result = false;
try {
cnnct = getConnection();
String preQueryStatement = "SELECT * FROM MYUSER WHERE USERID = ?";
pStmnt = cnnct.prepareStatement(preQueryStatement);
pStmnt.setString(1, userId);
ResultSet rslt = pStmnt.executeQuery();
result = rslt.next();
if (result) {
//return myusr in its entirety
}
} catch (SQLException ex) {
while (ex != null) {
ex.printStackTrace();
ex = ex.getNextException();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (pStmnt != null) {
try {
pStmnt.close();
} catch (SQLException e) {
}
}
if (cnnct != null) {
try {
cnnct.close();
} catch (SQLException sqlEx) {
}
}
}
return myusr;
}
Edit: I thought for the heck of it I would post the Myuser class as well.
public class Myuser {
private String userid;
private String name;
private String password;
private String email;
private String phone;
private String address;
private String secQn;
private String secAns;
public Myuser(String userid, String name, String password, String email, String phone, String address, String secQn, String secAns) {
this.userid = userid;
this.name = name;
this.password = password;
this.email = email;
this.phone = phone;
this.address = address;
this.secQn = secQn;
this.secAns = secAns;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSecQn() {
return secQn;
}
public void setSecQn(String secQn) {
this.secQn = secQn;
}
public String getSecAns() {
return secAns;
}
public void setSecAns(String secAns) {
this.secAns = secAns;
}
}
You can easily use result.getXXX(field_name):
if (rslt.next()) {
myusr = new Myuser(result.getString("userid"), result.getString("name"),
result.getString("password"), result.getString("phone"),
...);
}
Note don't need to use result = rslt.next(); before if(result), you have to use directly
if (rslt.next()) {
...
}

Java retrieving object from array

I'm having an issue fetching an object from an array of said Object. My code is below. I'm basically trying to build a table and fill in the columns with the data from each object. However currently the table is just showing the object and not the data. See picture:
Table:
public void buildTable(JPanel panel) {
File file = new File("C:\\Users\\user\\Desktop\\test.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
lineArray = new ArrayList<Person[]>();
while((line = br.readLine()) != null) {
String[] temp = line.split("\\t");
Person p = new Person(temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[7], temp[8]);
lineArray.add(new Person[]{p});
}
br.close();
} catch (FileNotFoundException e) { e.printStackTrace();}
catch (IOException e) { e.printStackTrace(); }
List<String> columns = new ArrayList<String>();
final List<Person[]> values = new ArrayList<Person[]>();
columns.add("First Name");
columns.add("Last Name");
columns.add("Address");
columns.add("Address 2");
columns.add("City");
columns.add("State");
columns.add("Zip Code");
columns.add("Phone");
columns.add("Email");
for (int i = 0; i < lineArray.size(); i++) {
values.add(lineArray.get(i)); //this is the line where I'm guessing the main problem is
}
TableModel tableModel = new DefaultTableModel(values.toArray(new Object[][] {}), columns.toArray());
final JTable table = new JTable(tableModel);
JScrollPane tableContainer = new JScrollPane(table);
tableContainer.setBounds(10, 36, 833, 219);
panel.add(tableContainer);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int selectedRow = table.convertRowIndexToModel(table.getSelectedRow());
contactName.setText((String) table.getValueAt(selectedRow, 0) + " " + table.getValueAt(selectedRow, 1));
contactAddress.setText((String) table.getValueAt(selectedRow, 2));
}
});
}
Object Class:
public class Person {
public String firstName;
public String lastName;
public String address;
public String address2;
public String city;
public String state;
public String zip;
public String phone;
public String email;
public Person(String firstName, String lastName, String address, String address2, String city, String state, String zip, String phone, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.address2 = address2;
this.city = city;
this.state = state;
this.zip = zip;
this.phone = phone;
this.email = email;
}
}
To solve your problem, you need only ONE ArrayList of Person (and not of array of Person), and you don't need the value ArrayList.
What you need instead is some method that create an array of arrays representing a table containing your data, in fact an array of arrays of Strings. The problem is the 'columns' of the table are actually the fields of the Person class. I'm not sure if my solution (below) is the best, probably you can solve this problem also dealing with the reflection.
Anyway, this works (I tried to modify least as possible your code or to simplify it):
public void buildTable(JPanel panel) throws IOException {
File file = new File("C:\\Users\\user\\Desktop\\test.txt");
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
lineArray = new ArrayList<Person>();
while ((line = br.readLine()) != null) {
String[] temp = line.split(",");
Person p = new Person(temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[7], temp[8]);
lineArray.add(p);
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
List<String> columns = new ArrayList<String>();
columns.add("First Name");
columns.add("Last Name");
columns.add("Address");
columns.add("Address 2");
columns.add("City");
columns.add("State");
columns.add("Zip Code");
columns.add("Phone");
columns.add("Email");
TableModel tableModel = new DefaultTableModel(Person.toStringsMatrix(lineArray), columns.toArray());
final JTable table = new JTable(tableModel);
JScrollPane tableContainer = new JScrollPane(table);
tableContainer.setBounds(10, 36, 833, 219);
panel.add(tableContainer);
}
And the Person class:
class Person {
public String firstName;
public String lastName;
public String address;
public String address2;
public String city;
public String state;
public String zip;
public String phone;
public String email;
public Person(String firstName, String lastName, String address, String address2, String city, String state, String zip, String phone, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.address2 = address2;
this.city = city;
this.state = state;
this.zip = zip;
this.phone = phone;
this.email = email;
}
public String[] toStrings() {
return new String[]{firstName, lastName, address, address2, city, state, zip, phone, email};
}
public static String[][] toStringsMatrix(ArrayList<Person> personList) {
int rows = personList.size();
String[] first = personList.get(0).toStrings();
int columns = first.length;
String[][] table = new String[rows][columns];
table[0] = first;
for (int k = 1; k < rows; k++) {
table[k] = personList.get(k).toStrings();
}
return table;
}
}
I hope this will help you.
Try adding a array of strings to your lineArray instead of Person objects.
lineArray.add(new String[]{temp[0], temp[1], temp[2], temp[3], temp[4], temp[5], temp[6], temp[7], temp[8]});

Categories

Resources