Populating jTable using List - java

I have a list of data which I got from my Json file using Json Jackson, how can I populate jTable from this list?
[{"id":1,"name":"Bambola","description":"Opis...","contact_number":"022\/349-499","email":"","address":"Svetosavksa 23","geo_latitude":"44.96868000000000","geo_longitude":"20.28140000000000","created_at":"2013-06-24 14:15:08","updated_at":"2013-06-24 14:15:08","deleted_at":null,"publication_starts":"1991-05-24 01:00:00","publication_ends":"1991-05-24 01:00:00"},{"id":2,"name":"Master","description":"Opis...","contact_number":"022\/349-123","email":"","address":"Svetosavksa 24","geo_latitude":"44.96653000000000","geo_longitude":"20.28170000000000","created_at":"2013-06-24 14:15:08","updated_at":"2013-06-24 14:15:08","deleted_at":null,"publication_starts":"0000-00-00 00:00:00","publication_ends":"0000-00-00 00:00:00"},{"id":3,"name":"Tritel","description":"Opis...","contact_number":"022\/321-499","email":"","address":"Svetosavksa 25","geo_latitude":"44.96654000000000","geo_longitude":"20.28170000000000","created_at":"2013-06-24 14:15:08","updated_at":"2013-06-24 14:15:08","deleted_at":null,"publication_starts":"0000-00-00 00:00:00","publication_ends":"0000-00-00 00:00:00"}]
Using the Json Jackson parser I have populated the List with this data.
List<Advertisement> advertisements = mapper.readValue(url, new TypeReference<List<Advertisement>>(){});
Now I want to populate the jTable, I have used the NetBeans GUI builder to create frame and the table. The table name is advertisementList_JT. So far what I have tried is this snippet of code found in a simillar question here on the site.
DefaultTableModel model = new DefaultTableModel();
for (Advertisement adv : advertisements) {
Object[] o = new Object[3];
o[0] = adv.getName();
o[1] = adv.getPublication_starts();
o[2] = adv.getPublication_ends();
model.addRow(o);
}
advertisementList_JT.setModel(model);
With this snippet the table when I start the application just goes gray and nothing happens, looked thru the debugger and no errors either.

I think it happens because you didn't supply the table header. See if this works:
Object[] columnNames = {"Name", "Starts", "Ends"};
DefaultTableModel model = new DefaultTableModel(new Object[0][0], columnNames);
for (Advertisement adv : advertisements) {
Object[] o = new Object[3];
o[0] = adv.getName();
o[1] = adv.getPublication_starts();
o[2] = adv.getPublication_ends();
model.addRow(o);
}
advertisementList_JT.setModel(model);
Another possibility is that advertisements List is empty;

Related

Send 2D Array to JTable

I am using swing and java in Eclipse to send data to JTable from a 2D Array
String [][] row = {{"iphone"},{"34567"}};
I have a 2D array. I am wanting to display it in JTable using eclipse.
The JTable will have to header like "Phone" and "Price" and the Jtable gets filled by the click of a button.
String[] columns = {"Phone","Price"};
Can some please help me to get it displayed in JTable
DefaultTableModel model = new DefaultTableModel(new Object[]{"Column1", "Column2"})
JTable table = new JTable(model);
To add a row:
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addRow(new Object[]{"iPhone", "73567",});
Placing the above code inside the action performed of the button.
public void actionPerformed(ActionEvent e)
{
DefaultTableModel model = (DefaultTableModel)table.getModel();
model.addRow(new Object[]{"iphone", "73576"});
}

How do I dynamically display contents in tables in Java

I need to display some content in a tabular form dynamically in Java. The content includes data that is fetched from an API in JSON format. At the end of each row I need to display a checkbox as well. The number of rows is dynamic and the columns are fixed. How do I do this?
The table will have the following columns:
Index
Username
Upload date
Percentage
Matched results
[Checkbox]
Finally found the answer to this problem. We can dynamically create a table using the class DefaultTableModel and the Java swing class JTable.
model = new DefaultTableModel();
Set the columns
model.setColumnIdentifiers(new Object[]{"Index","User","Reg no.","Match"});
jTable1.setModel(model);
jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
jTable1.setFillsViewportHeight(true);
jScrollPane1.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
jScrollPane1.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
Add the rows from the JSON response
for(int i=0;i< jsonArr.size();i++)
{
str = jsonArr.get(i).toString();
jsonObj = (JSONObject)parser.parse(str);
String sub = jsonObj.get("subid").toString();
String uname = jsonObj.get("username").toString();
String regno = jsonObj.get("regno").toString();
String percent = jsonObj.get("percent").toString();
model.addRow(new Object[]{sub,uname,regno,percent});
}

Reading a Access file using Jackcess and creating a Jtable with the data

I'm currently working on a Java application that reads an Access file and builds a Jtable model using the data that's collected. I've previously done the same with an Excel file but when I tried with Jackcess it was slightly diffrent and I've ran into some questionmarks.
My work so far:
public class AccessModel{
public DefaultTableModel getAccessModel() throws IOException {
Database db = DatabaseBuilder.open(new File("MyFile.accdb"));
Vector<String> columnNames = new Vector<String>();
Vector<String> vector = new Vector<String>();
Vector<Vector<String>> data = new Vector<Vector<String>>();
StringBuilder output = new StringBuilder();
Table table = db.getTable("Table1");
for (Column column : table.getColumns()) { // get the table column names
output.append(column.getName());
output.append("\n");
columnNames.add(column.getName());
}
for (Column column : table.getColumns()) { // get the column rows and values
vector.add(column.getRowValue(table.getNextRow()).toString());
}
data.add(vector);
// return the model to Gui
DefaultTableModel accessModel = new DefaultTableModel(data, columnNames);
return accessModel;
}
}
As you can see this method will only iterate trough the first row, then exit the loop. I'm either blind to an abvious solution due to 12 hours of straight work, or I'm doing something terribly wrong.
I've stumbled across some half-good solutions where an Iterator is used, but I cannot get the hang of it. Any suggestions on this? Or should I stay on lane with my current line of thought?
JTable (value for view is stored in XxxTableModel, in your case is used DefaultTableModel) is row bases Object,
TableColumn (value is stored in TableColumnModel) to divide row(s) to the columns
you would need to create two Objects,
Vector<String> columnNames (is only one row) for columns identifiers from Table table = db.getTable("Table1");
loop inside Table table = db.getTable("Table1"); to fill two dimensional Vector<Vector<Object>> data = new Vector<Vector<Object>>(); by using Vector<Object> vector = new Vector<Object>();, notice 1st. code line insode loop must be vector = new Vector<Object>();, you have to create a new Vector otherwise you'll add the same rown_times, last code line should be data.add(vector)
.
everything (I'm still think so) is described in Oracle tutorial How to use Tables

Insert row on jtable with DefaulTableModel on different methods

i want to add or insert column from different methods into one table.. cant explain it clearly but i show my codes to you to understand..for example.
(....)
DefaultTableModel dtm = new DefaultTableModel();
JTable table = new JTable();
Constructor(){
table.setModel(dtm);
(.....)
}
public void methodOne(){
String id = num.getText();
rs = stat.executeQuery("SELECT * FROM payments;");
Vector<String> header = new Vector<String>();
header.add("PAYMENT");
header.add("AMOUNT");
header.add("MODIFIER");
header.add("DATE MODIFIED");
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while(rs.next()) {
Vector<Object> row = new Vector<Object>();
row.add(rs.getString("description"));
row.add(rs.getString("amount"));
row.add(rs.getString("remarks"));
row.add(rs.getString("date"));
data.add(row);
} // loop
dtm.setDataVector(data , header);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(0,0,490,250);
panel.add(scrollPane);
validate();
}
public void methodTwo(){
(.....)
rs = stat.executeQuery("SELECT * FROM record where idNum ='"+id+"';");
while(rs.next()){
Vector<Object> row = new Vector<Object>();
row.add(rs.getString("description"));
row.add(rs.getString("amount"));
row.add(rs.getString("remarks"));
row.add(rs.getString("date"));
data.add(row);
} // while
}
those value inside row are the value i want to add on my table, i dont have any idea on how to id.. i want it to be like this:
first when you run the java it will autoumatically create a table
http://i1023.photobucket.com/albums/af355/guiacustodio/javaaaaaaaaaaaaaaaaaaaaaaa_zpse9a22225.jpg
i have a button and textfield i enter number on the textfield i.e
[PAY BUTTON] TextField:[__100]
i clicked the button and this is what will happen:
http://i1023.photobucket.com/albums/af355/guiacustodio/javaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_zps43879eab.jpg
First of all, the data Vector you are using is defined inside methodOne so the same data is not accesible via methodTwo.
Secondly it is not because there is data being added to data in a tablemodel that the table will refresh, you have to call one of the methods that trigger an refresh event in the gui, normally one calls the method fireTableChanged on the tablemodel after you added data.
Thridly: there is an interesting library called GlazedLists that handles a lot of these things automatically !

Populate a jTable from an ArrayList

I'm trying to populate a JTable from an ArrayList, The ArrayList is filled with data from my database.
this is the code I tried :
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(new String[]{"Numéro d'ordre", "Article", "Quantité", "Remarque"});
for (gestionstock.LigneBonInterne o : listLigneBonInterne) {
model.addRow(new String[]{o.getNumOrder().toString(), o.getdesgArt(), o.getQte().toString(), o.getRemarque()});
System.out.println(o.toString());
}
jTable1.setModel(model);
But I get this error message :
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at magasinier.BonInterneDetails.(BonInterneDetails.java:63)
the ligne 63 is : jTable1.setModel(model);
I did a test to see if the ArrayList is filled, and I found that the ArrayList is filled with records which means that there is no problem with filling the ArrayList
How can I solve this problem ?
EDIT :
I tried to create the JTable using code and assign it to ScrollPane :
JTable jTable1 = new JTable(model);
jTable1.setModel(model);
jScrollPane1.setViewportView(jTable1);
But I still get the same error this time is the line : jScrollPane1.setViewportView(jTable1);
Initialize the JTable jTable1 prior to setting the TableModel
jTable1 = new JTable(model);
jTable1.setModel(model);
In Netbeans palette you can specify some custom post-initialization code or use a custom constructor.

Categories