HashMap only printing out last value in JTable row - java

I really tried searching for the solution to this problem, but I cant seem to get it right. I have an application that Im working on, and I would like to print out all of a customers orders in a JTable with rows. So if a customer has three orders I want it to show each order on a separate row.
With this code (the next block) I got it to work, but it's only printing out the last value. So if I have Order 3 attached to a customer, and then add Order 4, it only shows Order 4.
JButton btnHämtaKund = new JButton("Hämta");
btnHämtaKund.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String searchTerm = sökrutaKund.getText();
Customer c = Controller.findCustomer(searchTerm);
String sum = "";
if (c != null) {
if (c.getOrders() != null) {
for (Order tmp : c.getOrders().values()) {
String date = tmp.getDate();
String price = Double.toString(tmp.getPrice());
String rfd = "";
if (tmp.getRdyForDelivery() == true) {
rfd = "Ready for delivery";
} else if (tmp.getRdyForDelivery() == false) {
rfd = "Processing";
}
model.addRow(new String[] {date, price, rfd});
}
txtfieldTestKund.setText(sum);
} else {
txtfieldTestKund.setText("c.getOrders() == null");
}
} else {
txtfieldTestKund.setText("c == null");
}
}
});
Model is my DefaultModelTable.
I also tried with a for-loop like this in case I was overwriting my last row all the time:
for (int i = 0; i < c.getOrders().size(); i++) {
String date = c.getOrders().get(i).getDate();
String price = Double.toString(c.getOrders().get(i).getPrice());
String rfd = "";
if (c.getOrders().get(i).getRdyForDelivery() == true) {
rfd = "Ready for delivery";
} else if (c.getOrders().get(i).getRdyForDelivery() == false) {
rfd = "Processing";
}
Object row[] = {date, price, rfd};
model.addRow(row);
}
but that just gave a Nullpointerexception.
Any ideas what to do? Really thankful for help!

I had to fix a method to increase the key for each Order i added to Customer, looks like I was overwriting the previous with the last one.
private int counter = 0;
public void add(Order o) {
counter += 1;
String newCounter = Integer.toString(counter);
this.orders.put(newCounter, o);
}

Related

table selectedRow() does not differentiate which one i select

I'm working on my project which is Bar management system for orders, like in a real restaurant or bar and I've got specific problem. I'm choosing specific table and I'm creating for example 3 orders in it which are represent in 3 rows. When i add one product in first order, then i click on second row ( order ) and add the same product, it adds it on both. Is the problem in the selectedRow() method or I'm trying to make the impossible xD...
public void createOrder() {
boolean isYes = showQuestionPopup("Open new order?");
if (isYes) {
Order order = new Order("1", selectedTableNumber, frame.dataProvider.loggedUser);
frame.dataProvider.orders.add(order);
frame.dataProvider.fetchProducts(productsTableModel, order);
frame.dataProvider.fetchOrders(ordersTableModel, selectedTableNumber);
}
}
public void addProductToOrder(Product product) {
if (ordersTable.getSelectedRow() < 0) {
showError("No selected row");
return;
}
int currentlySelectedRow = ordersTable.getSelectedRow();
Order order = frame.dataProvider.orders.get(ordersTable.getSelectedRow());
boolean isFound = false;
for (Product prd : order.getProducts()) {
if (prd.getBrand().equals(product.getBrand())) {
prd.setQuantity(prd.getQuantity() + 1);
isFound = true;
break;
}
}
if (!isFound) {
order.getProducts().add(product);
}
frame.dataProvider.fetchProducts(productsTableModel, order);
frame.dataProvider.fetchOrders(ordersTableModel, selectedTableNumber);
ordersTable.setRowSelectionInterval(currentlySelectedRow, currentlySelectedRow);
}
public void fetchOrders(DefaultTableModel model, int tableNumber) {
model.setRowCount(0);
for (int i = 0; i < orders.size(); i++) {
Order order = orders.get(i);
if (order.getTableNumber() == tableNumber) {
String row[] = new String[3];
row[0] = Integer.toString(i + 1);
row[1] = order.getProductsCount();
row[2] = order.getTotalPrice(false);
model.addRow(row);
}
}
}
public void fetchProducts(DefaultTableModel model, Order order) {
model.setRowCount(0);
for (Product product : order.getProducts()) {
String row[] = new String[3];
row[0] = product.getBrand();
row[1] = Integer.toString(product.getQuantity());
row[2] = product.getTotalPrice();
model.addRow(row);
}
}

Use values from previous row to aggregate values when row missing

I have a whole bunch of rows that contain tax payments.
Each row contains PaymentDueDate.
If row is missing in between PaymentDueDates, I have to use same values from previous row to aggregate for all totals.
In below example, between Row="2" and Row="3", data is missing for months 2015/09, 2015/10, 2015/11, 2015/12, 2016/01, 2016/02.
So, I have to use Row="2" values to use to account for missing rows.
<PaymentChangeMaintenance>
<PaymentChangeMaintenanceTransaction Row="1">
<BuydownSubsidyAmount>0.00</BuydownSubsidyAmount>
<AnnualInterestRate>4.75000</AnnualInterestRate>
<PIAmount>689.79</PIAmount>
<PaymentDueDate>2015-07-01</PaymentDueDate>
<CityTaxAmount>23.22</CityTaxAmount>
<CountyTaxAmount>32.25</CountyTaxAmount>
</PaymentChangeMaintenanceTransaction>
<PaymentChangeMaintenanceTransaction Row="2">
<BuydownSubsidyAmount>0.00</BuydownSubsidyAmount>
<AnnualInterestRate>4.75000</AnnualInterestRate>
<PIAmount>689.79</PIAmount>
<PaymentDueDate>2015-08-01</PaymentDueDate>
<CityTaxAmount>125.25</CityTaxAmount>
<CountyTaxAmount>666.22</CountyTaxAmount>
</PaymentChangeMaintenanceTransaction>
<PaymentChangeMaintenanceTransaction Row="3">
<BuydownSubsidyAmount>0.00</BuydownSubsidyAmount>
<AnnualInterestRate>4.75000</AnnualInterestRate>
<PIAmount>689.79</PIAmount>
<PaymentDueDate>2016-03-01</PaymentDueDate>
<CityTaxAmount>125.25</CityTaxAmount>
<CountyTaxAmount>666.22</CountyTaxAmount>
</PaymentChangeMaintenanceTransaction>
</PaymentChangeMaintenance>
Here is code someone wrote, but it is not clean-looking. I would like to use for-each :/
private void aggregateEscrowPaymountAmounts(List<PaymentChangeMaintenanceFieldsV214Type> fieldsType,
PaymentChangeMaintenance paymentChangeMaintenance, final int numberOfTrialPayments) {
AtomicInteger cnt = new AtomicInteger(1);
Iterator<PaymentChangeMaintenanceFieldsV214Type> fieldsTypeIterator = fieldsType.iterator();
PaymentChangeMaintenanceFieldsV214Type fieldType = fieldsTypeIterator.next();
PaymentChangeMaintenanceFieldsV214Type nextFieldType = null;
if (fieldsTypeIterator.hasNext()) {
nextFieldType = fieldsTypeIterator.next();
}
LocalDate monthDate = fieldType.getNextPaymentDueDate();
while (cnt.getAndIncrement() <= numberOfTrialPayments) {
PaymentChangeMaintenance tempPaymentChangeMaintenance = createPaymentChangeMaintenanceEscrow(fieldType);
paymentChangeMaintenance.aggregate(tempPaymentChangeMaintenance);
monthDate = monthDate.plusMonths(1);
if (nextFieldType != null) {
LocalDate nextFieldTypeDate = nextFieldType.getNextPaymentDueDate();
if (nextFieldTypeDate.getMonthValue() == monthDate.getMonthValue()) {
fieldType = nextFieldType;
if (fieldsTypeIterator.hasNext()) {
nextFieldType = fieldsTypeIterator.next();
} else {
nextFieldType = null;
}
}
}
}
}
For this certain case you can use a following approach: determine a step - for you it's a month. Then initialize a default value for a case of absence of the value on the next step. Then use some method that will take a next value and default value and depends on a step presence will return one of them
Here is a pseudocode:
List<Item> items;
Item nextItem = items.get(0);
Value step = month;
for (int i = 1; i < items.size(); i++) {
nextItem = getNextItem(items.get(i), nextItem, step);
****
}
Item getNextItem(Item nextItem, Item defaultItem, Value step) {
if (!nextItem.getStepValue().equals(calcNext(step))) {
return defaultItem;
} else {
return nextItem;
}
}
StepValue calcNext(Value step) {
/*some calculations. In your case month increment*/
}

JPA/Hibernate/Spring - Primary key exception

Eclipse throws me an exception - Duplicate entry '201805091-1' for key 'PRIMARY'. I understand that exception, but I do not understand why the code below makes a new record in my database. I thought this should work like: If the combination of date and doctors id does not exist - then make it otherwise use the combination that is currently in database. But there must be obviously something wrong...
Thank you very much :)
OperationsDate od = null; // these 6 lines of the code may be problematic
if(em.find(OperationsDate.class, id) != null) {
od = em.find(OperationsDate.class, id);
} else {
od = new OperationsDate(id);
}
public void process(List<Integer> list, int doctorId, String pin, boolean inf) {
Patient p = em.find(Patient.class, pin);
Doctor d = em.find(Doctor.class, doctorId);
p.addDoctor(d);
d.addPatient(p);
int id = countId(doctorId);
OperationsDate od = null;
if(em.find(OperationsDate.class, id) != null) {
od = em.find(OperationsDate.class, id);
} else {
od = new OperationsDate(id);
}
if(inf) {
for(int number : list) {
Medicine m = em.find(Medicine.class, number);
od.setDoctor(d);
d.addOperationsDate(od);
od.addMedicine(m);
m.addOperationsDate(od);
}
} else {
Operation o = em.find(Operation.class, list.get(0));
od.setDoctor(d);
d.addOperationsDate(od);
od.addOperation(o);
o.addOperationsDate(od);
}
}
public int countId(int doctorId) {
long millis=System.currentTimeMillis();
java.sql.Date date=new java.sql.Date(millis);
String id = "";
String date2 = date.toString();
for(int i=0; i < date2.length();i++) {
if(i == 4 || i == 7) {
continue;
}
id += date2.charAt(i);
}
id += doctorId;
int id2 = Integer.parseInt(id);
return id2;
}
Just try it this way then, as I told you in my comment:
OperationsDate od = em.find(OperationsDate.class, id);
if( od == null) {
od = new OperationsDate(id);
}
...
// potential persist or merge, depending on your frameworks configuration regarding autocommit and such
em.persist(od);
If it still doesn't work, add the code for your entities, to make sure nothing's wrong about it.

Add the items from one list to another list in java

I have two arraylists say
ArrayList<BaseItem> normal;
ArrayList<BaseItem> highlighted;
normal = new ArrayList<BaseItem>();
highlighted = new ArrayList<BaseItem>();
what I am doing is I am Iterating through a 3rd list(called MyItems) and adding the items in it called highlight and normal to the above two lists like this.
for (Iterator<BaseItem> iterator = MyItems.iterator(); iterator.hasNext();) {
BaseItem itemtype = iterator.next();
if (itemtype.isHighlight()) {
highlighted.add(itemtype);
}
else{
normal.add(itemtype);
}
}
So my question is I want to add every 5th and 6th item of the highlited list to the list called normal .i.e elements like 5,6,11,12,17,18 and so on
and also I want to add every 6th and 7th item of normal list to highlighted list i.e 6,7,13,14 and so on.
so now my highlighted and normal lists will contain the items like this
Highlighted -> highlighted1,highlighted2,highlighted3,highlighted4,normal6,normal7 highlighted7,highlighted8.highlighted9,highlighted10,normal13,normal14 and so on
Normal -> Noraml1,normal2,normal3,normal4,normal5,highlighted5,highlighted6,normal7,normal8,normal9,normal10,normal11,normal12,highlighted11,highlighted12 and so on
Any help is always appreciated,
Thanks
If I understand, use a counter when after 5 and 6 insert in your list, add in normal list instead of highlighted list
Try this:
int highAdded = 0;
int normalAdded = 0;
for (Iterator<BaseItem> iterator = MyItems.iterator(); iterator.hasNext();) {
BaseItem itemtype = iterator.next();
if (itemtype.isHighlight()) {
highAdded++;
if (highAdded == 5) {
normal.add(itemtype);
} else if (highAdded == 6) {
normal.add(itemtype);
highAdded = 0;
} else {
highlighted.add(itemtype);
}
}
else{
normalAdded++;
if (normalAdded == 6) {
highlighted.add(itemtype);
} else if (normalAdded == 7) {
highlighted.add(itemtype);
normalAdded = 0;
} else {
normal.add(itemtype);
}
}
}
EDIT
I write this code:
public class StackOverFlowSample {
public static void main(String [] args) {
List<String> lst = new ArrayList<String>();
List<String> lstHigh = new ArrayList<String>();
List<String> lstNormal = new ArrayList<String>();
lst.add("highlighted01");
lst.add("highlighted02");
lst.add("highlighted03");
lst.add("highlighted04");
lst.add("highlighted05");
lst.add("highlighted06");
lst.add("highlighted07");
lst.add("highlighted08");
lst.add("highlighted09");
lst.add("highlighted10");
lst.add("highlighted11");
lst.add("highlighted12");
lst.add("highlighted13");
lst.add("highlighted14");
lst.add("highlighted15");
lst.add("highlighted16");
lst.add("normal01");
lst.add("normal02");
lst.add("normal03");
lst.add("normal04");
lst.add("normal05");
lst.add("normal06");
lst.add("normal07");
lst.add("normal08");
lst.add("normal09");
lst.add("normal10");
lst.add("normal11");
lst.add("normal12");
lst.add("normal13");
lst.add("normal14");
lst.add("normal15");
lst.add("normal16");
int highAdded = 0;
int normalAdded = 0;
for (Iterator<String> iterator = lst.iterator(); iterator.hasNext();) {
String itemtype = iterator.next();
if (itemtype.startsWith("highlighted")) {
highAdded++;
if (highAdded == 5) {
lstNormal.add(itemtype);
} else if (highAdded == 6) {
lstNormal.add(itemtype);
highAdded = 0;
} else {
lstHigh.add(itemtype);
}
}
else{
normalAdded++;
if (normalAdded == 6) {
lstHigh.add(itemtype);
} else if (normalAdded == 7) {
lstHigh.add(itemtype);
normalAdded = 0;
} else {
lstNormal.add(itemtype);
}
}
}
String result = "HIGHLIGHTED ARRAY: ";
for (String curr : lstHigh) {
result += curr + ", ";
}
System.out.print(result);
result = "NORMAL ARRAY: ";
for (String curr : lstNormal) {
result += curr + ", ";
}
System.out.print(result);
}
}
The output is:
HIGHLIGHTED ARRAY: highlighted01, highlighted02, highlighted03, highlighted04, highlighted07, highlighted08, highlighted09, highlighted10, highlighted13, highlighted14, highlighted15, highlighted16, normal06, normal07, normal13, normal14,
NORMAL ARRAY: highlighted05, highlighted06, highlighted11, highlighted12, normal01, normal02, normal03, normal04, normal05, normal08, normal09, normal10, normal11, normal12, normal15, normal16,
Tell me if it's OK ;)

JTable table.getSelectedRows() issue

I create a JTable with a customized model and characteristics. I have a long written class that carries out the set up and rendering properly. I see that the .getSelectedRows() method is not working and never evaluates to a value. I was trying to get the index of the first row selected and the last. Here is my code.
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
rows = table.getSelectedRows();
firstRow = rows[0];
int rowCount = rows.length;
lastRow = rows[(rowCount - 1)];
if (command.equals("Run Threw")) {
}else if (command.equals("Shield Bash")) {
this.attack(firstRow, lastRow, command);
}
public boolean block (int defendersRow) {
}
public boolean fumble (int attackersRow) {
}
public boolean dodge (int defendersRow) {
}
public boolean critical (int attackersRow, int attackRoll) {
}
public void attack(int firstRow, int lastRow, String command) {
command = this.command;
firstRow = this.firstRow;
lastRow = this.lastRow;
if (command == "Bludgeon" || command == "React" || command == "ShieldBash") {
attackersRow = this.lastRow;
defendersRow = this.firstRow;
}else if(command == "Attack" || command == "Skill") {
attackersRow = this.firstRow;
defendersRow = this.lastRow;
}else {
}
table.setValueAt(true, attackersRow, 16);
fumbled = this.fumble(attackersRow);
if (fumbled == true) {
outputString = "fumbled";
}
Object maxDamageObject = table.getValueAt(attackersRow, 10);
int maxDamage = (Integer) maxDamageObject;
attackRoll = generator.nextInt(100) + 1;
this.critical(attackersRow, attackRoll);
if (criticaled == true) {
outputString = "criticaled";
}
dodged = this.dodge(defendersRow);
if (dodged == true) {
outputString = "dodged";
}
blocked = this.block(defendersRow);
if (blocked == true) {
outputString = "blocked";
}
int defenseRoll = generator.nextInt(100) + 1;
Object attackBaseObject = table.getValueAt(attackersRow, 6);
Object defenseBaseObject = table.getValueAt(defendersRow, 11);
int attackBase = (Integer) attackBaseObject;
int defenseBase = (Integer) defenseBaseObject;
int attack = attackRoll + attackBase;
int defense = defenseRoll + defenseBase;
Object minDamageObject = table.getValueAt(attackersRow, 9);
int minDamage = (Integer) minDamageObject;
damage = generator.nextInt((maxDamage - minDamage))+minDamage;
if (criticaled == true) {
damage = maxDamage * 2;
}else if (attack >= (defense + 50)) {
damage = damage * 2;
}else if (attack >= defense) {
damage = damage;
}else {
damage = 0;
}
this.outputSelection(outputString, attackersRow, defendersRow, command, damage);
this.damage(defendersRow, damage);
}
private void damage(int defendersRow, int damage) {
}
private void outputSelection(String outputString, int attackersRow, int defendersRow, String command, int damage) {
}
I doesn't see problem with code. May be you can cross check following points:
Are you able to select single / multiple row(s)? Or check what jTableObject.getRowSelectionAllowed() returns
Does your code gets called only after selecting rows. Your code should be executed after some rows are selected so that it can return you expected values.
Listener which calls above mentioned code, is it added to table.
Small points but better to cross check :).
As shown in this working example, you can add a ListSelectionListener to your table's ListSelectionModel and see if anything comes through. It may help pin down where things have gone awry: for example, a local table reference that shadows the intended one.

Categories

Resources