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); }
});
}
Related
I am trying to add an element to an ArrayList using user input. The problem is when I try add something and ask to list it, it doesn't show it in the list.
I thought it was a problem with the read method, but I am not sure if there is anything wrong with it. The other thing was the fact that the method for adding an element wasn't in a loop, I tried using a loop but it still wasn't working.
There is a movie class with a constructor that has the parameters for title, year, genre, price and a toString method.
Expected result: After adding a movie, it should list the movie added.
Actual result: The add method asks for input but when I use the list method it doesn't list what I added.
Here is the full Kiosk and Catalogue class for more context.
new Catalogue().addMovie();
You are creating a new Catalogue each time you want to add a Movie, and you are never referencing it.
Instead, add all your movies to the same Catalogue:
private void addMovie(Catalogue c) {
c.addMovie();
}
private void listMovie(Catalogue c) {
c.listMovie();
}
that's because of the 'new' keyword. you need to use singleton 'Catalogue' object here.
class Kiosk {
private static Catalogue catalogue;
public Catalogue getCatalogue() {
if(Objects.isNull(catalogue)){
catalogue = new Catalogue();
}
return catalogue; //will return singleton catalogue object
}
private void addMovie() {
getCatalogue().addMovie();
}
private void listMovie() {
getCatalogue().listMovie();
}
}
In Kiosk you must keep an instance of your catalogue.
I don't know where you plan to create the Catalogue instance so added 2 constructors:
public class Kiosk {
private Catalogue cat;
public Kiosk() {
this(new Catalogue());
}
public Kiosk(Catalogue catalogue) {
this.cat=catalogue;
}
private void addMovie() {
cat.addMovie();
}
private void listMovie() {
cat.listMovie();
}
}
The code snippet below is part of some code I am reading for an assignment but I cant understand the role of the copy variable in the snippet or what it does. I know its an instance of the Sample class, but why it is then assigned an ArrayList is not clear to me.
public class Sample implements Var{
private List lst1;
private List lst2;
public Sample() {
super();
}
public Sample(List lst1) {
this();
this.lst1 = lst1;
}
public List getLst1() {
return lst1;
}
public void setLst1(List lst1) {
this.lst1 = lst1;
}
#Override
public Var copy(){
Sample copy = new Sample(lst1);
copy.lst2 = new ArrayList(lst2);
return copy;
}
#Override
public void randomize(){
}
}
In fact the error message is explicit to show that you can't iterate over the variable copy because you haven't implemented the Iterable interface which allows you to do it. If you insist to loop over it and to have functions allowing you to do so: just visit this link Java Generics - Implementing the Iterable Interface where you can for exemple (if this is what you want) iterate over the elements of the two lists of an instance lst1 and lst2
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
Trying to get an understanding of generics in Java. I've created an ArrayList using non-generic methods and casting to print them out, everything works fine using the usual array.get(index) but when I use generics to create the list, the get method doesn't work. I can print the whole list just fine, but I want to pick out individual elements. I've tried a few different things which have made the code a little messy probably, so sorry about that. I know things could probably be done an easier way, I'm just trying to learn about Generics in Java and I ran into this issue. I've watched several different videos and found several examples, so I may be trying to put two concepts together the incorrect way. Tried researching, can't find the answer.
First class Generic.java is to create the generic ArrayList.
import java.util.ArrayList;
import java.util.List;
public class Generic<T> {
private ArrayList<T> data;
public Generic() {
data = new ArrayList<T>();
}
public void add(T element){
data.add(element);
}
//Not even sure if I need these get/set but I put them in there for testing
public ArrayList<T> getData() {return data;}
public void setData(ArrayList<T> data) {this.data = data;}
public String toString(){
return data.toString();
}
}
Second class is the main test class:
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List nonGenericList = new ArrayList();
nonGenericList.add("Enzo");
nonGenericList.add(458);
String nonGen1 = (String) nonGenericList.get(0);
Integer nonGen2 = (Integer) nonGenericList.get(1);
System.out.println(nonGen1);
System.out.println(nonGen2);
Generic<Object> genericList = new Generic<>();
genericList.add("Enzo");
genericList.add(458);
//This is where the .get(0) isn't working for me
System.out.println(genericList.get(0));
}
}
Thanks for any help!
Your Generic<T> class doesn't have the method get(int index), you should create the method if you want to call it...
Try adding this to your Generic<T> class
public T get(int index){
return data.get(index);
}
You can define get method like this in your Generic class:
public T get(int i) {return data.get(i);}
You do not have add method you have defined the getData() method,
so write
ArrayList a=genericList.getData();
System.out.println(a.get(0));
For my AP CompSci class, we're making a "Contacts" program to simulate using a virtual phonebook. The main class, Contacts is as follows.
public class Contacts extends ArrayList<Contact>
{
private ArrayList<Contact> contacts = new ArrayList<Contact>();
#Override
public boolean add(Contact c)
{
contacts.add(c);
Collections.sort(contacts);
return true;
}
public ArrayList<Contact> search(String name)
{
ArrayList<Contact> temp = new ArrayList<Contact>();
for(int i = 0; i<=contacts.size(); i++)
{
if(contacts.get(i).getName().equals(name))
{
temp.add(new Contact(name));
}
}
return temp;
}
}
As you can see, it extends ArrayList<Contact>. Contact is a simple object, composed of a String name and a 7-integer int num. The problem lies in the class ContactsFactory, where I loop through a text file to create a huge ArrayList of names.
public class ContactsFactory {
public static Contacts getContacts() throws FileNotFoundException {
String path = System.getProperty("user.dir");
Scanner s = new Scanner(new File(path + "\\src\\names.txt"));
Contacts contacts = new Contacts();
do {
contacts.add(new Contact(s.next()));
} while (s.hasNext());
s.close();
//print size to see anything added. It returns 0.
System.out.println(contacts.size());
return contacts;
}
}
However, when I implement the add() method for each name, not only does it seem not to add anything, but it returns no error. Even more interesting is that, as I found out when I put a print statement after every iteration, s.next() is no empty String. But the String(which experiences no issues being transferred from names.txt) is not added to contacts, and as a result, the ArrayList ends up empty with a size() of 0.
I think the error might be in the overridden Contacts.add() method, but I haven't been able to figure anything out. Can someone help me out? Thanks in advance.
I'm wondering why you extend ArrayList and additionally keep another copy of an ArrayList around. Besides the overwritten add (and size from azurefrog's answer), an ArrayList as well as the List interface offers a bunch of other methods - instead of overwriting all of them and delegating to the internal list, I would just rely on those methods and add the functionality I need:
public class Contacts extends ArrayList<Contact>
{
#Override
public boolean add(Contact c)
{
boolean result = super.add(c);
Collections.sort(this);
return result;
}
public ArrayList<Contact> search(String name)
{
// ...
}
}
By that you have a full-blown ArrayList and can extend it with what you need.
The other option is, to just kick out extends and just go for your own implementation of Contacts, utilizing the internal List as storage and not exposing it directly.
I think there is something wrong with your design.
I don't think you should extend ArrayList.
Because when you do it, your class IS an ArrayList, and also, you created an ArrayList object inside your class.
The thing is, when you called size, original ArrayList's size is being returned. Since you added the element to your ArrayList, the original is still empty.
You should use either delegation or inheritance, in this case you are mixing it both up.
Either implement java.util.List<Contact> (instead of extending ArrayList) and delegate every method call to the delegate (the class variable contacts)
OR
Remove the class variable contacts and use super.add() in your add method (instead of contacts.add()) and this instead of every other reference on contacts
I'm not sure how you read your file, but I seem to do just fine. In order to access the size of the contacts object in your factory, you need to call the 'size' method on the internal ArrayList instance variable, as opposed to calling on the 'contacts' object itself. In order to properly apply the 'size' method, it maybe that you need to override this method ('size') too.
Other than that, adding and retrieval seems fine. Check out the console output as well!
public class Contacts extends ArrayList<Contact>
{
private List<Contact> contacts = new ArrayList<Contact>();
#Override
public boolean add(Contact c)
{
contacts.add(c);
//Collections.sort(contacts);
return true;
}
#Override
public String toString()
{
return contacts.toString();
}
public List<Contact> getMyList()
{
return this.contacts;
}
public static void main(String[] args)
{
Contacts test=ContactsFactory.getContacts();
System.out.println(test.toString());
}
}
class ContactsFactory {
public static Contacts getContacts() {
String[] names={"A","B","C","D"};
int i=0;
Contacts contacts = new Contacts();
do {
System.out.println("Adding: "+names[i]);
contacts.add(new Contact(names[i]));
i++;
} while (i<names.length);
//print size to see anything added. It returns 0.
System.out.println(contacts.getMyList().size());
return contacts;
}
}
class Contact
{
String name;
#Override
public String toString()
{
return "Contact: "+this.name;
}
public Contact(String val)
{
this.name=val;
}
}
Output:
Adding: A
Adding: B
Adding: C
Adding: D
4
[Contact: A, Contact: B, Contact: C, Contact: D]