I want to display the data on JTable for every button press. Before that, the button will create and store data to the List and should display the data on the table. But, only the creation and data storing is working and the data is not displayed. What should I do to display the data on the table.
This is the abstract model I made to fill my table.
import javax.swing.JList;
import javax.swing.table.AbstractTableModel;
import com.main.Products;
import java.util.List;
public class CartTableModel extends AbstractTableModel{
List<Products> productList;
private final String[] columnNames = new String[] {
"Product:", "ID:", "Variant:", "Size:","Unit Price:","Quantity:","Unit Total:"
};
private Class[] columnClass = new Class[] {
String.class, Integer.class, String.class, String.class, Double.class, Integer.class, Double.class
};
public CartTableModel(List<ProductInfo> productList)
{
this.productList = productList;
}
public String getColumnName(int column)
{
return columnNames[column];
}
#Override
public Class<?> getColumnClass(int columnIndex)
{
return columnClass[columnIndex];
}
#Override
public int getColumnCount()
{
return columnNames.length;
}
#Override
public int getRowCount()
{
return productList.size();
}
#Override
public Object getValueAt(int rowIndex, int columnIndex)
{
Products row = productList.get(rowIndex);
if(0 == columnIndex) {
return row.getProductName();
}
else if(1 == columnIndex) {
return row.getProductID();
}
else if(2 == columnIndex) {
return row.getVariant();
}
else if(3 == columnIndex) {
return row.getSize();
}
else if(4 == columnIndex){
return row.getUnitPrice();
}
else if(5 == columnIndex){
return row.getQuantity();
}
else if(6 == columnIndex){
return row.getTotal();
}
return null;
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return true;
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex)
{
Products row = productList.get(rowIndex);
if(0 == columnIndex) {
row.setProductName((String) aValue);
}
else if(1 == columnIndex) {
row.setProductID((int) aValue);
}
else if(2 == columnIndex) {
row.setVariant((String) aValue);
}
else if(3 == columnIndex) {
row.setSize((String) aValue);
}
else if(4 == columnIndex){
row.setUnitPrice((double) aValue);
}
else if(5 == columnIndex){
row.setQuantity((int) aValue);
}
}
}
This is how the JTable is created:
CartTableModel model = new CartTableModel(productList);
JTable cartTable = new JTable(model);
Also, This is how the data is created:
public void actionPerformed(ActionEvent e) {
if(e.getSource() == coconutPieBtn){
cart.addProduct(new Product("Coconut Creamy Pie", 101,"Pastry","Med",79.99));
}
}
fireTableCellUpdated(productList.size(), columnNames.length)
The row/column values you specify are wrong for two reasons:
you always use the same value no matter what cell you update and
java indexes are 0 based, so you are referring to a row/column that doesn't exist.
Just use:
fireTableCellUpdated(rowIndex, columnIndex)
Also:
cart.addProduct(new Product("Coconut Creamy Pie", 101,"Pastry","Med",79.99));
is wrong. Once the model is created you need to add the new Product to the CartTableModel, NOT the List.
So you need to create a method in your CartTableModel to dynamically add products.
The basic code would be:
public void addProduct(Product product)
{
insertProduct(getRowCount(), product);
}
public void insertProduct(int row, Product product)
{
products.add(row, product);
fireTableRowsInserted(row, row);
}
Check out Row Table Model for a complete example of creating your own custom TableModel with methods for dynamically updating the model.
Related
Hello I want to show the index number of each row in the table I tried with for loop but I had no success can you tell me how to do that ?
I need a logic that return the number of each row in the line "case 0: return getRowCount();" it return the total of rows only
public class TableModel extends AbstractTableModel{
UsersDao ud = new usersDao();
private List<Users> users;
public TableModel() throws Exception {
this.users = (ArrayList<Users>)ud.getUsersList();
}
private DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
#Override
public int getRowCount() {
return users.size();
}
#Override
public int getColumnCount() {
return 10;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Users u = users.get(rowIndex);
switch(columnIndex){
case 0: return getRowCount();
case 1: return u.getName();
case 2: return u.getAge();
case 3: return u.getGender();
default: return "";
}
}
public String getColumnName(int column){
switch(column){
case 0: return "NO";
case 1: return "NAME";
case 2: return "AGE";
case 3: return "GENDER";
default: return "";
}
}
public void addUser(Users u){
users.add(u);
fireTableRowsInserted(users.size()-1, users.size()-1);
}
public void deletePatient(Users u){
users.remove(p);
fireTableRowsInserted(users.size()-1, users.size()-1);
}
}
I think you have a problem in getValueAt
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Users u = users.get(rowIndex);
switch(columnIndex){
case 0: return rowIndex; // return rowIndex rather than the total number of rows
case 1: return u.getName();
case 2: return u.getAge();
case 3: return u.getGender();
default: return "";
}
}
I'm currently programming Yahtzee and I'm in the process of changing the player names. For this I use an extra form in which there is a JTable and a JButton.
Depending on the variable number of players in the table, an entry will be created where you can change the name. Only the second column should be editable - this also works.
However, I have no idea how to make it possible to add the contents from the second column to an ArrayList at the push of a button so that I can continue to use them.
Here is the implementation of my custom TableModel
public class SpielerBenennungTableModel implements TableModel {
private int spielerAnzahl = 0;
private ArrayList<TableModelListener> Listener = new ArrayList<TableModelListener>();
public SpielerBenennungTableModel(int spielerAnzahl){
this.spielerAnzahl = spielerAnzahl;
}
#Override
public int getRowCount() {
return spielerAnzahl;
}
#Override
public int getColumnCount() {
return 2;
}
#Override
public String getColumnName(int arg0) {
if(arg0 == 0){
return "Spieler";
}else{
return "Eigener Name";
}
}
#Override
public Class<?> getColumnClass(int arg0) {
return String.class;
}
#Override
public boolean isCellEditable(int arg0, int arg1) {
if(arg1 == 1){
return true;
}else{
return false;
}
}
#Override
public Object getValueAt(int arg0, int arg1) {
if(arg1 == 0){
return "Spieler: " + (arg0+1);
}else{
return rowData[arg0][arg1];
}
}
#Override
public void setValueAt(Object arg0, int arg1, int arg2) {
}
#Override
public void addTableModelListener(TableModelListener arg0) {
Listener.add(arg0);
}
#Override
public void removeTableModelListener(TableModelListener arg0) {
Listener.remove(arg0);
}
}
Try this out:
In your SpielerBenennungTableModel you need an object to hold the data you display. We will be using a List<String[]> that should look like this (I named it rows):
[
["Spieler: 1", "Bob"],
["Spieler: 2", "John"]
]
every time you change a value, the setValueAt method is called and will update the List<String[]> with the correct value.
Then when you use the getValueAt method, it will read from this same List<String[]>
class SpielerBenennungTableModel implements TableModel {
private int spielerAnzahl = 0;
private ArrayList<TableModelListener> Listener = new ArrayList<TableModelListener>();
// this will hold the data for every rows
private List<String[]> rows;
public SpielerBenennungTableModel(int spielerAnzahl){
this.spielerAnzahl = spielerAnzahl;
// initialize the list so that all rows are
// ["Spieler: n", ""]
rows = new ArrayList<>();
for(int i = 0; i<spielerAnzahl; i++) {
this.rows.add(new String[] { "Spieler: " + (i+1), "" });
}
}
#Override
public int getRowCount() {
return spielerAnzahl;
}
#Override
public int getColumnCount() {
return 2;
}
#Override
public String getColumnName(int col) {
return col == 0 ? "Spieler" : "Eigener Name";
}
#Override
public Class<?> getColumnClass(int col) {
return String.class;
}
#Override
public boolean isCellEditable(int row, int col) {
return col == 1;
}
#Override
public Object getValueAt(int row, int col) {
return rows.get(row)[col];
}
#Override
public void setValueAt(Object value, int row, int col) {
rows.get(row)[col] = value.toString();
}
#Override
public void addTableModelListener(TableModelListener arg0) {
Listener.add(arg0);
}
#Override
public void removeTableModelListener(TableModelListener arg0) {
Listener.remove(arg0);
}
}
I am working on my Java MySql project. I am showing workers in Kitchen Department meals that they need to prepare for guests. When my app starts it fetches unprepared meals from database and displays them in JTable. After they have done it, they check field "done" in table and they press confirm button. Now I want that my table is refreshed when they click order button and that table shows only meals that they need to prepare. I don't have problems with that, I just execute query and I can get unprepared meals from database. My problem is that I don't know how to refresh table. In code I have wrote comment where I think that JTable needs to be refreshed. I am using AbstractTableModel.
Picture of my JTable: http://i.imgur.com/mfO2ts9.jpg
Here is my TableModel class:
public class KitchenTableModel extends AbstractTableModel {
private ArrayList<WrapperKitchen> hrana;
public KitchenTableModel(ArrayList<WrapperKitchen> hrana2) {
this.hrana = hrana2;
}
#Override
public int getColumnCount() {
// TODO Auto-generated method stub
return 8;
}
#Override
public int getRowCount() {
// TODO Auto-generated method stub
return hrana.size();
}
public String getColumnName(int columnIndex) {
switch (columnIndex) {
case 0:return "Order number";
case 1:return "Room";
case 2:return "Category";
case 3:return "Meal";
case 4:return "Quantity";
case 5:return "Note";
case 6:return "Order time";
case 7:return "Done";
}
return null;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
// TODO Auto-generated method stub
WrapperKitchen jelo = hrana.get(rowIndex);
switch (columnIndex) {
case 0:return jelo.getIdUslugaHrana();
case 1:return jelo.getBrojSobe();
case 2:return jelo.getNazivKategorija();
case 3:return jelo.getNazivHrane();
case 4:return jelo.getKolicina();
case 5:return jelo.getNapomena();
case 6:return jelo.getDatumVrijeme();
case 7:return jelo.getIzvrseno();
}
return null;
}
#Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex == 7)
return Boolean.class;
return super.getColumnClass(columnIndex);
}
#Override
public boolean isCellEditable(int rowIndex, int colIndex) {
return (colIndex == 7);
}
#Override
public void setValueAt(Object inValue, int inRow, int inCol) {
if(inRow < 0 || inCol < 0 || inRow >= getRowCount() )
return;
WrapperKitchen jelo= hrana.get(inRow);
switch (inCol) {
case 0:jelo.setIdUslugaHrana((int)inValue);break;
case 1:jelo.setBrojSobe((int)inValue);break;
case 2:jelo.setNazivKategorija((String)inValue);break;
case 3:jelo.setNazivHrane((String)inValue);break;
case 4:jelo.setKolicina((int)inValue);break;
case 5:jelo.setNapomena((String)inValue);break;
case 6:jelo.setDatumVrijeme((Date)inValue);break;
case 7:jelo.setIzvrseno((boolean)inValue);break;
default: throw new RuntimeException("something bad happen incorrect column " + inCol);
}
fireTableCellUpdated(inRow, inCol);
}
}
Here is code of my JButton ActionListener with commented line:
ActionListener a1 = new ActionListener() {
public void actionPerformed(ActionEvent a) {
IzvrseneNarudzbe.clear();
boolean izvrseno;
int id;
for(int red=0;red<KuhinjaListaJela.size();red++){
Object obj = Tablica.getModel().getValueAt(red, 7);
izvrseno=(boolean)obj;
if(izvrseno==true)
{
Object obj2 = Tablica.getModel().getValueAt(red, 0);
id=(int)obj2;
IzvrseneNarudzbe.add(id);
}
}
izvrsiQuery();
//IN THIS LINE I NEED TO REFRESH MY JTABLE
}
void izvrsiQuery(){
for(int i=0;i<IzvrseneNarudzbe.size();i++){
String SqlQuery="UPDATE `room_service`.`usluga_hrana` SET `izvrseno` = '" + 1 +"' WHERE `usluga_hrana`.`id_usluga_hrana` ="+IzvrseneNarudzbe.get(i);
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager
.getConnection("jdbc:mysql://"
+ "localhost:3306/room_service",
"root", "");
Statement Stat = (Statement) con.createStatement();
int Rez = Stat.executeUpdate(SqlQuery);
Stat.close();
} catch (Exception e2) {
System.out.println(e2);
}
}
}
};
In your button's ActionListener, you should invoke setValueAt() to update your TableModel with the results of your query. The model will fireTableCellUpdated() to notify the table to update itself.
I have a jtable with columns for both string and date data types.
but for now every information is presented as a string data
I will like to present date data types in the jtable's
date columns.
I also present below codes for the data model
public class MyTableModel extends AbstractTableModel {
private List<List<Object>> dataList = new ArrayList<>();
private String[] header = { "ID","SUBJECT","LETTTER FROM","LETTER DATE","DATE RECEIED",
"REMARKS","DATE DISPATCHED","DESTINATION OFFICE"};
public List<List<Object>> getDataList() {
return dataList;
}
public void setDataList(List<List<Object>> dataList) {
this.dataList = dataList;
fireTableDataChanged();
fireTableStructureChanged();
}
public void setHeader(String[] header) {
this.header = header;
}
public String[] getHeader() {
return header;
}
#Override
public int getRowCount() {
return dataList.size();
}
#Override
public int getColumnCount() {
return header.length;
}
#Override
public String getColumnName(int col) {
return header[col];
}
#Override
public Object getValueAt(int row, int col) {
return dataList.get(row).get(col);
}
}
any suggestion cos am new to jtable
Override getColumnClass method:
#Override
public Class<?> getColumnClass(int columnIndex) {
if (isDate(columnIndex)) {
return Date.class;
}
else {
return String.class;
}
}
I'd like to add a checkbox to a column. I am using a tableViewer. The user shouldn't be able to edit the checkbox.
Google wasn't helpful so far, so I came here.
my labelprovider looks like this:
this.tableViewer2 = new TableViewer(table1);
this.tableViewer2.setContentProvider(new ArrayContentProvider());
this.tableViewer2.setLabelProvider(new ITableLabelProvider() {
#Override
public String getColumnText(Object element, int columnIndex) {
Platz p = (Platz) element;
switch (columnIndex) {
case 0:
return p.getReihe().getReihenfolge().toString();
case 1:
return p.getNummer().toString();
case 2:
return p.getKategorie().getPreisstd().toString();
}
return null;
}
});
I'd like to add a fourth column with a checkbox but I don't know how.
Thanks in advance!
ITableLableProvider has a method getColumnImage().
Just override it and return an image of the checkbox.
this.tableViewer2 = new TableViewer(table1);
this.tableViewer2.setContentProvider(new ArrayContentProvider());
this.tableViewer2.setLabelProvider(new ITableLabelProvider() {
#Override
public Image getColumnImage(Object element, int columnIndex) {
//do magic here and return an image :)
}
#Override
public String getColumnText(Object element, int columnIndex) {
Platz p = (Platz) element;
switch (columnIndex) {
case 0:
return p.getReihe().getReihenfolge().toString();
case 1:
return p.getNummer().toString();
case 2:
return p.getKategorie().getPreisstd().toString();
}
return null;
}
});