I am working on invoice and have added jTable to my frame for multiple items, like I have 4 fields for user "item, quantity, rate, price" and user fills it all and click on add button then these fields are added to jTable with item id inlcuded.
now the problem I am facing when user enters the same item whereas that item is already added in the list and it duplicates the row in jTable.
All i want to update that row if the item is same, update its quantity field with adding new quantity value and price value.
i.e.
id |Item |qty| rate| Price|
--------------------------------------
12 |saee |3 | 300| 900 |
now if user enters the same item with 5 quantity, it should update same item or row with plus quantity and price like.
--------------------------------------
id |Item |qty| rate| Price|
--------------------------------------
12 |saee |8 | 300| 24000|
but instead of this, it adds a second row in jTable.
here is my code for adding items in to jTable
DefaultTableModel model = (DefaultTableModel) tbl_sale.getModel();
model.addRow(new Object[]{lbl_id.getText(), txt_item.getText(), txt_qty.getText(), txt_rate.getText(), txt_rs.getText()});
can anyone tell me what should i do?
Sometimes I think we forget that we're operating in an OO environment and the power that something like that can bring
What I mean is, you data can easily be encapsulated into an object, for example...
public class Order {
private int id;
private String item;
private int quanity;
private double unitPrice;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public int getQuanity() {
return quanity;
}
public void setQuanity(int quanity) {
this.quanity = quanity;
}
public double getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public double getTotalPrice() {
return getUnitPrice() * getQuanity();
}
}
This also has the capacity to calculate the total price dynamically, rather than needing us to do it.
DefaultTableModel is good for representing disjointed pieces of information, but not so good at representing an object per row, to this end, I use an AbstractTableModel and customise it for the needs of the object, something like...
public class OrderTabelModel extends AbstractTableModel {
protected static final String COLUMN_NAMES[] = {"ID", "Item", "Qty", "Rate", "Price"};
protected static final Class COLUMN_TYPES[] = {int.class, String.class, int.class, double.class, double.class};
private List<Order> orders;
public OrderTabelModel() {
orders = new ArrayList<>(25);
}
public void add(Order order) {
orders.add(order);
fireTableRowsInserted(orders.size() - 1, orders.size() - 1);
}
public void remove(Order order) {
int row = orders.indexOf(order);
if (row >= 0) {
orders.remove(order);
fireTableRowsDeleted(row, row);
}
}
public void update(Order order) {
int row = orders.indexOf(order);
if (row >= 0) {
fireTableRowsUpdated(row, row);
}
}
public Order getOrderAt(int row) {
return orders.get(row);
}
#Override
public int getRowCount() {
return orders.size();
}
#Override
public int getColumnCount() {
return COLUMN_NAMES.length;
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return COLUMN_TYPES[columnIndex];
}
#Override
public String getColumnName(int column) {
return COLUMN_NAMES[column];
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object value = null;
Order order = getOrderAt(rowIndex);
switch (columnIndex) {
case 0:
value = order.getId();
break;
case 1:
value = order.getItem();
break;
case 2:
value = order.getQuanity();
break;
case 3:
value = order.getUnitPrice();
break;
case 4:
value = order.getTotalPrice();
break;
}
return value;
}
}
Now, when you want to add/remove/update a given object, you can just call add/remove/update methods of the OrderTabelModel.
Be Sure though, when you want to update an Order, you're interacting with an instance from the model, otherwise things won't go as you expect...
OrderTableModel model = ...;
//...
Order order = model.getOrderAt(0);
order.setQuanity(10);
model.update(order);
Related
I have an assignment to make this Restaurant Program. it Consists of an Order Class a product class and the main class. Order has an ArrayList to hold the products. I create an instance of the Order and then I add items through my main method.A product has a name(string) a bar-code(string), and a price(float).
Then I have to output a receipt.But what if a customer orders more of one product? Do I instantiate everything one by one? Is a second Beer Product independent? Should I hold quantities somehow? If I want to add a second beer I have to create a new product Beer2 etc? I don't know beforehand how many products each order will hold and the quantity of each so Is this way of instantiating proper? Thanks
Note: it is still incomplete as I want to deal with this before I move on.
import java.util.Date;
public class MyRestaurantTester {
public static void main(String[] args) {
Date currentDate = new Date();
Paraggelia order1 = new Paraggelia(currentDate,"11B");
Product Beer = new Product("Amstel","111222",1.20f);
Product Beef = new Product("Pork Beef","333444",8.50f);
order1.add(Beer);
order1.add(Beef);
System.out.println(order1.getReceipt(30f));
}
}
Order Class(nevermind the name Paraggelia I gave it)
import java.util.ArrayList;
import java.util.Date;
/*Notes to self:
* -Work on Comments
* -Javadocs maybe?
* -try to optimize the rough code.
*/
/*Order class*/
public class Paraggelia {
private Date orderDate;
private String tableNumber;
private int customerCount;
private ArrayList<Product> listOfItems;
/*Constructor(s)*/
Paraggelia(Date orderDate,String tableNumber){
this.orderDate=orderDate;
this.tableNumber=tableNumber;
this.listOfItems = new ArrayList<Product>();
}
/*Add && Delete Products from the Order class*/
public void add(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}else{
listOfItems.add(p);
}
}
public void delete(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}
else
{
listOfItems.remove(p);
}
}
/** Calculates and returns the total price
* Usually called directly as a parameter of getReceipt function
* */
public static float getTotalPrice(){
return 0;
}
/** Creates and returns the final Receipt!
* -Display must consist of:
* Item$ - BarCode# - Item Amount#
* Total Price#
* Table Number#
*/
public String getReceipt(float totalPrice){
StringBuilder receipt = new StringBuilder();
for(int i =0; i<this.listOfItems.size();i++){
receipt.append(listOfItems.get(i).getName());
receipt.append("\n");
}
return new String(receipt);
}
/*Getters && Setters */
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getTableNumber() {
return tableNumber;
}
public void setTableNumber(String tableNumber) {
this.tableNumber = tableNumber;
}
public int getCustomerCount() {
return customerCount;
}
public void setCustomerCount(int customerCount) {
this.customerCount = customerCount;
}
}
Product Class:
public class Product {
private String Name;
private String barCode;
private float sellingPrice;
/*Constructors: */
Product(){}
Product(String Name,String barCode,float sellingPrice){
this.Name=Name;
this.barCode=barCode;
this.sellingPrice=sellingPrice;
}
/*Getters & Setters*/
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getBarCode() {
return barCode;
}
public void setBarCode(String barCode) {
this.barCode = barCode;
}
public float getSellingPrice() {
return sellingPrice;
}
public void setSellingPrice(float sellingPrice) {
this.sellingPrice = sellingPrice;
}
}
Instead of ArrayList ( List ) you can use Map ( HashMap for example )
MyRestaurantTester
public class MyRestaurantTester {
public static void main(String[] args) {
Date currentDate = new Date();
Paraggelia order1 = new Paraggelia(currentDate,"11B");
Product Beer = new Product("Amstel","111222",1.20f);
Product Beef = new Product("Pork Beef","333444",8.50f);
order1.add(Beer, 1);
order1.add(Beef, 5);
System.out.println(order1.getReceipt(30f));
}
}
Paraggelia
class Paraggelia {
private Date orderDate;
private String tableNumber;
private int customerCount;
private Map<Product, Integer> listOfItems;
/*Constructor(s)*/
Paraggelia(Date orderDate,String tableNumber){
this.orderDate=orderDate;
this.tableNumber=tableNumber;
this.listOfItems = new HashMap<Product, Integer>();
}
/*Add && Delete Products from the Order class*/
public void add(Product p, int quantity){
if(p == null)
{
throw new IllegalArgumentException();
}else{
listOfItems.put(p, quantity);
}
}
public void delete(Product p){
if(p == null)
{
throw new IllegalArgumentException();
}
else
{
listOfItems.remove(p);
}
}
/** Calculates and returns the total price
* Usually called directly as a parameter of getReceipt function
* */
public static float getTotalPrice(){
return 0;
}
/** Creates and returns the final Receipt!
* -Display must consist of:
* Item$ - BarCode# - Item Amount#
* Total Price#
* Table Number#
*/
public String getReceipt(float totalPrice){
StringBuilder receipt = new StringBuilder();
for(Map.Entry<Product,Integer> entry : this.listOfItems.entrySet()) {
Product product = entry.getKey();
Integer quantity = entry.getValue();
receipt.append(product.getName() + " " + quantity);
receipt.append("\n");
}
return new String(receipt);
}
/*Getters && Setters */
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
public String getTableNumber() {
return tableNumber;
}
public void setTableNumber(String tableNumber) {
this.tableNumber = tableNumber;
}
public int getCustomerCount() {
return customerCount;
}
public void setCustomerCount(int customerCount) {
this.customerCount = customerCount;
}
}
OUTPUT:
Pork Beef 5
Amstel 1
Three basic approaches come to mind:
Instantiate each product individually
Instead of ArrayList, have another structure that can associate items with quantities; or,
Make a class Article, which belongs to a Product: Product beerProduct = new Product("beer", "0129", 1.37); Article beer = new Article(beerProduct), beer2 = new Article(beerProduct).
The first solution gives you a lot of flexibility (e.g. to discount individual articles for, say, being damaged). The second solution is more economical with objects. The third one captures the intuition that all the Heineken bottles are the same. It is really up to what you want to do - both approaches are equally valid, for some purpose.
i want to update my database using jtable, table r disply but not update please provide mi solution for it
i am doing following code but it cant update my database and how can fire query for that my database contain id,name,password,email,phone_no
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
public class JtExample extends JFrame {
JTable tbldetails;
DefaultTableModel dtm ;
public int editcol1;
public int editrow;
public JtExample() {
setVisible(true);
setSize(500,500);
setTitle("login Frame");
setLocationRelativeTo(null);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
dtm = new DefaultTableModel(); //dtm consiste row and clonum
String rowheader[] = {"ID","Name" ,"Password", "Email","phn_no"};
dtm.addColumn("ID");
dtm.addColumn("Name");
dtm.addColumn("address");
dtm.addColumn("Email");
dtm.addColumn("phn_no");
dtm.addRow(rowheader);
add();
dtm.addTableModelListener(new TableModelListener ()
{
#Override
public void tableChanged(TableModelEvent arg0) {
int editcol1 =tbldetails.getEditingColumn();
int editrow =tbldetails.getEditingRow();
TableCellEditor tce = tbldetails.getCellEditor(editrow , editcol1);
System.out.println(tce.getCellEditorValue());
}
});
tbldetails = new JTable(dtm);
tbldetails.setBounds(100,100,500,200);
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://Localhost:3306/mydata","root","root");
PreparedStatement ps=con.prepareStatement(" update employee set editcol1=? where editrow=?");
int editcol1 = 0;
String tce = null;
ps.setString(editcol1, tce);
int i=ps.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
add(tbldetails);
}
public void add()
{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://Localhost:3306/mydata","root","root");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select *from employee");
while(rs.next())
{
dtm.addRow(new Object[]{rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4), rs.getString(5)});
}
con.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String args[])
{
new JtExample();
}
}
public static void main(String args[])
{
new JtExample();
}
}
Note: There is more then one way to skin this cat
My first thought is, don't use a DefaultTableModel, instead, use a AbstractTableModel, this will give you greater control of the model and changes to its state.
Start by defining a Plain Old Java Object (POJO) which represents your data. Personally I prefer to start with an interface, this allows me to define mutable and non-mutable versions depending on my requirements
Something like...
public class Employee {
private String id; //??
private String name;
private String password; // Probably should be a char[]
private String email;
private String phoneNumber;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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 getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Employee(String id, String name, String password, String email, String phoneNumber) {
this.id = id;
this.name = name;
this.password = password;
this.email = email;
this.phoneNumber = phoneNumber;
}
}
...for example
Next, you need to define a TableModel which is capable of supporting this data...
public class EmployeeTableModel extends AbstractTableModel {
private String columnNames[] = {"ID","Name" ,"Password", "Email","phn_no"};
private List<Employee> employees;
public EmployeeTableModel() {
employees = new ArrayList<Employee>(25);
}
public EmployeeTableModel(List<Employee> employees) {
this.employees = employees;
}
public void add(Employee employee) {
employees.add(employee);
fireTableRowsInserted(employees.size() - 1, employees.size() - 1);
}
public void remove(Employee employee) {
int index = employees.indexOf(employee);
employees.remove(employee);
fireTableRowsDeleted(index, index);
}
#Override
public int getRowCount() {
return employees.size();
}
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public String getColumnName(int column) {
return columnNames[column];
}
public Employee getEmployeeAt(int row) {
return employees.get(row);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Employee emp = getEmployeeAt(rowIndex);
Object value = null;
switch (columnIndex) {
case 0:
value = emp.getId();
break;
case 1:
value = emp.getName();
break;
case 2:
value = emp.getPassword();
break;
case 3:
value = emp.getEmail();
break;
case 4:
value = emp.getPhoneNumber();
break;
}
return value;
}
}
We're going to add to this later, but for now, this gives us the basics we need...
When you load the data from the database, you could use something like...
EmployeeTableModel model = new EmployeeTableModel();
try (ResultSet rs = st.executeQuery("select *from employee")) {
while(rs.next())
{
model.add(new Employee(
rs.getString(1),
rs.getString(2),
rs.getString(3),
rs.getString(4),
rs.getString(5)));
}
} finally {
tbldetails.setModel(model);
}
So, now we have a self contained unit of work, in our Employee class, a TabelModel which can support it and a means by which you can load the data, now, you need some way to intercept the changes to the data and update the database.
To this end, we're going to update the EmployeeTableModel
public class EmployeeTableModel extends AbstractTableModel {
//...
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex > 0; // id should not be editable here...
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
Employee emp = getEmployeeAt(rowIndex);
switch (columnIndex) {
case 1:
emp.setName(aValue.toString());
break;
case 2:
emp.setPassword(aValue.toString());
break;
case 3:
emp.setEmail(aValue.toString());
break;
case 4:
emp.setPhoneNumber(aValue.toString());
break;
}
update(emp);
fireTableCellUpdated(rowIndex, columnIndex);
}
This will call the update method every time a cell is updated. To this, we pass the Employee object. Based on the value of the id property, you will either need to update or insert a new record.
This is a very simple example, because of the nature of JDBC, the JDBC call could take a period of time to execute. I might be tempted to have some kind of (blocking) queue, onto which I could add Employee objects.
This queue would be processed by another Thread (or SwingWorker or some such), which would pop off the next object and process it, triggering an event callback (to which the TableModel would be listening) with the updated data. The TableModel would then be able to update itself accordingly...
Another idea is to simply have a "save" button, which the user can click. You would then simply iterate through the list of Employees and update them. For this, I would have a simple boolean flag for each object, which would be set to true whenever any of the set methods are called
public class Employee {
private boolean changed = false;
public boolean hasChanged() {
return changed;
}
public void setName(String name) {
this.name = name;
changed = true;
}
Take a closer look at How to Use Tables for moe details
What is the proper relationship, in code, between a table model and the actual database queries?
Inside the addRow() method in the table model, should I place a further call to my database class, which in turn inserts the row into the database? I've illustrated this in the below code snippets.
public class MainPanel extends JPanel
{
...
public MainPanel()
{
personTableModel = new PersonTableModel();
personTable = new JTable(personTableModel);
...
insertButton = new JButton("Insert");
insertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
String name = nameTextBox.getText();
String address = addressTextBox.getText();
Object[] row = { name, address };
personTableModel.addRow(row); // <--- Add row to model
}
});
}
}
public class PersonTableModel extends AbstractTableModel
{
private List<Object[]> data;
private List<String> columnNames;
PersonDB personDB = new PersonDB();
...
public void addRow(Object[] row)
{
// insert row into 'data'
personDB.addPerson(row); // <---- Call the personDB database class
}
...
}
public class PersonDB
{
public PersonDB()
{
// establish database connection
}
public addPerson(Object[] row)
{
// code that creates a SQL statement based on row data
// and inserts new row into database.
}
...
}
Whether or not you should directly make an insert call depends on some aspects:
Do you want other processes to access the data immediately?
Do you fear that your program crashes and you lose important information?
Can you ensure that any data persisted during addRow is meaningful (the program could terminate directly after the insert)?
Than of course it may be a good idea to directly insert the data into the backing Database.
You should however watch out, that there are two variants of addRow and two variants of insertRow. DefaultTableModel directs calls internally through insertRow(int, Vector), which would probably be the only function to overwrite, if you want to immediately persist data.
If you like the proposed idea of DTOs the examples below may help you.
The Idea is to represent "Entities" or table rows as classes in Java. A DTO is the simplest representation and normally only contains fields with respective getter and setter.
Entities can generically be persisted and loaded through ORM libraries like EclipseLink or Hibernate. Additionally for this table-application the use of DTOs provide a way of storing data not shown to the user in a clean and typed way.
DTO:
public class PersonDto {
private Long id;
private String name;
private String street;
public PersonDto() {
}
public PersonDto(Long id, String name, String street) {
this.id = id;
this.name = name;
this.street = street;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public static class NameColumn extends DtoTableModel.ColumnProvider<PersonDto, String> {
public NameColumn() {
super("Name", String.class);
}
#Override
public String getValue(PersonDto dto) {
return dto.getName();
}
#Override
public void setValue(PersonDto dto, Object value) {
dto.setName((String) value);
}
}
public static class StreetColumn extends DtoTableModel.ColumnProvider<PersonDto, String> {
public StreetColumn() {
super("Street", String.class);
}
#Override
public String getValue(PersonDto dto) {
return dto.getStreet();
}
#Override
public void setValue(PersonDto dto, Object value) {
dto.setStreet((String) value);
}
}
}
DTO based TableModel:
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
public class DtoTableModel<T> extends AbstractTableModel {
private final ArrayList<T> rows;
private final ArrayList<ColumnProvider<T, ?>> columns;
protected DtoTableModel() {
rows = new ArrayList<T>();
columns = new ArrayList<ColumnProvider<T, ?>>();
}
#Override
public int getRowCount() {
return rows.size();
}
#Override
public int getColumnCount() {
return columns.size();
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return columns.get(columnIndex).getValue(rows.get(rowIndex));
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
final ColumnProvider<T, ?> column = columns.get(columnIndex);
column.setValue(rows.get(rowIndex), aValue);
this.fireTableCellUpdated(rowIndex, columnIndex);
}
#Override
public String getColumnName(int column) {
return columns.get(column).getTitle();
}
public void addColumn(ColumnProvider<T, ?> column) {
this.columns.add(column);
this.fireTableStructureChanged();
}
public void addRow(T row) {
this.rows.add(row);
this.fireTableRowsInserted(this.rows.size() - 1, this.rows.size() - 1);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return this.columns.get(columnIndex).getValueClass();
}
public static abstract class ColumnProvider<T, V> {
private String title;
private final Class<V> valueClass;
protected ColumnProvider(String title, Class<V> valueClass) {
this.title = title;
this.valueClass = valueClass;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Class<V> getValueClass() {
return valueClass;
}
public abstract V getValue(T dto);
public abstract void setValue(T dto, Object value);
}
}
Example-"Application":
import javax.swing.*;
import java.awt.*;
public class JTableTest extends JFrame {
private final JTable jTable;
public JTableTest() throws HeadlessException {
super("JFrame test");
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
final GridBagLayout layout = new GridBagLayout();
final Container contentPane = this.getContentPane();
contentPane.setLayout(layout);
final GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
final DtoTableModel<PersonDto> dm = new DtoTableModel<PersonDto>();
jTable = new JTable(dm);
dm.addColumn(new PersonDto.NameColumn());
dm.addColumn(new PersonDto.StreetColumn());
dm.addRow(new PersonDto(1L, "Paul", "Mayfairy Street"));
dm.addRow(new PersonDto(2L, "Peter", "Ferdinand Street"));
JScrollPane scrollpane = new JScrollPane(jTable);
contentPane.add(scrollpane, gridBagConstraints);
this.pack();
}
public static void main(String[] args) {
final JTableTest jTableTest = new JTableTest();
jTableTest.setVisible(true);
}
}
I need to be able to update the quantity very simply in this section of code:
import java.util.HashMap;
import java.util.Map;
public class StockData {
private static class Item {
Item(String n, double p, int q) {
name = n;
price = p;
quantity = q;
}
// get methods
public String getName() { return name; }
public double getPrice() { return price; }
public int getQuantity() { return quantity; }
// instance variables
private String name;
private double price;
private int quantity;
}
// with a Map you use put to insert a key, value pair
// and get(key) to retrieve the value associated with a key
// You don't need to understand how this works!
private static Map<String, Item> stock = new HashMap<String, Item>();
static {
// if you want to have extra stock items, put them in here
// use the same style - keys should be Strings
stock.put("00", new Item("Bath towel", 5.50, 10));
stock.put("11", new Item("Plebney light", 20.00, 5));
stock.put("22", new Item("Gorilla suit", 30.00, 7));
stock.put("33", new Item("Whizz games console", 50.00, 8));
stock.put("44", new Item("Oven", 200.00, 4));
}
public static String getName(String key) {
Item item = stock.get(key);
if (item == null) return null; // null means no such item
else return item.getName();
}
public static double getPrice(String key) {
Item item = stock.get(key);
if (item == null) return -1.0; // negative price means no such item
else return item.getPrice();
}
public static int getQuantity(String key) {
Item item = stock.get(key);
if (item == null) return -1; // negative quantity means no such item
else return item.getQuantity();
}
// update stock levels
// extra is +ve if adding stock
// extra is -ve if selling stock
public static void update(String key, int extra) {
Item item = stock.get(key);
if (item != null) item.quantity += extra;
}
}
I've built the GUI for the update page and just need the method to add into it?
Sorry for the trivial question but you have to start somewhere.
Thanks for your help.
I donĀ“t know if I really get your problem, but this is my suggestion to increase the quantity of your Item.
Just add a public method like this:
public void addQuantity(int q) { quantity += q }
I hope you meant this.
Add this method:
public void setQuantity(int q) { quantity = q }
And you may want to start reading at http://docs.oracle.com/javase/tutorial/
I should tell this first, this is NOT about Rendering a Table cell.
Here is the TableModel that i'm building using a 2D array based on a User object in my DB.
List<User> userList = userManagerService.getAllUsers();
/* String[] col_user = {"Username", "Name", "Phone", .... } */
String[][] data = new String[userList.size()][col_user.length];
int i = 0;
for (User user : userList) {
String[] userdata = new String[col_user.length];
userdata[0] = user.getUserUsername();
userdata[1] = user.getUserName();
userdata[2] = user.getUserPhone();
userdata[3] = user.getUserNic();
userdata[4] = user.getUserAddress();
userdata[5] = user.getUserEmail();
data[i++] = userdata;
}
VstTableItemModel tiModel = new VstTableItemModel(data, col_user);
dataTable.setModel(tiModel);
My problem is how can i get a User object back, using the selected row in the Table. Note that i can't make a new User object and populate it with the row data. I must get the queried User object(objects in userList). So, is their any way to set a Object with a table row ?
Here is my VstTableItemModel class.
public class VstTableItemModel extends AbstractTableModel {
ArrayList<Object[]> data;
String[] header;
public VstTableItemModel(Object[][] obj, String[] header) {
this.header = header;
data = new ArrayList<Object[]>();
for (int i = 0; i < obj.length; ++i) {
data.add(obj[i]);
}
}
#Override
public int getRowCount() {
return data.size();
}
#Override
public int getColumnCount() {
return header.length;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return data.get(rowIndex)[columnIndex];
}
#Override
public String getColumnName(int index) {
return header[index];
}
}
Instead of splitting the User object up before you create the model, add it directly to the model and allow the model to do the work for you...
For example
public class VstTableItemModel extends AbstractTableModel {
private List<User> users;
public VstTableItemModel(List<User> users) {
this.users = new ArrayList<User>(users);
}
#Override
public int getRowCount() {
return users.size();
}
#Override
public int getColumnCount() {
return 6;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object value = "??";
User user = users.get(rowIndex);
switch (columnIndex) {
case 0:
value = user.getUserUsername();
break;
case 1:
value = user.getUserName();
break;
case 2:
value = user.getUserPhone();
break;
case 3:
value = user.getUserNic();
break;
case 4:
value = user.getUserAddress();
break;
case 5:
value = user.getUserEmail();
break;
}
return value;
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return // Return the class that best represents the column...
}
/* Override this if you want the values to be editable...
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
//....
}
*/
/**
* This will return the user at the specified row...
* #param row
* #return
*/
public User getUserAt(int row) {
return users.get(row);
}
}
This way, you should be able to do something like...
List<User> userList = userManagerService.getAllUsers();
VstTableItemModel tiModel = new VstTableItemModel(userList);
Now when you need to...you can grab a the user that is represent at a specific row...
User user = tiModel.getUserAt(rowIndex);