When calling a method that adds an object to a collection in GWT I get a null pointer error. I have no idea why as everything I have done creates a very simple object (only contains a string). Here is the code that calls the function and the function:
public class PlantMenu extends VerticalPanel {
private Collection<PlantData> plantList;
private Collection<PlantData> newPlantData;
public PlantMenu() {
createPlants();
/*
for(Iterator<PlantData> i = plantList.iterator(); i.hasNext();) {
Window.alert(i.next().getPlantName());
}*/
}
public Collection<PlantData> createPlants() {
PlantData plant1 = new PlantData("Herbs");
PlantData plant2 = new PlantData("Flowers");
PlantData plant3 = new PlantData("Vegetable");
newPlantData.add(plant1);
newPlantData.add(plant2);
newPlantData.add(plant3);
return newPlantData;
}
}
It errors out (null pointer) when trying to add the first plant, this line:
PlantData plant1 = new PlantData("Herbs");
Any help appreciated :)
You didn't initialize your collections. Despite, you already told that its not on that line, but I doubt it. Showing a full exception stack would be much more helpful though. And the exception may occur in your PlantData constructor, but you didn't show it here.
You could do something like this,
private Collection<PlantData> plantList = new ArrayList<PlantData>();
private Collection<PlantData> newPlantData = new ArrayList<PlantData>();
I have used ArrayList, because generally we use ArrayList. Other implementation can also be used, according to the requirements.
You have not initialised your variables properly, this has nothing to do with GWT and is just basic Java. Here's a working version:
public class PlantMenu extends VerticalPanel {
private List<PlantData> plantList = new ArrayList<PlantData>();
private List<PlantData> newPlantData = new ArrayList<PlantData>();
public PlantMenu() {
createPlants();
for(PlantData plant : newPlantData) {
Window.alert(plant.getPlantName());
}
}
public List<PlantData> createPlants() {
newPlantData.add(new PlantData("Herbs"));
newPlantData.add(new PlantData("Flowers"));
newPlantData.add(new PlantData("Vegetable"));
return newPlantData;
}
}
As a side note, you shouldn't be extending VerticalPanel, but rather extending Composite and then using a vertical panel as your widget using setWidget(...);
Related
So basically im creating a list with a lot of information that i get from the user, and i need to display that "Estudiante" created on a list asside. So this is what i first tried, but it tells me that setListData is for arrays, so i tried other thing that i found that included the using .toArray(array) but that didnt work too.
Just to clarify what modelo is i copied this first code
public class VentanaEstudiante extends javax.swing.JFrame {
private Sistema modelo;
/**
* Creates new form VentanaEstudiante
*/
public VentanaEstudiante(Sistema unSistema) {
modelo = unSistema;
this.setSize(400, 280);
initComponents();
}
private void BotonCrearEstudianteActionPerformed(java.awt.event.ActionEvent evt) {
Estudiante unEst=new Estudiante(NombreEstudiante.getText(), Integer.parseInt(CedulaEstudiante.getText()),MailEstudiante.getText(), Integer.parseInt(NumeroEstudiante.getText()), Integer.parseInt(SemestreEstudiante.getText()));
modelo.agregarEstudiante(unEst);
ListaEstudiantesJ.setListData((modelo.getListaEstudiantes()).toArray());
Estudiante has a toString method, and the superclass, also does.
public String toString(){
return super.toString() + "Numero:" + this.getNumero() + "Semestre: " + this.getSemestre();
}
Here you have my lists and i only copied the listaEstudiantes methods because this are the ones im asking right now. This class Sistema, doesnt have any toString methods because i throught that this arraylist didnt needed one.
public class Sistema {
private ArrayList<Estudiante> listaEstudiantes;
private ArrayList<Docente> listaDocentes;
private ArrayList<Equipo> listaEquipos;
public Sistema(){
listaEstudiantes = new ArrayList<>();
listaDocentes= new ArrayList<>();
listaEquipos=new ArrayList<>();
}
public void agregarEstudiante(Estudiante unEstudiante){
listaEstudiantes.add(unEstudiante);
}
public ArrayList<Estudiante> getListaEstudiantes(){
return listaEstudiantes;
}
I need to use ArrayList in case you have something that may work better, i just need to use them
This whole project has a lot of showing Lists and sometimes i have to even let the user select things from them, something that i also dont know how to do but i dont know if i can ask more than one question here. The list is also going to need to refresh and all of that but i think i can handle that. Thanks
JList.setListData() has two variants, one expecting an array of elements, the other expecting a vector of elements.
Behind the scenes these two methods create an instance of an anonymous subclass of AbstractListModel and pass that instance to JList.setModel().
You can easily implement similar code for any List instance:
static <E> void setListData(JList<E> jList, List<? extends E> listData) {
jList.setModel(new AbstractListModel<E>() {
public int getSize() { return listData.size(); }
public E getElementAt(int i) { return listData.get(i); }
});
}
i have made a generic list class:
public class FahrzeugListe<T extends Fahrzeug> implements TableModel {
private T[] array;
private int nextFreeSlot = 0;
private List<TableModelListener> tableListener = new ArrayList<TableModelListener>();
public FahrzeugListe(int capacity){
array = (T[]) new Fahrzeug[capacity];
}
public void add (T o){
if(nextFreeSlot == array.length){
throw new IllegalStateException("Liste ist voll!");
}
array[nextFreeSlot] = o;
nextFreeSlot++;
for(TableModelListener l : tableListener){
l.tableChanged(new TableModelEvent(this)); /
}
}
Its ofc not the whole class, but i think, its the important part for my problem.
I have another class for making those "Fahrzeug"-objects, its e.g. a car or bus...
Those objects i add through a GUI into this list, and to my GUI i added a button, where i wanted to save this list to JSON, so, when i start my program again, i can take the information out of my list first and then work with it.
In my GUI class i implemented the following method for a button "Save":
private class SaveListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
String json = new Gson().toJson(fahrzeugListe);
System.out.println("The text, should be written in jason: " +json);
}
}
Somehow i get this error message:
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
Anybody can help me please? :)
private transient List<TableModelListener> tableListener = new ArrayList<TableModelListener>();
I added the keyword transient, and everything works fine now xD
I have a modest programming background, but I am totally green to Java. I inherited some Java code at work, and I am simply trying to call this list properly.
Assistance appreciated.
public class CallTestClassList {
try { <how do I properly call the list from TestClass?> }
}
public class TestClass {
public List TestList() {
String s = null;
List cData = new ArrayList();
String[] Warning = null;
String[] Error = null;
int flag = 0;
}
return cData;
}
new TestClass().TestList();
At least, that's what I assume is the answer since I don't know what sort of constructors TestClass has.
This class is where I want to call the arrays and set the arrays to empty within the parameters
public class ElectronicsEquipmentSupplier {
private int currentMonth;
private int currentYear;
private String rangeOfProducts;
private CustomerDetailsList details; //Contains the customer details array
private PurchaseOrderList pal; //Contains the purchase array
public ElectronicsEquipmentSupplier(int currentMonth, int currentYear,
String rangeOfProducts ) {
this.currentMonth = currentMonth;
this.currentYear = currentYear;
this.rangeOfProducts = rangeOfProducts;
}
}
This is the class where the array is created. It pulls information from a separate class called PurchaseOrder and then sets the list.
public class PurchaseOrderList {
private ArrayList<PurchaseOrder> purchaseCollection;
public PurchaseOrderList() {
purchaseCollection = new ArrayList<PurchaseOrder>();
}
The CustomerDetailsList class is essentially the same. Just not sure as to the best way to set the array to empty when called in the ElectronicsEquipmentSupplier.
Simply wrap the collection's own clear() method with a publicly-accessible method in your PurchaseOrderClass:
public class PurchaseOrderList {
private ArrayList<PurchaseOrder> purchaseCollection;
public PurchaseOrderList() {
purchaseCollection = new ArrayList<PurchaseOrder>();
}
//THIS IS THE IMPORTANT PART
public void clearPurchaseCollection() {
purchaseCollection.clear();
//You could also accomplish the same thing by reinitializing the list:
//purchaseCollection = new ArrayList<PurchaseOrder>();
}
}
Note however, that calling new PurchaseOrderList() already guarantees an empty purchaseCollection list, since you initialize it in the constructor that way.
So the only time you would need to call clearPurchaseCollection() is if you are reusing this object and want to clean it out first. Depending on the rest of your application, that may be necessary, but it may also just be simpler to throw away that instance and create a new PurchaseOrderList(). Totally depends on the situation.
I am currently writing a game for android where there are enemies that fly across the screen and then disappear, to be replaced by other enemies. Now, this happens very fast, and my code currently performs a lot of memory allocation and deallocation to create and delete these enemy objects, so I'm trying to find a way to optimize this. I got this Pool class implementation from a book on android game dev:
public class Pool<T> {
public interface PoolObjectFactory<T> {
public T createObject();
}
private final List<T> freeObjects;
private final PoolObjectFactory<T> factory;
private int maxObjects;
public Pool(PoolObjectFactory<T> factory, int maxObjects) {
this.maxObjects = maxObjects;
this.factory = factory;
freeObjects = new ArrayList<T>(maxObjects);
}
public T newObject() {
T object = null;
if (freeObjects.isEmpty()) {
object = factory.createObject();
} else {
object = freeObjects.remove(freeObjects.size() - 1);
}
return object;
}
public void free(T object) {
if (freeObjects.size() < maxObjects) freeObjects.add(object);
}
}
Now, the way to use this class is as follows:
PoolObjectFactory<Enemy> factory = new PoolObjectFactory<Enemy>() {
public Enemy createObject() {
return new Enemy();
}
};
Pool<Enemy> enemyPool = new Pool<Enemy>(factory, 50);
The obvious problem with this method is that you can't input any parameters to the createObject() method, thus forcing you to use classes that take no arguments in their constructor. This will force me to rewrite a lot of code since the Enemy class I'm using takes several different parameters. I can think of a couple of workarounds, like this one:
PoolObjectFactory<Enemy> factory = new PoolObjectFactory<Enemy>() {
public Enemy createObject(Object... args) {
return new Enemy((Float)args[0], (Float)args[1]);
}
};
Pool<Enemy> enemyPool = new Pool<Enemy>(factory, 50);
But it's error-prone and annoying to update. I could also initialize the Enemy object in the createObject() method with bogus values and then set them manually later, or I could create a Pool class for every single object but I would really prefer not doing that.
Any suggestions on how to improve this code? How do you fellow java game developers deal with pooling objects to avoid garbage collection? Thanks very much.
1) You should override the createObject function in your PoolObjectFactory.
2) You will need a initialize() function that actually sets the parameters for each EnemyObject. Just have the constructor for the EnemyObject call the initialize function. Then, when you get the object out of the pool, you should just call initialize with your parameters and it should work perfectly.