Codename one a loop inside a TableModel - java

i'm trying to place a loop inside a TableModel to loop all the articles inside an arraylist to insert all the rows inside the table so i can add it to the form and show all the articles to the user
public class ListArticlesForm extends Form {
public ListArticlesForm(Form previous) {
setTitle("List all articles");
SpanLabel sp = new SpanLabel();
sp.setText(ServiceTask.getInstance().getAllArticles().toString());
ArrayList<Articles> articles = ServiceTask.getInstance().getAllArticles();
TableModel model = new DefaultTableModel(new String[]{"name", "description", "label", "quantity", "rating", "rate"},
new Object[][]{
{
// I WANT TO PLACE A FOR HERE (this is showing only the first row !
articles.get(0).getName(), articles.get(0).getDescription(), articles.get(0).getLabel(), articles.get(0).getQuantity(), articles.get(0).getRating(), add(createStarRankSlider())
},});
Table table = new Table(model);
add(table);
getToolbar().addMaterialCommandToLeftBar("", FontImage.MATERIAL_ARROW_BACK, e -> previous.showBack());
}
}

You can't create an array as a for loop inside the array. You need to do it a line sooner.
Object[][] rows = new Object[articles.size()][];
for(int iter = 0 ; iter < rows.length ; iter++) {
rows[iter] = new Object[] {
articles.get(iter).getName(), articles.get(0).getDescription(), articles.get(0).getLabel(), articles.get(0).getQuantity(), articles.get(0).getRating(), add(createStarRankSlider())
};
}
TableModel model = new DefaultTableModel(new String[]{"name", "description", "label", "quantity", "rating", "rate"}, rows);

now after i Run the project the table rows are displayed correctly except the rank stars
the show outside the table and inside the colonne a text appears:
the function for the star rank creation is :
private Slider createStarRankSlider(int id) {
Slider starRank = new Slider();
starRank.setEditable(true);
starRank.setMinValue(0);
starRank.setMaxValue(10);
int fontSize = Display.getInstance().convertToPixels(3);
Font fnt = Font.createTrueTypeFont("Handlee", "Handlee-Regular.ttf").
derive(fontSize, Font.STYLE_PLAIN);
Style s = new Style(0xffff33, 0, fnt, (byte) 0);
Image fullStar = FontImage.createMaterial(FontImage.MATERIAL_STAR, s).toImage();
s.setOpacity(100);
s.setFgColor(0);
Image emptyStar = FontImage.createMaterial(FontImage.MATERIAL_STAR, s).toImage();
initStarRankStyle(starRank.getSliderEmptySelectedStyle(), emptyStar);
initStarRankStyle(starRank.getSliderEmptyUnselectedStyle(), emptyStar);
initStarRankStyle(starRank.getSliderFullSelectedStyle(), fullStar);
initStarRankStyle(starRank.getSliderFullUnselectedStyle(), fullStar);
starRank.setPreferredSize(new Dimension(fullStar.getWidth() * 5, fullStar.getHeight()));
starRank.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
ServiceTask.getInstance().UpdateRank(id,starRank.getIncrements());
Dialog.show("Success","thank you for rating our product",new Command("OK"));
}
});
return starRank;
}

Related

Put firebase data in a JTable

I am struggling to put some firebase data into a jtable in java swing.
As seen in photo I've been able to retrieve the data from firebase but for some reason the data won't be displayed in the JTable field(table1)
I looks like the getID(), getName()... methods didn't get any value, since I tried to print row[i] to see if there is any value.
There is a screenshot of the actual program
Could any of you tell what's the problem?
addNewCaseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
database = FirebaseDatabase.getInstance();
ref = database.getReference("NewCases");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println(dataSnapshot.getValue());
ArrayList<Object[]> myList = new ArrayList<>();
DefaultTableModel tableModel = (DefaultTableModel) table1.getModel();
tableModel.addColumn("ID");
tableModel.addColumn("Name");
tableModel.addColumn("Age");
tableModel.addColumn("City");
tableModel.addColumn("TimeStamp");
tableModel.addColumn("Disease");
tableModel.addColumn("Risk");
Object[] row = new Object[6];
tableModel.setNumRows(0);
myList.clear();
CasesList casesList = new CasesList();
for (DataSnapshot ds : dataSnapshot.getChildren()){
casesList.setID((Integer)ds.child("ID").getValue());
casesList.setName(ds.child("Name").getValue().toString());
casesList.setAge((Integer)ds.child("Age").getValue());
casesList.setCity(ds.child("City").getValue().toString());
casesList.setTimeStamp(ds.child("TimeStamp").getValue().toString());
casesList.setDisease(ds.child("Disease").getValue().toString());
casesList.setRisk(ds.child("Risk").getValue().toString());
// myList.add(ds.getKey());
row[0] = casesList.getID();
row[1] = casesList.getName();
row[2] = casesList.getAge();
row[3] = casesList.getCity();
row[4] = casesList.getTimeStamp();
row[5] = casesList.getDisease();
row[6] = casesList.getRisk();
myList.add(row);
System.out.println(myList);
tableModel.addRow(row);
}
table1.setModel(tableModel);
Thanks in advance!
Have you defined the table columns with lines like these?
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addColumn("ID");
tableModel.addColumn("Name");
tableModel.addColumn("Age");
Also, the method setModel should be called after the for:
for... {
//add row to tableModel
}
table1.setModel(tableModel);
EDIT:
Analyzing in more detail, I also verify that you have 7 fields but your array has only space for 6. In this line row [6] = casesList.getRisk (); throws an exception at runtime. Expand the size of your array to solve this.
Object[] row = new Object[7];
To display the column names it is convenient to add your table to a scroll panel.
JScrollPane scrollPane = new JScrollPane(table1);
frame.getContentPane().add(scrollPane);
This works for me:
ArrayList<Object[]> myList = new ArrayList<>();
DefaultTableModel tableModel = (DefaultTableModel) table1.getModel();
tableModel.addColumn("ID");
tableModel.addColumn("Name");
tableModel.addColumn("Age");
tableModel.addColumn("City");
tableModel.addColumn("TimeStamp");
tableModel.addColumn("Disease");
tableModel.addColumn("Risk");
Object[] row = new Object[7];
tableModel.setNumRows(0);
myList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
CasesList casesList = new CasesList();
casesList.setID((Integer) ds.child("ID").getValue());
casesList.setName(ds.child("Name").getValue().toString());
casesList.setAge((Integer) ds.child("Age").getValue());
casesList.setCity(ds.child("City").getValue().toString());
casesList.setTimeStamp(ds.child("TimeStamp").getValue().toString());
casesList.setDisease(ds.child("Disease").getValue().toString());
casesList.setRisk(ds.child("Risk").getValue().toString());
row[0] = casesList.getID();
row[1] = casesList.getName();
row[2] = casesList.getAge();
row[3] = casesList.getCity();
row[4] = casesList.getTimeStamp();
row[5] = casesList.getDisease();
row[6] = casesList.getRisk();
myList.add(row);
System.out.println(myList);
tableModel.addRow(row);
}
table1.setModel(tableModel);

Star rank in table row are displayed outside the table

when I Run the project the table rows are displayed correctly except the rank stars the show outside the table and inside the colonne a text appears as displayed in the image :
public ListTasksForm(Form previous) {
SpanLabel sp = new SpanLabel();
sp.setText(ServiceTask.getInstance().getAllArticles().toString());
ArrayList<Articles> articles = ServiceTask.getInstance().getAllArticles();
Object[][] rows = new Object[articles.size()][];
for (int iter = 0; iter < rows.length; iter++) {
rows[iter] = new Object[]{
articles.get(iter).getName(), articles.get(iter).getDescription(), articles.get(iter).getLabel(), articles.get(iter).getQuantity(),
articles.get(iter).getRating(), add(createStarRankSlider(articles.get(iter).getId_article()))
};
}
TableModel model = new DefaultTableModel(new String[]{"name", "description", "label", "quantity", "rating", "rate"}, rows);
Table table = new Table(model);
add(table);
getToolbar().addMaterialCommandToLeftBar("", FontImage.MATERIAL_ARROW_BACK, e -> previous.showBack());
}
});
and this is the function for the star rank creation
private Slider createStarRankSlider(int id) {
Slider starRank = new Slider();
starRank.setEditable(true);
starRank.setMinValue(0);
starRank.setMaxValue(10);
int fontSize = Display.getInstance().convertToPixels(3);
Font fnt = Font.createTrueTypeFont("Handlee", "Handlee-Regular.ttf").
derive(fontSize, Font.STYLE_PLAIN);
Style s = new Style(0xffff33, 0, fnt, (byte) 0);
Image fullStar = FontImage.createMaterial(FontImage.MATERIAL_STAR, s).toImage();
s.setOpacity(100);
s.setFgColor(0);
Image emptyStar = FontImage.createMaterial(FontImage.MATERIAL_STAR, s).toImage();
initStarRankStyle(starRank.getSliderEmptySelectedStyle(), emptyStar);
initStarRankStyle(starRank.getSliderEmptyUnselectedStyle(), emptyStar);
initStarRankStyle(starRank.getSliderFullSelectedStyle(), fullStar);
initStarRankStyle(starRank.getSliderFullUnselectedStyle(), fullStar);
starRank.setPreferredSize(new Dimension(fullStar.getWidth() * 5, fullStar.getHeight()));
starRank.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
ServiceTask.getInstance().UpdateRank(id,starRank.getIncrements());
}
});
return starRank;
}
You didn't include the code for the initStarRankStyle but it's pretty obvious what you did here. You just relied on the behavior of the container. Table derives Container so it includes all of its methods e.g. add(Component).
But these methods won't work correctly since a table fetches its data from the model and invokes add internally. So you're logic is conflicting with the table.
You need to derive table and define how you want that data to be rendered. You can do that by overriding the method protected Component createCell(Object value, int row, int column, boolean editable) as explained here.

I want to add Data in JTable when an item is selected from JComboBox in Java?

I have made a JComboBOx in which I am showing the products that I sell. When a user clicks the Item i search in array list and a Object is returned and from that Object I want to put information in a two dimensional array and after that I want to add that two dimensional array to the row of the JTable but i am not getting anything in table.
Anyone who can help my how I can add items in JTable when an Item is selected from JComboBox?
public void actionPerformed(ActionEvent arg0) {
String boughtThing = InventoryList.getSelectedItem().toString();
int NumberOfItems = Integer.parseInt(JOptionPane.showInputDialog("Enter the Number Item"));
ImplementInventoryServices service = new ImplementInventoryServices();
Inventory thing = service.searchInventory(boughtThing);
double price = thing.getPricePerUnit();
String nameOfProduct = thing.getInventoryName();
int stock = thing.getNumberOfInventory();
int IDofProduct = thing.getInventoryID();
subtotal = 0;
subtotal = price * NumberOfItems;
stock = stock - NumberOfItems;
data[0][0] = Double.toString(price);
data[0][1] = nameOfProduct;
data[0][2] = Integer.toString(NumberOfItems);
data[0][3] = Double.toString(subtotal);
info = new Information(price, nameOfProduct, IDofProduct, subtotal);
Inventory inventory = new Inventory(nameOfProduct, IDofProduct, price, stock);
ImplementInventoryServices updating = new ImplementInventoryServices();
updating.updateInventory(nameOfProduct, inventory);
subTotalList.add(subtotal);
DataHandlingForInventory.write();
}
});
String [] columns = {"ID","Name","Price Per Unit", "Sub Total"};
OrignalTable = new JTable(data,columns);
OrignalTable.setBounds(10, 119, 425, 219);
InvoiceMake.getContentPane().add(OrignalTable);
Try like this:
Create a DefaultTableModel to hold your data and link that to the table:
Object [] columns = {"ID","Name","Price Per Unit", "Sub Total"};
tableModel = new DefaultTableModel(columns, 0);
OrignalTable = new JTable(tableModel);
Now you can use that model (defined as a field in your class so you have access inside the anonymous ActionListener) to work on the data:
// before
// data[0][0] = Double.toString(price);
// data[0][1] = nameOfProduct;
// data[0][2] = Integer.toString(NumberOfItems);
// data[0][3] = Double.toString(subtotal);
// after
tableModel.addRow(new Object[]{Double.toString(price),
nameOfProduct,
Integer.toString(NumberOfItems),
Double.toString(subtotal)});
Please be sure to read up on the documenentation on How to Use Tables

How to properly delete row in JTable with double click?

Good afternoon guys, i'm trying to learn java programming and then i'm encountering some problem that i don't know why with my code when I'm learning about JTable.
So, what I'm trying to do is when i double clicked the row in JTable named TableGejala, the row that i double clicked will transfered into the other JTable named TableAturan and after that the row that i double clicked in TableGejala will be removed. For the part of transferring row from TableGejala to TableAturan successfully transferred when i double clicked the row, but it doesn't delete the correct row in TableGejala. Instead of deleting the row that i clicked, it delete the row below it.
For more details, this is my code to create TableGejala :
private void getTableGejala() {
while(tabel2.getRowCount() > 0){
for(int i=0;i < tabel2.getRowCount();i++){
tabel2.removeRow(i);
}
}
tabel2.addColumn("ID Gejala");
tabel2.addColumn("Nama Gejala");
TabelGejala.setModel(tabel2);
TabelGejala.setAutoResizeMode(TabelGejala.AUTO_RESIZE_ALL_COLUMNS);
}
And then this is my code to get data for my table from MySQL :
private void loadDataGejala(Boolean baru){
tabel2.getDataVector().removeAllElements();
try {
java.sql.Connection konek = (Connection) Koneksi.KoneksiDB.getConnection();
java.sql.Statement konek_statement = konek.createStatement();
String query_bukaTabel = "";
if(baru){
query_bukaTabel = "select id_gejala,nama_gejala from gejala";
}
else{
String idPkt = FieldID.getText();
query_bukaTabel = "select gejala.id_gejala,gejala.nama_gejala from gejala where gejala.id_gejala not in(select id_gejala from aturan2 where id_penyakit='"+idPkt+"')";
}
java.sql.ResultSet line_result = konek_statement.executeQuery(query_bukaTabel);
while (line_result.next()) {
Object[] getO = new Object[2];
getO[0] = line_result.getString("id_gejala");
getO[1] = line_result.getString("nama_gejala");
tabel2.addRow(getO);
}
line_result.close();
konek_statement.close();
}catch (Exception e) {}
}
This is my code to transfer the row and delete the row :
private void TabelGejalaMousePressed(java.awt.event.MouseEvent evt) {
if (evt.getClickCount()>=2){
int col = 0;
int row = 0;
row = TabelGejala.rowAtPoint(evt.getPoint());
col = TabelGejala.columnAtPoint(evt.getPoint());
String col1 = (String)TabelGejala.getValueAt(row, 0);
String col2 = (String)TabelGejala.getValueAt(row, 1);
DefaultTableModel model = (DefaultTableModel) TabelAturan.getModel();
DefaultTableModel old = (DefaultTableModel) TabelGejala.getModel();
old.removeRow(row);
model.addRow(new Object[]{col1, col2, 0});
TabelAturan.requestFocus();
TabelAturan.setRowSelectionInterval(TabelAturan.getRowCount()-1,TabelAturan.getRowCount()-1);
TabelAturan.editCellAt(TabelAturan.getRowCount()-1,2);
}
}
And this is the screenshot of my problem :
Before Double Clicked
After Double Clicked
Which part that makes my output get the wrong row to be deleted? please help me, and thank you in advance for any helps, even for reading my question :)
Firstly disable cell editable property in your first table(TabelGejala) to ensure proper deleting of row. I achieved this using the following code :-
//instance table model
DefaultTableModel tableModel = new DefaultTableModel(new Object[][]{},
new String[]{
"ID Gejala", "Nama Gejala"
}) {
#Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
TabelGejala.setModel(tableModel);
then use jtable.getselectedrow() and jtable.getselectedcolumn() to get values from table. after addition of desired values to second table, simply delete the selected row. here is the code, derived from your code :-
private void TabelGejalaMousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
if (evt.getClickCount() >= 2) {
DefaultTableModel model = (DefaultTableModel) TabelAturan.getModel();
DefaultTableModel old = (DefaultTableModel) TabelGejala.getModel();
model.addRow(new Object[]{TabelGejala.getValueAt(TabelGejala.getSelectedRow(), 0), TabelGejala.getValueAt(TabelGejala.getSelectedRow(), 1), 0});
old.removeRow(TabelGejala.getSelectedRow());
TabelAturan.requestFocus();
TabelAturan.setRowSelectionInterval(TabelAturan.getRowCount() - 1, TabelAturan.getRowCount() - 1);
TabelAturan.editCellAt(TabelAturan.getRowCount() - 1, 2);
}
}

java, collect data from one JTable, using event handler change display of other JTable

Since the program is too large I'll just paste the important parts of code. Here's the problem:
I have two JTables. First one collects data from DB and displays the list of all invoices stored in DB. The purpose of the second table is when you click on one row from the table, event handler needs to collect integer from column ID. Using this ID the second table will then display all the contest of that invoice (all the products stored in it).
First and second table work perfectly. The problem is that I have no idea how can I collect certain data (I basically just need ID column) from a selected row and then through a method I already made update the second JTable with new info. Here's my code if it helps:
(PS: once I learn how to do that, will the list on the left change every time by default when I select different row, or do I need to use validate/revalidate methods?)
public JPanel tabInvoices() {
JPanel panel = new JPanel(new MigLayout("", "20 [grow, fill] 10 [grow, fill] 20", "20 [] 10 [] 20"));
/** Labels and buttons **/
JLabel labelInv = new JLabel("List of all invoices");
JLabel labelPro = new JLabel("List of all products in this invoice");
/** TABLE: Invoices **/
String[] tableInvTitle = new String[] {"ID", "Date"};
String[][] tableInvData = null;
DefaultTableModel model1 = new DefaultTableModel(tableInvData, tableInvTitle);
JTable tableInv = null;
/** Disable editing of the cell **/
tableInv = new JTable(model1){
public boolean isCellEditable(int r, int c) {
return false;
}
};
/** Load the invoices from DB **/
List<Invoice> listInv = is.getAllInvoices();
for (int i = 0; i < listInv.size(); i++) {
model1.insertRow(i, new Object[] {
listInv.get(i).getID(),
listInv.get(i).getDate()
});
}
/** TABLE: Invoice Info **/
String[] tableInfTitle = new String[] {"ID", "Name", "Type", "Price", "Quantity"};
String[][] tableInfData = null;
DefaultTableModel model2 = new DefaultTableModel(tableInfData, tableInfTitle);
JTable tableInf = null;
/** Disable editing of the cell **/
tableInf = new JTable(model2){
public boolean isCellEditable(int r, int c) {
return false;
}
};
/** Load the products from DB belonging to this invoice **/
List<Product> listPro = is.getInvoiceInfo(1); // Here's where I need the ID fetched from selected row. For now default is 1.
for (int i = 0; i < listPro.size(); i++) {
model2.insertRow(i, new Object[] {
listPro.get(i).getID(),
listPro.get(i).getName(),
listPro.get(i).getType(),
listPro.get(i).getPrice(),
listPro.get(i).getQuantity()
});
}
/** Scroll Panes **/
JScrollPane scrollInv = new JScrollPane(tableInv);
JScrollPane scrollPro = new JScrollPane(tableInf);
panel.add(labelInv);
panel.add(labelPro, "wrap");
panel.add(scrollInv);
panel.add(scrollPro);
return panel;
}
For now, the right table only displays content of the first invoice:
With the help of following code you can get the value of selected clicked cell, so you just have to click on ID cell value (the Invoicee ID whose Products you want to see in second table) and with the help of following event handler you will get the value and then you can get data based on that ID and set to second table. (In the code below, table is the object of your first table)
(Off-course you will have to apply some validation too, to check that the selected (and clicked) cell is ID not the DATE)
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
int row = table.rowAtPoint(e.getPoint());
int col = table.columnAtPoint(e.getPoint());
Object selectedObj = table.getValueAt(row, col);
JOptionPane.showMessageDialog(null, "Selected ID is " + selectedObj);
}
});

Categories