Using information from object selected in jList - java

I am having difficulty getting information from a jList so that it can be used to create an object in a different class when a button is clicked,
private void jButtonAddOrderActionPerformed(java.awt.event.ActionEvent evt) {
int noCopies;
String title, Name;
noCopies = Integer.parseInt(jTextFieldCopies.getText());
title = Book.bookInstances.get(jListPubBooks.getSelectedIndex()).getName();
Name = Book.bookInstances.get(jListPubBooks.getSelectedIndex()).getPublisherName();
new Order(noCopies, title, Name);
setjlistmodel(Order.orderItem);
I am sure there are no problems with my setjlistmodel method as this works elsewhere in my program when only getting information from text fields. I think my problem is with these two lines:
title = Book.bookInstances.get(jListPubBooks.getSelectedIndex()).getName();
Name = Book.bookInstances.get(jListPubBooks.getSelectedIndex()).getPublisherName();
}
This is my order class;
package bookstore;
import java.util.ArrayList;
public class Order {
int noOfBooks;
String bookTitle;
String pubName;
public static ArrayList<Order> orderItem = new ArrayList<>();
ArrayList<ArrayList<Order>> Order = new ArrayList<>();
public Order(int noBooks, String Title, String Name)
{
this.noOfBooks = noBooks;
this.bookTitle = Title;
this.pubName = Name;
orderItem.add(this);
}
public void addOrder(ArrayList ord)
{
Order.add(ord);
}
public int getNoBooks()
{
return noOfBooks;
}
public String getBookTitle()
{
return bookTitle;
}
public String getPubName()
{
return pubName;
}
}
setjlistmodel method:
private void setjlistmodel(ArrayList<Order> orderInstances){
DefaultListModel OrderList = new DefaultListModel();
for(int i = 0; i<=OrderList.size()-1;i++){
OrderList.addElement(orderInstances.get(i).getNoBooks());
System.out.println(orderInstances.get(i).getBookTitle());
System.out.println(OrderList.firstElement());
}
jListOrder.setModel(OrderList);
}
The problem is that it is not displaying anything in jListOrder when the button is clicked. I don't think the Order is being added to the orderItem ArrayList.

"The problem is that it is not displaying anything in jListOrder when the button is clicked. I don't think the Order is being added to the orderItem ArrayList."
I think adding an orderItem is fine.
OrderList size is zero when you first initialize it, which means your loops does absolutely nothing
DefaultListModel OrderList = new DefaultListModel();
for(int i = 0; i <= OrderList.size() - 1; i++)
You probably want
for(int i = 0; i <= orderInstances.size() - 1; i++)
Which is using the ArrayList size.
As a side note, please separate operators with space. It makes it easier to read.

Related

Looping for array lists and adding values which match two array lists into a new one

I'm trying to make a program that matches a clients interests with aspects of a holiday, I have an array list of holidays and an array list of strings for the clients interests and I wanted to create a new array list which would add all elements that are contained in both. This is what I have but it comes up with a null pointer exception, Any ideas where I've gone wrong?
the debugger points towards the disjoint and at " int c1size = c1.size();"
Relevant parts of code...
In main...
ClientExt1 marina = new ClientExt1("Marina",14321,"marina.calder1#btinternet.com");
ArrayList<String> interests = new ArrayList<>();
interests.add("History");
interests.add("Music");
marina.setInterests(interests);
holidaySeller.getHolidayMatches(marina);
Client...
public class ClientExt1 {
private String name;
private int id;
private String email;
private HolidayExt1 holidayBooked;
private ArrayList<String> interests;
public ClientExt1(String name, int id, String email){
this.name=name;
this.id=id;
this.email=email;
}
public void setInterests(ArrayList interests) {
this.interests=interests;
}
public ArrayList<String> getInterests(){
return interests;
Company class...
public class CompanyExt1 {
protected ArrayList<StaffExt1> staffMembers;
protected ArrayList<HolidayExt1> holidays;
protected ArrayList<GuideExt1> holidayGuides;
protected ArrayList<AdventureExt1> adventureHolidays;
protected ArrayList<CultureExt1> cultureHolidays;
private ArrayList<String> matchedHolidays;
public ArrayList<String> findHolidayMatch(ClientExt1 client) {
ArrayList interests = client.getInterests();
int i;
for (i = 0; i < holidays.size() && i< interests.size(); i++) {
if (!Collections.disjoint(holidays.get(i).getAspects(), interests)) {
matchedHolidays.add(holidays.get(i).getName());
}
}
return matchedHolidays;
}
public void getHolidayMatches(ClientExt1 client){
System.out.println(client.getName() + ", the holidays recommended to you based on your interests from this company are:" + findHolidayMatch(client));
}
}
You need to initialize holidays before you use it and matchedHolidays before you add values to it in findHolidayMatch
I would actually make matchedHolidays a local variable instead of a class member since it is only used in the scope of the findHolidayMatch method.

How to set for loop array values to a bean

I have the following loop in a controller class:
for (int i = 0; i <= locationArr.length - 1; i++) {
data.put(idArr[i], locationArr[i]);
locationBean.setLocation_name(locationArr[i]);
}
My Bean looks like :
public class LocationBean {
private String region_id;
private String region_name;
private String location_id;
private String location_name;
//getters and setters
}
I am trying to set location_name as setLocation_name(locationArr[i]);
But only getting last values of the loop [i] is being assigned.
If you like to have multiple location names you can do that by e.g. a List or more general any Collection if order does not matter.
Here an example:
public class LocationBean {
private String region_id;
private String region_name;
private String location_id;
private List<String> locationNames = new ArrayList<>();
//getters and setters
public List<String> getLocationNames() {
return locationNames;
}
}
usage in your loop:
locationBean.getLocationNames().add(locationArr[i]);
I did not refactor all your example code to be complient to the java naming convention. You should name your variables in camel case.
Either u can create a list of LocationBean objects :
ArrayList <LocationBean> locationBeanList = new ArrayList <LocationBean>)();
for (int i = 0; i <= locationArr.length - 1; i++) {
data.put(idArr[i], locationArr[i]);
locationBean = new LocationBean();
locationBean.setLocation_name(locationArr[i]);
locationBeanList.add(locationBean);
}
Or, u can create list of locations in single location bean
public class LocationBean {
private String region_id;
private String region_name;
private String location_id;
private List<String> location_name_list = new ArrayList<String>();
//getters and setters
}
List<String> locationList = new ArrayList <String>();
for (int i = 0; i <= locationArr.length - 1; i++) {
data.put(idArr[i], locationArr[i]);
locationList.add(locationArr[i]);
}
locationBean.setLocation_name_list(locationList );
LocationBean with a List
You want to store every location name, not set ONE value. So you want a method addLocationName store it into a Collection
locationBean.addLocationName(locationArr[i]);
That method is simple, it will add every String into a List<String>
private List<String> locationsName;
private List<String> locationsId;
public LocationBean (){
locationsName = new ArrayList<String>();
locationsId= new ArrayList<String>();
}
public boolean addLocationName(string locationName){
return this.locationsName.add(locationName);
}
public boolean addLocationId(string locationId){
return this.locationsId.add(locationId);
}
Of course, you would need to do the same with location_id, so a Bean would be smarter :
public class Location{
private String id;
private String name;
public Location(String id, String name){ ... }
//constructor and getter
}
and simply use a List<Location> instead. That way, both id and name are stored together.
public boolean addLocation(Location location){
return this.locations.add(location);
}
or passing the values
public boolean addLocation(String id, String name){
return this.locations.add(new Location(id, name));
}
List of LocationBean
Or your bean should only have one location and then this is in your loop that you need to store every instance of LocationBean into a List<LocationBean> (don't forget to create a new instance each time`
List<LocationBean> locations = new ArrayList<>();
for (int i = 0; i <= locationArr.length - 1; i++) {
locationBean = new LocationBean(); //new instance each time
locationBean.setLocation_name(locationArr[i]);
locations.add(locationBean); //add into the list
}

How can I calculate the sum of all elements within my JList ?

I'm creating a shopping cart simulation with a list of products that i want to add together and display the total of as they are being added to the cart basket (implemented as a jlist).
In my main class I have a button with an action listener to take items from my stocklist and add them to the basket.
scanBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
checkoutBasket.addElement(productList.getSelectedValuesList());
}
});
In addition I have a JTextField set up below the basket which I want to dynamically update with the total cost as I add items to the cart. My question is how could I go about doing this ? Thank you.
cartTotalField = new JTextField();
getContentPane().add(cartTotalField);
cartTotalField.setBounds(581, 441, 233, 28);
Cart Item Class :
import java.io.*;
public class CartItem implements Serializable {
private String barcodeNo;
private String itemName;
private String price;
public CheckoutItem() {
}
public CheckoutItem (String barno, String in, String cost) {
barcodeNo = barno;
itemName = in;
price = cost;
}
public String getBarcodeNo(){
return barcodeNo;
}
public String getItemName(){
return itemName;
}
public void setitemName(String itemName){
this.itemName = itemName;
}
public String getPrice(){
return price;
}
public String toString(){
return barcodeNo + ": " + itemName + ", " + price;
}
public Object getID() {
// TODO Auto-generated method stub
return null;
}
}
In your actionPerformed, you could do something like this (of course, this is a very naive approach to get it, you could possibly think of something better on this):
#Override
public void actionPerformed(ActionEvent evt) {
//Get the newly added list values.
JList list = productList.getSelectedValuesList();
double totalAddedValue = 0.0;
double oldCartValue = 0.0;
//Iterate to get the price of the new items.
for (int i = 0; i < list.getModel().getSize(); i++) {
CartItem item = (CartItem) list.getModel().getElementAt(i);
totalAddedValue += Double.ParseDouble(item.getPrice());
}
//Set total price value as an addition to cart total field.
//cartTotalField must be accessible here.
string cartFieldText = cartTotalField.getText();
//Check that cartTextField already contains a value.
if(cartTextField != null && !cartTextField.isEmpty())
{
oldCartValue = Double.parseDouble(cartFieldText);
}
cartTotalField.setText(String.valueOf(oldCartValue + totalAddedValue));
checkoutBasket.addElement(list);
}
UPDATE: In general, you should consider adding checks and/or exception handling for numeric conversions. A good idea would also be to change the price property to double (or int, modifying the above code accordingly) in your CartItem class.

What is wrong with this method - (Adding Elements within a Jlist)?

I'm currently in the process of creating a shopping cart simulation program. The main GUI contains two lists, one is a list of products or the inventory. (products stored within a .dat file which is automatically loaded upon launch) The other is blank and is to model my shopping basket. The idea is to be able to scan items from my inventory into the checkout basket. As this is happening i want a text field i created to dynamically update with the cost of all the items in the basket.
Below is the method for my scan button, which is supposed to perform the above :
public void actionPerformed(ActionEvent evt) {
//Get the newly added list values.
JList list = productList.getSelectedValuesList();
double totalAddedValue = 0.0;
double oldCartValue = 0.0;
//Iterate to get the price of the new items.
for (int i = 0; i < list.getModel().getSize(); i++) {
CartItem item = (CartItem) list.getModel().getElementAt(i);
totalAddedValue += Double.ParseDouble(item.getPrice());
}
//Set total price value as an addition to cart total field.
//cartTotalField must be accessible here.
string cartFieldText = cartTotalField.getText();
//Check that cartTextField already contains a value.
if(cartTextField != null && !cartTextField.isEmpty())
{
oldCartValue = Double.parseDouble(cartFieldText);
}
cartTotalField.setText(String.valueOf(oldCartValue + totalAddedValue));
checkoutBasket.addElement(list);
}
Currently however scanning the item will add it to the list but print strange results in the total. (Adds 5.5 for each item regardless of their actual value**). It will also print a line under the item name as such javax.swing.JList[,0,0,344x326,layout=java.awt.BorderLa... .
Below are the classes for my CartItem and ItemList if they may help. Thank you.
-Cart Item
import java.io.*;
public class CartItem implements Serializable {
private String barcodeNo;
private String itemName;
private String price;
public CartItem() {
}
public CartItem (String barno, String in, String cost) {
barcodeNo = barno;
itemName = in;
price = cost;
}
public String getBarcodeNo(){
return barcodeNo;
}
public String getItemName(){
return itemName;
}
public void setitemName(String itemName){
this.itemName = itemName;
}
public String getPrice(){
return price;
}
public String toString(){
return barcodeNo + ": " + itemName + ", " + price;
}
public Object getID() {
// TODO Auto-generated method stub
return null;
}
}
-ItemList
import javax.swing.DefaultListModel;
public class ItemList extends DefaultListModel {
public ItemList(){
super();
}
public void addCartItem(String barcodeNo, String itemName, String price){
super.addElement(new CartItem(barcodeNo, itemName, price));
}
public CartItem findItemByName(String name){
CartItem temp;
int indexLocation = -1;
for (int i = 0; i < super.size(); i++) {
temp = (CartItem)super.elementAt(i);
if (temp.getItemName().equals(name)){
indexLocation = i;
break;
}
}
if (indexLocation == -1) {
return null;
} else {
return (CartItem)super.elementAt(indexLocation);
}
}
public CartItem findItemByBarcode(String id){
CartItem temp;
int indexLocation = -1;
for (int i = 0; i < super.size(); i++) {
temp = (CartItem)super.elementAt(i);
if (temp.getBarcodeNo().equals(id)){
indexLocation = i;
break;
}
}
if (indexLocation == -1) {
return null;
} else {
return (CartItem)super.elementAt(indexLocation);
}
}
public void removeItem(String id){
CartItem empToGo = this.findItemByBarcode(id);
super.removeElement(empToGo);
}
}
You're adding the JList itself to the check out basket, and that doesn't make sense:
checkoutBasket.addElement(list);
This, javax.swing.JList[,0,0,344x326,layout=java.awt.BorderLa... . shows that something is displaying the toString() representation of the JList, likely your checkout basket.
Regarding,
Adds 5.5 for each item regardless of their actual value
I don't think your current code shows why this is happening, and you might want to create and post an mcve.
Other thoughts:
Don't use String to represent price, but rather consider a numeric field, perhaps BigDecimal if you want to be accurate for money.
You look to be mixing your view with your model too much. Try to keep them separate as possible, meaning, you should likely have some more non-GUI classes including one to represent the shopping basket, and any other nouns.

Update a single variable of a class in an ArrayList of class in java

I have a class Components:
public class Components {
int numberOfNets;
String nameOfComp;
String nameOfCompPart;
int numOfPin;
public components(int i, String compName, String partName, int pin) {
this.numberOfNets = i;
this.nameOfComp = compName;
this.nameOfCompPart = partName;
this.numOfPin = pin;
}
}
Inside another class I created an arraylist of Components class:
List<Components> compList = new ArrayList<Components>();
Later in the code, I am adding the elements in List in this way:
compList.add(new Components(0,compName,partName,0));
See, here numberOfNets and numOfPin variables in Components class are initiated with 0 values. But these values are getting calculated/incremented in a later part of code and hence I need to update the new values of only these two variables in each list element. Now from ArrayList doc I get the idea of updating a list element using its index by set operation. But I am confused how to set/update a particular variable of a class in an ArrayList of a class. I need to update only these two mentioned variables, not all of the four variables in Components class. Is there any way to do that?
You should add getter/setter to your component class so that outer class can update component's members
public class Components {
private int numberOfNets;
private String nameOfComp;
private String nameOfCompPart;
private int numOfPin;
public components(int i, String compName, String partName, int pin) {
setNumberOfNets(i);
setNameOfComp(compName);
setNameOfCompPart(partName);
setNumOfPin(pin);
}
public void setNumberOfNets(int numberOfNets) {
this.numberOfNets = numberOfNets;
}
// Similarly other getter and setters
}
You can now modify any data by using following code because get() will return reference to original object so modifying this object will update in ArrayList
compList.get(0).setNumberOfNets(newNumberOfNets);
Example code.
public class Main {
public static void main(String[] args) {
List<Components> compList = new ArrayList<Components>();
compList.add(new Components(0, "compName", "partName", 0));
System.out.println(compList.get(0).toString());
compList.get(0).numberOfNets = 3;
compList.get(0).numOfPin = 3;
System.out.println(compList.get(0).toString());
}
}
Your class.
public class Components {
int numberOfNets;
String nameOfComp;
String nameOfCompPart;
int numOfPin;
public Components(int i, String compName, String partName, int pin) {
this.numberOfNets = i;
this.nameOfComp = compName;
this.nameOfCompPart = partName;
this.numOfPin = pin;
}
public String toString() {
return this.numberOfNets + " " + nameOfComp + " " + nameOfCompPart
+ " " + numOfPin;
}
}
The output:
0 compName partName 0
3 compName partName 3

Categories

Resources