Java: Filling a JComboBox with objects - java

I'm trying to fill a jComboBox with objects. I have it working in one class, but in this class it's giving a NullPointerException but the code is almost the same. What am I missing here?
The code I'm using to fill the comboboxes:
I have translated every variable to English and removed some unnescessary stuff. I hope it's more clear for you guys now:
package unive.billing.boundary.clientmanager.frames;
import unive.billing.control.ClientsManager;
import unive.billing.control.InsuranceManager;
/**
*
* #author Forza
*/
public class ClientFrame extends javax.swing.JFrame {
/**
* Creates new form AddClientGUI
*/
private ClientsManager clientmanager;
private InsuranceManager insurancemanager;
public ClientFrame() {
initComponents();
clientmanager = new ClientsManager();
clientmanager.printList();
updateComboBoxCompany();
updateComboBoxInsurance();
}
private ClientsManager clientmanager;
private InsuranceManager insurancemanager;
public ClientFrame() {
initComponents();
clientmanager = new ClientsManager();
clientmanager.printList();
updateComboBoxCompany();
updateComboBoxInsurance();
}
public void updateComboBoxCompany()
{
for (Object object : insurancemanager.getCompanyNames())
{
companyComboBox.addItem(object);
}
}
public void updateComboBoxInsurance()
{
for (Object object : insurancemanager.getPolicyNames())
{
insuranceComboBox.addItem(object);
}
}
Here are the methods used:
public Object[] getCompanyNames()
{
ArrayList<String> cnames = new ArrayList<String>();
for (InsurancesCompany company : insurancecompanyList)
{
cnames.add(company.getCompanyName());
}
return cnames.toArray();
}
public Object[] getPolicyNames()
{
ArrayList<String> vnames = new ArrayList<String>();
for (Insurance insurance : insuranceList)
{
vnames.add(insurance.getPolicyName());
}
return vnames.toArray();
}
This is how my lists are initialized:
public class InsuranceManager {
private String insurancePath;
private String insurancecompanyenPath;
private static List<InsurancesCompany> insurancecompanyList;
private static List<Insurance> insuranceList;
private Insurance currentInsurance;
public InsuranceManager() {
insurancecompanyenPath = "Files/company.txt";
insurancePath = "Files/insurance.txt";
insuranceList = new List<>();
}
public void createNewList()
{
insurancecompanyList = new List<>();
System.out.println("Creates list");
}
public Object[] getCompanyNames()
{
ArrayList<String> cnames = new ArrayList<String>();
for (InsurancesCompany company : insurancecompanyList)
{
cnames.add(company.getCompanyName());
}
return cnames.toArray();
}
public Object[] getPolicyNames()
{
ArrayList<String> vnames = new ArrayList<String>();
for (Insurance insurance : insuranceList)
{
vnames.add(insurance.getPolicyName());
}
return vnames.toArray();
}
Edit: Here's the MainGUI which calls createNewList (maakLijstAan)
private ClientsManager clientsmanager;
private BillingManager billingmanager;
private InsuranceManager insurancemanager;
public MainGUI() {
clientsmanager = new ClientsManager();
clientsmanager.CreateNewList();
insurancemanager = new InsuranceManager();
insurancemanager.CreateNewList();
insurancemanager.loadInsuranceCompanyList();
initComponents();
jMenuItem1.setText("Save clients");
jMenuItem2.setText("Load clients");
jMenuItem3.setText("Exit");
}

You never initialize verzekeringBeheer, therefore you get a NullPointerException when you try to invoke methods on that variable.
You should have somewhere in your constructor, something like this:
verzekeringbeheer = new VerzekeringBeheer();
Also, try to avoid making your code coupled with other parts of your code. For example:
public VerzekeringBeheer() {
...
//verzekeringmaatschappijLijst is never initialized!!!
}
public void maakLijstAan()
{
verzekeringmaatschappijLijst = new Lijst<>();
System.out.println("Maak lijst aan");
}
public Object[] getMaatschappijNamen()
{
ArrayList<String> mnamen = new ArrayList<String>();
// Here you use verzekeringmaatschappijLijst without checking that is not null!!!
for (VerzekeringsMaatschappij maatschappij : verzekeringmaatschappijLijst)
{
mnamen.add(maatschappij.getMaatschappijNaam());
}
return mnamen.toArray();
}
If nobody calls maakLijstAan, you will get a NullPointerException in getMaatschappijNamen. Try to avoid code that is so dependent of external code, in order to run without problems.

all data for JComboBox are stored in ComboBoxModel
set ComboBoxModel for proper Objects type (String, Integer, Icon or simple Object), Java7 implements Generics, there are significant differiences in compare with Java6
all updates (to the JComboBox or its Model) must be done on Event Dispatch Thread

I only see you useing variables but for me they are nit initialized. So they are null and you get a NPE.
So how are verzekeringmaatschappijLijst and verzekeringLijst initialized?

Related

Using a Java For-Each Loop to iterate over an ArrayList which has private access?

I have three classes: Labradors, Kennels and Show. The Kennel contains a private ArrayList of
Labradors. As shown:
Labradors.java:
public class Labradors {
private String name;
private String description;
public Labradors(String n, String d) {
name = n;
description = d;
}
public String getName() {
return name;
}
}
Kennel.java:
import java.util.ArrayList;
public class Kennel{
private ArrayList<Labradors> labs;
public Kennel() {
labs = new ArrayList<Labradors>();
}
public void addDog(Labradors l) {
labs.add(l);
}
}
and
Show.java
class Show
{
public static void main(String args[])
{
Labradors Dave = new Labradors("Dave", "Good dog!");
Labradors Bob = new Labradors("Bob", "Likes tummy rubs!");
Kennel niceHome = new Kennel();
niceHome.addDog(Dave);
niceHome.addDog(Bob);
for (Labradors lab: niceHome.labs ) {
System.out.println(lab.getName());
}
}
}
My for-each loop in Show gives me the following error:
Show.java:12: error: labs has private access in Kennel
for (Labradors lab: niceHome.labs ) {
^
1 error
Clearly one solution would be to make the ArrayList public, but my understanding of encapsulation is that best practice means it should be private and a Getter written. But how do I do this?
I feel this should have a really easy answer, but I'm having difficulty tracking it down...
NB - I'm using openjdk version 11.0.6 on Ubuntu 19.10.
Inside Kennel Class make a getter function
import java.util.ArrayList;
public class Kennel{
private ArrayList<Labradors> labs;
public Kennel() {
labs = new ArrayList<Labradors>();
}
public void addDog(Labradors l) {
labs.add(l);
}
public ArrayList<Labradors> getLabs(){
return this.labs;
}
}
Then access from main function like this
class Show
{
public static void main(String args[])
{
Labradors Dave = new Labradors("Dave", "Good dog!");
Labradors Bob = new Labradors("Bob", "Likes tummy rubs!");
Kennel niceHome = new Kennel();
niceHome.addDog(Dave);
niceHome.addDog(Bob);
for (Labradors lab: niceHome.getLabs()) {
System.out.println(lab.getName());
}
}
}

Global Variable appending multiple copies of data while updating

I have created a class named "Global Services" which I use to save my data globally and access them in a different activity. But when I am calling the set() method, instead of overview the existing data instead it is appending that data. Below is my code.
I have even tried to remove the instance but still, it is appending the new data instead of overwriting.
import java.util.ArrayList;
import java.util.List;
public class GlobalServices {
private static GlobalServices instance;
String partner, leadsResponse;
List<Leads> assignedList = new ArrayList<>();
List<Leads> unAssignedList = new ArrayList<>();
List<Inventory> listInventory = new ArrayList<>();
private GlobalServices() {}
public static GlobalServices getInstance() {
if (instance == null) {
instance = new GlobalServices();
}
return instance;
}
public static void destory() {
instance = null;
}
public String getPartner() {
return partner;
}
public String getLeadsResponse() {
return leadsResponse;
}
public List<Leads> getAssignedList() {
return assignedList;
}
public List<Leads> getUnAssignedList() {
return unAssignedList;
}
public List<Inventory> getListInventory() {
return listInventory;
}
public void setPartner(String partner) {
this.partner = partner;
}
public void setLeadsResponse(String leadsResponse) {
this.leadsResponse = leadsResponse;
}
public void setAssignedList(List<Leads> assignedList) {
this.assignedList = assignedList;
}
public void setUnAssignedList(List<Leads> unAssignedList) {
this.unAssignedList = unAssignedList;
}
public void setListInventory(List<Inventory> listInventory) {
this.listInventory = listInventory;
}
}
The problem is that you're just assigning new references to your lists in GlobalServices but not creating new lists. This means as soon as you modify this reference from another place in your code, it will be reflected in the GlobalServices list as well. All you have to do is:
public void setAssignedList(List<Leads> assignedList) {
this.assignedList = new ArrayList<>(assignedList);
}
public void setUnAssignedList(List<Leads> unAssignedList) {
this.unAssignedList = new ArrayList<>(unAssignedList);
}
public void setListInventory(List<Inventory> listInventory) {
this.listInventory = new ArrayList<>(listInventory);
}
This way a new copy will be created in memory for each list and the data will be overwritten.
Sorry if I was wrong, but your code here is not a problem.
The problem might come from other part of your application.
The data you set might be the data that extend your current data.
Example you have
GlobalServices instance = GlobalServices.getInstance()
List<Inventory> listInventory1 = new ArrayList<>();
listInventory1.add(new Inventory());
instance.setListInventory(listInventory1); // now your inventory have one item
// In some where else in your project
List<Inventory> listInventory2 = instance.getListInventory(); // lisInventorys.size() equals 1
// Then you add more data to listInventory2 by mistake
listInventory2.add(new Inventory()); // listInventory2.size() equals 2
// Then you set back listInventory2 to your global service
instance.setListInventory(listInventory2); // now your inventory have two item
So, the data had been actually overwrite, it data just been extended by accident.

How to set a value on a class using another class that is called/set in main class

I have 3 classes, say: ShareType, ShareTypesTrue and Main.
public class ShareType {
public String shareTypeName = "";
public String noOfShare = "";
public String parValue = "";
public void setShareTypeName(String shareTypeName) {
this.shareTypeName = shareTypeName;
}
public void setNoOfShare(String noOfShare) {
this.noOfShare = noOfShare;
}
public void setParValue(String parValue) {
this.parValue = parValue;
}
}
public class ShareTypesTrue {
public List<ShareType> shareType;
public void setShareType(List<ShareType> shareType) {
this.shareType = shareType;
}
}
public class Main {
ShareTypesTrue sharetypetrue = new ShareTypesTrue();
sharetypetrue.add(shareTypeName);
}
Now my problem is i need to set shareTypeName to a value under the class ShareTypesTrue. Meaning i have to use ShareTypesTrue to call on the Sharetype class and set the shareTypeName.
Anyone has an idea?
NOTE: I cant change/add code in the first 2 classes except in main. i just need to find a way to get around this.
Thanks Alot
Please check below code for Main class.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String args[]){
ShareTypesTrue sharetypetrue = new ShareTypesTrue();
//Create object
ShareType shareType = new ShareType();
shareType.setShareTypeName("Original Name");
//Create list
List<ShareType> shareTypes=new ArrayList<ShareType>();
shareTypes.add(shareType);
//Attach it to share
sharetypetrue.setShareType(shareTypes);
//Print
for(ShareType shareTypesMember:sharetypetrue.shareType){
System.out.println(shareTypesMember.shareTypeName);
}
//Editing it.
for(ShareType shareTypesMember:sharetypetrue.shareType){
shareTypesMember.shareTypeName = "Updated Name";
}
//Print
for(ShareType shareTypesMember:sharetypetrue.shareType){
System.out.println(shareTypesMember.shareTypeName);
}
}
}
Use Sharetype class to set the shareTypeName
ShareType share = new ShareType();
share.setShareTypeName("name");
share.setNoOfShare("no");
share.setParValue("val");
List<ShareType> shareType = new ArrayList<ShareType>();
shareType.add(share);
use ShareTypesTrue to set Sharetype
ShareTypesTrue sharetrue = new ShareTypesTrue();
sharetrue.setShareType(shareType);//pass ShareType as list
If you want to set the 'name' in ShareType, what prevents you from doing the below:
class ShareTypeTrue_Extended extends ShareTypeTrue{
protected shareTypeName;
public ShareTypeTrue_Extended(String shareTypeName){this.shareTypeName=shareTypeName;}
public void setShareType(List<ShareType> shareType) {
for(ShareType s: shareType)s.setShareTypeName(this.shareTypeName);
super.setShareType(shareType);
}
}

Arraylist add object by setter

I have created ArrayList and make setter and getter for it.
In the other class i want to add objects in this array. But my code doesn't works. i think i need to add in method setter for array some other code..
public class DataVar {
private ArrayList<String> arrayLinks = new ArrayList<>();
public ArrayList<String> getArrayLinks() {
return arrayLinks;
}
public void setArrayLinks(ArrayList<String> arrayLinks) {
this.arrayLinks = arrayLinks;
}
}
//Here is another class
public class LinksAd {
public void getAllLinksAd() {
DataVar dataVar = new DataVar();
String link = "href";
dataVar.setArrayLinks(link) }}
Looking at your code you are trying to add a String type, where your code specifies that you are expecting an ArrayList. Assuming you just want to add a string to your arraylist the following will work:
public void setArrayLinks(String arrayLinks) {
this.arrayLinks.add(arrayLinks);
}
You can implement generic setter method.
This is DataVar class:
public class DataVar {
private List<String> itemList=new ArrayList<String>();
public List<String> getItemlist() {
return itemList;
}
public void setItemList(Object list) {
if (list.getClass().equals(String.class)) {
itemList.add((String)list);
}
else if (list.getClass().equals(ArrayList.class)) {
itemList = (ArrayList<String>)list;
}
else {
throw new Exception("Rejected type- You can set String or ArrayList");
}
}
}
And this is calling setter method example:
Main class:
public static void main(String[] args) {
List<String> exampleList = new ArrayList<String>();
exampleList.add("This example");
exampleList.add("belongs to");
String owner = "http://www.javawebservice.com";
DataVar dataVar = new DataVar();
dataVar.setItemList(exampleList);
dataVar.setItemList(owner);
for(String str:dataVar.getItemlist()){
System.out.println(str);
}
}
Output:
This example
belongs to
http://www.javawebservice.com
So, you can set ArrayList, also you can set String.
You could do a mehtod to add an Item like this:
public void addStringToList(String s)
{
arrayLinks.add(s);
}
In LinksAd you have to wirte:
dataVar.addStringToList(link);

jList not displaying data from custom model?

I'm trying to populate a JList through subclassing the AbstractListModel.I have looked through numerous places to try and find what I was doing wrong, but never managed to resolve the problem.So this class handles my GUI...
//View
public class central extends javax.swing.JFrame {
public central() {
initComponents();
list.addMouseListener(new abstracts.mouseActions(list));
}
public void setListModel(ListModel l ){
list.setModel(l);
}
// The rest are auto generated code for the interface, not relevant
Then is my middle class...
public class MainCtrl {
//View reference
private views.central mainFrame = new views.central();
//Model reference
private abstracts.ListData model = new abstracts.ListData();
/*All this was testing purposes and it worked
private DefaultListModel model = new DefaultListModel();
*/
private void showView(){
mainFrame.setListModel(model);
mainFrame.setVisible(true);
models.contact p2 = new models.contact("Alex", "Christopher","alex#hotmail.com","22","Def");
models.contact p1 = new models.contact("Joes", "Smith","joey#hotmail.com","33","Def");
model.addContact(p2);
model.addContact(p1);
/* def version
model.addElement(p2);
*/
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new MainCtrl().showView();
}
catch (Exception e) {
e.printStackTrace();
}
}
Then I have got the AbstractListModel implementation
public class ListData extends AbstractListModel {
//Store people info
private Vector<contact> people;
public ListData() {
people = new Vector<contact>();
}
public void addContact(contact newPerson){
people.add(newPerson);
int per = people.indexOf(newPerson);
fireIntervalAdded(this,0,getSize());
}
#Override
public contact getElementAt(int index){
return people.get(index);
}
#Override
public int getSize(){
return people.size();
}
#Override
protected void fireIntervalAdded(Object src, int index, int index2){
System.out.println(index2);
}
.....
I tested DefautListModel and it displayed the values, but when I incorporate a custom model it doesn't display ? Is there a extra step I'm missing ? Also mainCtrl is the main class...
Thanks could really use some help
Instead of
fireIntervalAdded(this,0,getSize());
in your addContact() put
fireContentsChanged(this,0,getSize());
listModel = new DefaultListModel();
listModel.addElement("Jane Doe");
listModel.addElement("John Smith");
listModel.addElement("Kathy Green");
list = new JList(listModel);
please refer this link it will help you
http://docs.oracle.com/javase/tutorial/uiswing/components/list.html

Categories