Implementing ArrayLists to Table models - java

Hi I have an arraylist of a class I created called Pets which has the variables below
private String name;
private String species;
private int age;
I wanted to display this arraylist into a jTable and I did that succesfully by using defaultTableModel and calling setModel().
However I needed to add a sorting and filtering function for the Jtable. I took a look at the java tutorials were they were creating a subclass of AbstractTableModel in order to sort and filter. However they were using arrays to store the data. So I tried modifying the code to use an arraylist isntead but Im stuck with this method
public Object getValueAt(int row, int col) {
return data[row][col];
}
How do I get all the values from one object from th arraylist?
Any help will be greatly appreciated. Thanks in advance.

Does your ArrayList hold a row that is it's own type of object? If so, and if your ArrayList is a generic ArrayList<RowItem> then you could do something like:
#Override
public Object getValueAt(int row, int col) {
if (row > getRowCount()) {
// throw an exception
}
RowItem rowItem = rowItemList.get(row);
switch (col) {
case 0:
return rowItem.getName();
case 1:
return rowItem.getLastSpecies();
case 2:
return rowItem.getAge();
}
return null; // or throw an exception
}

You can try this:
public Object getValueAt(int row, int col) {
switch(col) {
case 0:
return ((Pets)data.get(row)).getName();
case 1:
return ((Pets)data.get(row)).getSpecies();
case 2:
return ((Pets)data.get(row)).getAge();
}
return null;
}

Related

How to make columns editable in special abstract model JTable

Hey guys i doing my assignment and now i have the problem with non editable cells, actually it became editable, but the result of editing didn't set at arraylist, I tried many solution from internet, but it doesn't work.
So my work like registration system which get information about guest, and then stored it into csv file. In additional function the program must let display, update, delete and searching function.
I finished all, without update,delete and searching. Can you please looking my code and help me or give the advice, link or something useful.
this is my abstract model:
public class ddispmodel extends AbstractTableModel {
private final String[] columnNames = { "FirstName", "SecondName", "Date of
birth", "Gender", "Email", "Address", "Number", "Attending","ID" };
private ArrayList<String[]> Data = new ArrayList<String[]>();
private boolean editable;
public void AddCSVData(ArrayList<String[]> DataIn) {
this.Data = DataIn;
this.fireTableDataChanged();
}
#Override
public int getColumnCount() {
return columnNames.length;// length;
}
#Override
public int getRowCount() {
return Data.size();
}
#Override
public String getColumnName(int col) {
return columnNames[col];
}
#Override
public Object getValueAt(int row, int col) {
return Data.get(row)[col];
}
public boolean isCellEditable(int row, int col) {
setValueAt(Data, row, col);
this.fireTableCellUpdated(row, col);
return true;
}
}
This is part of my main class
It is action Listener of menu item witch activate displaying function
(I didn't copy all class, because it nearly 1000 lines, but if it necessary, i can submit all code )
dlog.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent e){
CSVFileDomestic Rd = new CSVFileDomestic();
ddispmodel ddispm = new ddispmodel();
ddisp.setModel(ddispm);
File DataFile = new File("D:\\cdne4\\WorkPlace\\Domestic.csv");
ArrayList<String[]> Rs2 = Rd.ReadCSVfile(DataFile);
ddispm.AddCSVData(Rs2);
System.out.println("Rows: " + ddispm.getRowCount());
System.out.println("Cols: " + ddispm.getColumnCount());
cl.show(cp, "dispDomPanel");
}
});
and File class which convert date from csv to arraylist
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
public class CSVFileDomestic {
private final ArrayList<String[]> Rs = new ArrayList<String[]>();
private String[] OneRow;
public ArrayList<String[]> ReadCSVfile(File DataFile) {
try {
BufferedReader brd = new BufferedReader(new
FileReader(DataFile));
while (brd.ready()) {
String st = brd.readLine();
OneRow = st.split(",");
Rs.add(OneRow);
System.out.println(Arrays.toString(OneRow));
}
}
catch (Exception e) {
String errmsg = e.getMessage();
System.out.println("File not found:" + errmsg);
}
return Rs;
I am new at Java and this is my first program , please can you explain more easily
but the result of editing didn't set at arraylist,
You need to override the setValueAt(...) method of the TableModel to save the data.
It would be something like:
String[] row = data.get(row);
row[column] = value;
this.fireTableCellUpdated(row, col);
Also, the isCellEditable(...) method should NOT do any processing. It simply returns true/false for the given column. If you want all columns editable then it should just be:
public boolean isCellEditable(int row, int col) {
//setValueAt(Data, row, col);
//this.fireTableCellUpdated(row, col);
return true;
}
I finish this)) and go to do others options.
camickr thank you for help, you give me the way, which bring me to answer))
I spend nearly 6 hours for trying to do it and finally I got it.
If someone interesting, answer is
public boolean isCellEditable(int row, int col) {
return true;
}
#Override
public void setValueAt(Object aValue, int row, int col){
Data.get(row)[col]= (String) aValue;
fireTableCellUpdated(row,col);
so I just make new method setValueAT which said me camickr.
than I went to Oracle site and read about it, and after try it to do, but
it doesn't, because aValue can't be converted from object to String, and finally I initiate aValue as a String, so now it works.However it is not all, it only change arraylist. Needs new method to convert arraylist to csv file. I am working about it now, maybe after I will show it. Sorry for my theory, I am new at java, just learn how it works))

Why we extends AbstractTabelModel when set values into JTabel?

Im developing a app for ordeing system and i have to set data into JTabels.
And this code is successfully working.I wanted to know what the importance of and whats happen in this class?
Why we need to import AbstractTabelModel.class?
OrderTabelModel Class:-
public class OrderTableModel extends AbstractTableModel{
protected static final String[] COLUMN_NAMES={"Item","Qty","Amount"};
private List<Order> rows;
public OrderTableModel(List<Order> rows){
this.rows = new ArrayList<>(rows);
}
#Override
public int getRowCount() {
return rows.size();
}
#Override
public int getColumnCount() {
return COLUMN_NAMES.length;
}
#Override
public String getColumnName(int column) {
return COLUMN_NAMES[column];
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object value = null;
Order row = rows.get(rowIndex);
switch (columnIndex) {
case 0:
value = row.getItem();
break;
case 1:
value = row.getQty();
break;
case 2:
value = row.getAmount();
break;
}
return value;
}
}
this is other class
private void tblOrderListMouseClicked(java.awt.event.MouseEvent evt) {
int raw = tblOrderList.getSelectedRow();
Order or;
String item;
Double qty,amount,total;
ArrayList<Order> arrOrder = new ArrayList<Order>();
String selectedRaw = tblOrderList.getModel().getValueAt(raw, 0).toString();
System.out.println("order id : "+selectedRaw);
String sql = "select item,qty,amount from orderdetails where orderid='"+selectedRaw+"'";
con = new DBconnector().connect();
try {
Statement ps =con.createStatement();
ResultSet rs2 = ps.executeQuery(sql);
while(rs2.next()){
or = new Order();
or.setItem(rs2.getString("item"));
System.out.println("Item :" +rs2.getString("item"));
or.setQty(rs2.getDouble("qty"));
or.setAmount(rs2.getDouble("amount"));
arrOrder.add(or);
}
rs2.close();
ps.close();
OrderTableModel tblModel = new OrderTableModel(arrOrder);
tblOrderItems.setModel(tblModel);
} catch (Exception e) {
e.printStackTrace();
}
}
Can some one explain me the process of this please?
It is not always mandatory to extend the AbstractTableModel. You can simply extend the DefaultTableModel and only override the getValueAt() method if you have to.
But most of the time for simple usages it is not even needed to override the getValueAt() method either.
By using the DefaultTableModel, you have a limitation for the converting you data (imported from DB) to an object[][] or Vector types which may be a little boring.
But you asked what is the importance of using AbstractTabelModel?
In this case I can say when JTable is started to being rendered, it needs to determine the number of rows and number of the columns and also it needs to know which data should be renedered in each cell and so on. Based on this, JTable ask for this Information from the underlying TableModel. So it is needed for your TableModel(any child or implementation of TableModel) to have those methods which are used by JTable to retrieve the needed information.
Hope this would be helpful.
Good Luck.

AbstractTableModel won't update JTable

i'm trying to make my JTable show changes made to my TableModel extending AbstractTableModel. I made a Heap to insert all the documents and then I apply a heapSort on my heap array, so this ordered array should be my TableModel data. It looks like this:
public class ModeloTabla extends AbstractTableModel {
private Heap heap;
private Nodo[] datos;
#Override
public int getRowCount() {
return heap.getNumNodos();
}
#Override
public int getColumnCount() {
return 4;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
if ( !heap.empty() ) {
datos = heap.heapSort();
}
Documento doc = datos[rowIndex].getDocumento();
switch ( columnIndex ) {
case 0:
return doc.getNombre();
case 1:
return doc.getHojas();
case 2:
return doc.getPrioridad();
default:
return null;
}
}
}
Inside the getValueAt method when I call heap.heapSort() the heap internal array is destroyed and it returns a Nodo[] with the ordered nodes. So when datos has an ordered array with nodes, my JTable won't show the data. Now, if I don't execute the heap.heapSort() and instead just call for the unordered array from the heap, my JTable shows everything.
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
datos = heap.getDatos();
Documento doc = datos[rowIndex].getDocumento();
... //This works but datos is unordered
}
}
I've tried replacing the Heap unordered array with the ordered one inside heapSort() and returning it using getDatos() but then the JTable again won't show up, also I've checked for the returning array from heapSort() and it's working well, the data is the same as the one from getDatos() but ordered. Any help with this would be very appreciated, thanks.
In the getValueAt() method you are retrieving the data from the datos object.
Documento doc = datos[rowIndex].getDocumento();
So the row count should be based on the number of rows in the datos object.
public int getRowCount() {
//return heap.getNumNodos();
return datos.length;
}
The getValueAt() method should NOT be sorting the data. The data in the model should already be sorted. Either sort it externally or sort it when you create the model. That is the getValueAt() method should not be changing the structure of the data. Also every time you change the data you would need to resort.

How to update JTable using values from an array in java

Hi I converted my arraylist into an array so I can use it to display its elements in a JTable but nothing is displaying. It is giving me an error (error is explained in code comments). I just want to have one column only which displays values from this array. Can someone guide me in the correct direction? Thanks
Here is my code:
private static class EnvDataModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private static ArrayList<Integer> list = new ArrayList<Integer>();
private Object age[];
...
public EnvDataModel() {
age=list.toArray();
}
public String getColumnName(int col) {
return "Age";
}
public int getColumnCount() {
return 1;
}
public int getRowCount() {
return list.size();
}
public Object getValueAt(int row, int col) {
// Error message The method get(int) in the type ArrayList<Integer> is not applicable for the arguments (Object)
return list.get(age[row]);
}
}
1) ArrayList in the AbstractTableModel returns Column, please read tutorial about JTable how TableModel works
2) you can change ArrayList<Integer> to the Vector<Vector<Integer>> or Interger[][], then you don't need to define for AbstractTableModel, only use default contructor for JTable
JTable(Object[][] rowData, Object[] columnNames)
or
JTable(Vector rowData, Vector columnNames)
3) add Integer value to the DefaultTableModel
list.get(age[row]); requires list.get(int) whereas age[row] is object.
So, try this
int i =Integer.parseInt( age[row].toString() );
and than
list.get(i);

Java JTable binding via JPA

I have tried to search for proper answers, but nothing helped me so far. I am quite new to java GUI programming, actually, to java itself.. I have however managers to understand JPA, how to retrieve, insert and delete using JPA.
Now I want the data in my database to be shown in a JTable.
I currently have the following mySQL table(which i want to show in a JTable
games
Id PK int
Title
Publisher
Genre
ReleaseDate
As far as coding concerns, I have succesfully retrieved the data contained in the table using the following:
public List<Game> getGames(){
List<Game> games;
try{
TypedQuery<Game> selectGamesQuery = entityManager.createQuery("SELECT g FROM Game g", Game.class);
games = selectGamesQuery.getResultList();
} catch(Exception e) {
System.out.println(e);
}
return games;
}
This succesfully returns a list of games whom I can iterate trough.
Then, in my view I have the following
JScrollPane scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
tblGames = new JTable(new tblGamesModel());
tblGames.setShowVerticalLines(true);
tblGames.setShowHorizontalLines(true);
tblGames.setFillsViewportHeight(true);
scrollPane.setViewportView(tblGames);
Which ofcourse leads us to the table model,which is where I'm stuck.
public class tblGamesModel extends AbstractTableModel {
private GameRepository gameRepository;
private List<Game> games;
/**
*
*/
public tblGamesModel(){
gameRepository = new GameRepository();
games = gameRepository.getGames();
}
private static final long serialVersionUID = 1L;
#Override
public int getColumnCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getRowCount() {
// TODO Auto-generated method stub
return games.size();
}
#Override
public Object getValueAt(int arg0, int arg1) {
// TODO Auto-generated method stub
return null;
}
}
I know this is alot of code for a simple post, but I really don't know how else to show the current problem. Any good links would help, or advise on its own.
Thanks for taking the time to read the code and possibly help me out.
Remember, I am just a student programming, so I have a lot to learn about conventions etc aswell. So pointers are also welcome, as I am eager to learn from more experienced developers.
The simplest option is something like this:
#Override
public int getColumnCount() {
return 5;
}
...
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Game game = games.get(rowIndex);
switch (columnIndex) {
case 0:
return game.getId();
case 1:
return game.getTitle();
case 2:
return game.getPublisher();
case 3:
return game.getGenre();
case 4:
return game.getReleaseDate();
}
return null;
}
That can be prone to maintenance problems due to all the magic numbers - a solution would be to use an enumeration for the columns:
enum GameTableColumn {
ID, TITLE, PUBLISHER, GENRE, RELEASE_DATE;
}
And then get the enumeration instance for a column using GameTableColumn.values()[columnIndex].
A few style notes - tblGamesModel is a non-standard name for a Java class, class names always start with an upper case letter. A more Java name would be GamesTableModel. Hungarian notation prefixes (such as "tbl") are generally discouraged.
Also having a database fetch in a constructor is generally a bad idea. In a Swing application you want all fetches to be explicit so you can ensure they do not block the UI. Rather than getGames() I would suggest retrieveGames(). It may be best to construct the GamesRepository outside the table model and pass it in to the constructor. You could then perform the JPA query first in a different thread. This would prevent the UI thread from freezing while the database access is in progress.
Pass loaded list to the model via constructor parameter or setter method. Then you can use following model structure:
public class TblGamesModel extends AbstractTableModel {
private static final String[] COLUMNS = {"id", "title",
...........
private static final int COL_ID = 0;
private static final int COL_TITLE = 1;
private List<Game> list; //list that is injected via constructor or setter method
public int getRowCount() {
return list.size();
}
public int getColumnCount() {
return COLUMNS.length;
}
public Object getValueAt(int rowIndex, int columnIndex) {
Game game = list.get(rowIndex);
switch (columnIndex) {
case COL_ID:
return game.getId();
........
}
}
public String getColumnName(int column) {
return COLUMNS[column];
}

Categories