Implement methods of an implemented List to an ArrayList - java

I know what to do with my programming code, but I just don't know why we have to do it.
My ArrayList class implements a List<E> interface. This means I have to copy all methods in my List interface to my ArrayList class. This is to stop the error of my ArrayList class saying: "ArrayList is not abstract and does not override abstract method iterator(int)" error. Can someone explain that to me in more detail?
Also: When I used the auto correct in NetBeans it says statements after each method "throw new UnsupportedOperationException("Not supported yet.");". Why?
Here's my code:
public class ArrayList<E> implements List<E> {
private E[] elementData;
private int elementCount;
private int capacityIncrement;
private static final int INVALID_INDEX=-1;
private static final int DEFAULT_CAPACITY = 100;
public ArrayList() {
capacityIncrement = 0;
elementData = (E[]) new Object[DEFAULT_CAPACITY];
}
public ArrayList(int capacity) {
this.capacityIncrement = 0;
this.elementData = (E[]) new Object[capacity];
}
public ArrayList(int capacity, int increment) {
this.capacityIncrement = increment;
this.elementData = (E[]) new Object[capacity];
}
private static class ArrayListIterator<E> implements Iterator<E> {
private ArrayListIterator(ArrayList c) {
elementData = c;
}
public interface List<E> {
public int size();
public boolean isEmpty();
public void clear();
public boolean contains(E element);
public void add(E element);
public boolean remove(E element);
public E elementAt(int index);
public int indexOf(E element);
public void insertElementAt(E element, int index);
public void removeElementAt(int index);
public void setElementAt(E element, int index);
public void removeDuplicates();
public void trimToSize();
public Iterator<E> iterator();
public Iterator<E> iterator(int index);
public String toString();
}

Since you implement an interface, you must implement all of the methods it declares (unless your class is abstract). Have a look at the Java tutorial trail on inheritance.

An interface is a contract that states that certain functionality will be provided by any class that implements it. That's done by specifying each of the method signatures (but, generally, no method bodies - so there's no actual implementation logic). So, if you have a class that implements that interface, you have to provide implementations for each of the methods so that your class fulfills that contract.

You implement the interface List so you need to implement all method which are defined in this interface. The exception says you should add the method iterator() to ArrayList.
An interface is like a contract which you (your class) sign(s). You have to fulfill everything which is defined in the contract or in other words you need to implement every (abstract) method from the interface.
Edit: I cleaned up the code and now the only thing you have to do is to implement every method with a // TODO comment in it.
public class ArrayList<E> implements List<E> {
private Object[] elementData;
private int elementCount;
private int capacityIncrement;
private static final int INVALID_INDEX = -1;
private static final int DEFAULT_CAPACITY = 100;
public ArrayList() {
capacityIncrement = 0;
elementData = new Object[DEFAULT_CAPACITY];
}
public ArrayList(int capacity) {
this.capacityIncrement = 0;
this.elementData = new Object[capacity];
}
public ArrayList(int capacity, int increment) {
this.capacityIncrement = increment;
this.elementData = new Object[capacity];
}
#Override
public int size() {
// TODO Auto-generated method stub
return 0;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
#Override
public void clear() {
// TODO Auto-generated method stub
}
#Override
public boolean contains(E element) {
// TODO Auto-generated method stub
return false;
}
#Override
public void add(E element) {
// TODO Auto-generated method stub
}
#Override
public boolean remove(E element) {
// TODO Auto-generated method stub
return false;
}
#Override
public E elementAt(int index) {
// TODO Auto-generated method stub
return null;
}
#Override
public int indexOf(E element) {
// TODO Auto-generated method stub
return 0;
}
#Override
public void insertElementAt(E element, int index) {
// TODO Auto-generated method stub
}
#Override
public void removeElementAt(int index) {
// TODO Auto-generated method stub
}
#Override
public void setElementAt(E element, int index) {
// TODO Auto-generated method stub
}
#Override
public void removeDuplicates() {
// TODO Auto-generated method stub
}
#Override
public void trimToSize() {
// TODO Auto-generated method stub
}
#Override
public Iterator<E> iterator() {
// TODO Auto-generated method stub
return null;
}
#Override
public Iterator<E> iterator(int index) {
// TODO Auto-generated method stub
return null;
}
protected class ArrayListIterator<T> implements Iterator<T> {
private ArrayList<T> list;
private ArrayListIterator(ArrayList<T> list) {
this.list = list;
}
#Override
public boolean hasNext() {
// TODO Auto-generated method stub
return false;
}
#Override
public T next() {
// TODO Auto-generated method stub
return null;
}
#Override
public void remove() {
// TODO Auto-generated method stub
}
}
}
interface List<T> {
public int size();
public boolean isEmpty();
public void clear();
public boolean contains(T element);
public void add(T element);
public boolean remove(T element);
public T elementAt(int index);
public int indexOf(T element);
public void insertElementAt(T element, int index);
public void removeElementAt(int index);
public void setElementAt(T element, int index);
public void removeDuplicates();
public void trimToSize();
public Iterator<T> iterator();
public Iterator<T> iterator(int index);
public String toString();
}

Since you are saying that your class "implements List", it must implement all methods defined in the List interface. An interface is like an abstract specification for your class, specifying what your class can do (its methods) without giving an details about what your class contains/how it does its work

Related

Javafx right click edit listView item and similar methods

I am building a JavaFX todo list and am not sure how to continue. The right click popup menu works fine but I am not sure how to edit/change the contents of the ListView other than just removing them.
LocalEvent e = a string somehow?
I am trying to do 4 total things in a right click popup menu in Javafx:
Done is to place a check mark next to and strikeout the item.
Nest is to create a nested list from a list item (no idea at all how).
Edit is to make the list item editable and save the chages.
Remove works :)
I have done this by adding the following to the fxml file:
<JFXListView fx:id="eventList" editable="true" layoutX="24.0" layoutY="106.0" prefHeight="354.0" prefWidth="939.0">
<contextMenu>
<ContextMenu>
<items>
<MenuItem fx:id="popUp" mnemonicParsing="false" onAction="#Done" text="Done" />
<MenuItem fx:id="popUp3" mnemonicParsing="false" onAction="#Remove" text="Remove" />
<MenuItem fx:id="popUp1" mnemonicParsing="false" onAction="#Nest" text="Nest" />
<MenuItem fx:id="popUp2" mnemonicParsing="false" onAction="#Edit" text="Edit" />
</items>
</ContextMenu>
</contextMenu></JFXListView>`
Here is my Controller.java file:
package application;
import java.net.URL;
import java.time.LocalDate;
import java.util.ResourceBundle;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXListView;
import com.jfoenix.controls.JFXTextField;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.DatePicker;
import javafx.scene.control.MenuItem;
import javafx.scene.input.MouseEvent;
public class Controller implements Initializable{
#Override
public void initialize(URL url, ResourceBundle rb) {
datePicker.setValue(LocalDate.now());
eventList.setExpanded(true);
eventList.depthProperty().set(1);
}
#FXML
private MenuItem popUp;
#FXML
private JFXTextField textBox;
#FXML
private JFXListView<LocalEvent> eventList;
ObservableList<LocalEvent> list = FXCollections.observableArrayList();
#FXML
private JFXButton AddButton;
#FXML
private DatePicker datePicker;
#FXML
void Submit(ActionEvent event) {
list.add(new LocalEvent(datePicker.getValue(), textBox.getText()));
eventList.setItems(list);
datePicker.setValue(LocalDate.now());
textBox.setText("");
}
#FXML
public void onEnter(ActionEvent event){
list.add(new LocalEvent(datePicker.getValue(), textBox.getText()));
eventList.setItems(list);
datePicker.setValue(LocalDate.now());
textBox.setText("");
}
#FXML
void Done(ActionEvent event) {
int index = eventList.getSelectionModel().getSelectedIndex();
String str = list.get(index).toString();
str = "[✓] " + str;
LocalEvent e = null; // <- how to put a string in here?
list.set(index, e);
eventList.setItems(list);
//eventList.setItems(list.set(index, element));
}
#FXML
void Remove(ActionEvent event) {
// remove selected task
list.remove(eventList.getSelectionModel().getSelectedIndex());
}
#FXML
void Nest(ActionEvent event) {
System.out.println("How the hell do I do that? lol");
// check for nested level
// create a nested list item
}
#FXML
void Edit(ActionEvent e) {
System.out.println("Edit selection");
eventList.setEditable(true);
int index = eventList.getSelectionModel().getSelectedIndex();
eventList.scrollTo(index);
eventList.layout();
eventList.edit(index);
eventList.layout();
}
}
LocalEvent is a java class file as follows:
package application;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javafx.beans.InvalidationListener;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
public class LocalEvent implements ObservableList<LocalEvent> {
private String description;
private LocalDate date;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public LocalEvent(LocalDate date, String description) {
this.setDate(date);
this.setDescription(description);
}
#Override
public String toString() {
return "At " + this.getDate() + ": " + this.getDescription();
}
#Override
public int size() {
// TODO Auto-generated method stub
return 0;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean contains(Object o) {
// TODO Auto-generated method stub
return false;
}
#Override
public Iterator<LocalEvent> iterator() {
// TODO Auto-generated method stub
return null;
}
#Override
public Object[] toArray() {
// TODO Auto-generated method stub
return null;
}
#Override
public <T> T[] toArray(T[] a) {
// TODO Auto-generated method stub
return null;
}
#Override
public boolean add(LocalEvent e) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean remove(Object o) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean containsAll(Collection<?> c) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean addAll(Collection<? extends LocalEvent> c) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean addAll(int index, Collection<? extends LocalEvent> c) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean removeAll(Collection<?> c) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean retainAll(Collection<?> c) {
// TODO Auto-generated method stub
return false;
}
#Override
public void clear() {
// TODO Auto-generated method stub
}
#Override
public LocalEvent get(int index) {
// TODO Auto-generated method stub
return null;
}
#Override
public LocalEvent set(int index, LocalEvent element) {
// TODO Auto-generated method stub
return null;
}
#Override
public void add(int index, LocalEvent element) {
// TODO Auto-generated method stub
}
#Override
public LocalEvent remove(int index) {
// TODO Auto-generated method stub
return null;
}
#Override
public int indexOf(Object o) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int lastIndexOf(Object o) {
// TODO Auto-generated method stub
return 0;
}
#Override
public ListIterator<LocalEvent> listIterator() {
// TODO Auto-generated method stub
return null;
}
#Override
public ListIterator<LocalEvent> listIterator(int index) {
// TODO Auto-generated method stub
return null;
}
#Override
public List<LocalEvent> subList(int fromIndex, int toIndex) {
// TODO Auto-generated method stub
return null;
}
#Override
public void addListener(InvalidationListener listener) {
// TODO Auto-generated method stub
}
#Override
public void removeListener(InvalidationListener listener) {
// TODO Auto-generated method stub
}
#Override
public void addListener(ListChangeListener<? super LocalEvent> listener) {
// TODO Auto-generated method stub
}
#Override
public void removeListener(ListChangeListener<? super LocalEvent> listener) {
// TODO Auto-generated method stub
}
#Override
public boolean addAll(LocalEvent... elements) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean setAll(LocalEvent... elements) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean setAll(Collection<? extends LocalEvent> col) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean removeAll(LocalEvent... elements) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean retainAll(LocalEvent... elements) {
// TODO Auto-generated method stub
return false;
}
#Override
public void remove(int from, int to) {
// TODO Auto-generated method stub
}
}
Any help at all appreciated.
The first thing that stands out was mentioned in the comments: your LocalEvent shouldn't implements ObservableList, it's just a data holder. You probably will want it to also hold a boolean to see if it's completed:
public class LocalEvent {
private String description;
private LocalDate date;
private boolean completed = false;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public void setCompleted(boolean completed) {
this.completed= completed;
}
public LocalEvent(LocalDate date, String description) {
this.setDate(date);
this.setDescription(description);
}
#Override
public String toString() {
String base = "At " + this.getDate() + ": " + this.getDescription();
return completed ? "[✓] " + base : base;
}
}
I don't know what the jfoenix controls are, but I'll assume they are close enough to JavaFX standard controls. The ListView should be bound to the list of events:
ObservableList<LocalEvent> list = FXCollections.observableArrayList();
ListView<LocalEvent> eventList = new ListView<>(list);
(I would also rename the lists to something that makes more sense.)
Now any change to list will be reflected in eventList so you don't need to touch eventList. This allows your done method to look like:
#FXML
void done(ActionEvent event) {
int index = eventList.getSelectionModel().getSelectedIndex();
LocalEvent localEvent = list.get(index);
localEvent.setCompleted(true);
list.set(index, localEvent);
}
Note that we needed to reset the item in the list because it doesn't know that a field of the LocalEvent instance has changed. You can make it that the fields also report changes by using an extractor, see here and many other answers here about it.
Editing depends on the cell used by the ListView, I would suggest reading about it in the docs and other questions here. Note that you probably want to be able to edit the description and date separately and not the whole toString value, so you'll have to provide a mechanism for that like bringing back the DatePicker.
Nesting depends on what you want it to look like. You might need to define your own cell factory, but consider just adding an indentation, via "\t"s, which will make it looks nested. If you really need a nesting in the data model, then each LocalEvent will have to hold its own ObservableList<LocalEvent> nestedEvents.
Also, method names should start with a lowercase.

How to call methods within my abstract class that implements an imported interface?

Right now, I have a class 'Bag' that implements an imported interface 'USet'
My class 'Bag' is as follows:
package Bag;
import java.util.Iterator;
public class Bag implements USet<Integer>{
#Override
public Iterator<Integer> iterator() {
// TODO Auto-generated method stub
return null;
}
#Override
public int size() {
// TODO Auto-generated method stub
return 0;
}
#Override
public boolean add(Integer x) {
// TODO Auto-generated method stub
return false;
}
#Override
public Integer remove(Integer x) {
// TODO Auto-generated method stub
return null;
}
#Override
public Integer find(Integer x) {
// TODO Auto-generated method stub
return null;
}
#Override
public void clear() {
// TODO Auto-generated method stub
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Bag<Integer> myBag=new USet<Integer>();
}
}
I cannot call my class or access methods within it in my main. Simply put, I just want to add, remove integers in my Bag and create my own method of sorting them. However, since this is an abstract interface, it seems I cannot just call this. Is there a work around?
For reference, my imported USet is:
package Bag;
public interface USet<T> extends Iterable<T> {
public int size();
public boolean add(T x);
public T remove(T x);
public T find(T x);
public void clear();
}
Here is the code that does that. I believe it is quite simple so there is no need for an explanation.
package Bag;
import bag.USet;
import java.util.Iterator;
public class Bag implements USet<Integer> {
#Override
public Iterator<Integer> iterator() {
System.out.println("iterator called.");
return null;
}
#Override
public int size() {
System.out.println("size called.");
return 0;
}
#Override
public boolean add(Integer x) {
System.out.println("add called with " + x);
return false;
}
#Override
public Integer remove(Integer x) {
System.out.println("remove called with " + x);
return null;
}
#Override
public Integer find(Integer x) {
System.out.println("find called with " + x);
return null;
}
#Override
public void clear() {
System.out.println("clear called ");
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Bag myBag = new Bag();
myBag.add(1);
myBag.add(2);
myBag.add(3);
int size = myBag.size();
}
}
NB:
Looking at the code of your USet, I am thinking you intend to have special Set of Integers. If this is the case, then the code of your USet is not even a collection but a special Iterator. To make it be a collection you either extend the Collection interface, or Set specifically. In your case I believe its a Set you want. So your code should be like below.
package bag;
import java.util.HashSet;
public abstract class USet2 extends HashSet<Integer> {
}
and
package bag;
import java.util.Collection;
import java.util.Iterator;
public class Bag2 extends USet2 {
public Bag2() {
super();
}
#Override
public int size() {
return super.size();
}
#Override
public boolean isEmpty() {
return super.isEmpty();
}
#Override
public boolean contains(Object o) {
return super.contains(o);
}
#Override
public Iterator<Integer> iterator() {
return super.iterator();
}
#Override
public Object[] toArray() {
return super.toArray();
}
#Override
public <T> T[] toArray(T[] a) {
return super.toArray(a);
}
#Override
public boolean add(Integer e) {
return super.add(e);
}
#Override
public boolean remove(Object o) {
return super.remove(o);
}
#Override
public boolean containsAll(Collection<?> c) {
return super.containsAll(c);
}
#Override
public boolean addAll(Collection<? extends Integer> c) {
return super.addAll(c);
}
#Override
public boolean removeAll(Collection<?> c) {
return super.removeAll(c);
}
#Override
public boolean retainAll(Collection<?> c) {
return super.retainAll(c);
}
#Override
public void clear() {
super.clear();
}
}

anonymous inner class interface

I have this LinkedListDouble class which has the public ListIterator<T>listIterator() method,and I'm trying to execute the interface ListIterator as it's anonymous inner class,am I going the right path?what should I do to make the public int nextIndex()/public int previousIndex() work?
nextIndex method returns the index of the element that would be returned by a subsequent call to next, or list size if the list iterator is at the end of the list and the previousIndex method returns the index of the element that would be returned by a subsequent call to previous, or -1 if the list iterator is at the beginning of the list as it said here
here is the LinkedListDouble class
public class LinkedListDouble <T> {
private Node first = null;
private Node last = null;
public LinkedListDouble () // constructor
{
first = null; // no items on list yet
last = null;
}
public void add(T item) {
Node newNode = new Node(item);
if (isEmpty()) {
first =newNode;
last = newNode;
}
else {
//first.setPrev(newNode);
//newNode.setNext(first);
//first = newNode;
last.setNext(newNode);
newNode.setPrev(last);
last=newNode;
}
}
public boolean contains(T item){
if(first==null)
return false;
else
{
Node newNode=first;
while(newNode!=null)
{
if(newNode.getInfo().equals(item))
return true;
else
newNode=newNode.getNext();
}
}
return false;
}
public T remove(T item)
{//get care of first and last nodes
//and if there is more than 1 matching
boolean check=contains(item);
if(check==true)
{
Node newNode=first;
while(newNode!=null)
{
if(newNode.getInfo().equals(item))
{
newNode.getPrev().setNext(newNode.getNext());
newNode.getNext().setPrev(newNode.getPrev());
return item;
}
else
newNode=newNode.getNext();
}
}
return null;
}
public int size()
{
int size=0;
if(first==null)
return size;
else
{
Node newNode=first;
while(newNode!=null)
{
size++;
newNode=newNode.getNext();
}
}
return size;
}
public String toString()
{
Node newNode=first;
String s="";
while(newNode!=null)
{
s+=newNode.getInfo()+" ,";
newNode=newNode.getNext();
}
return s;
}
public boolean isEmpty() {
return first == null;
}
and here is the method that should execute the interface ListIterator as it's anonymous inner class and what I tried to do so far:
public ListIterator<T>listIterator()
{
ListIterator<T>listIterator = new ListIterator<T>() {
private Node current = first;
private Node temp2 = null;
private int curindex = 0;
#Override
public void add(T e) {
// TODO Auto-generated method stub
throw new RuntimeException();
}
#Override
public boolean hasNext() {
// TODO Auto-generated method stub
boolean flag=true;
if(current.getNext()==null)
{
flag=false;
}
return flag;
}
#Override
public boolean hasPrevious() {
// TODO Auto-generated method stub
boolean flag=true;
if(current.getPrev()==null)
{
flag=false;
}
return flag;
}
#Override
public T next() {
// TODO Auto-generated method stub
if (!hasNext()) throw new NoSuchElementException();
temp2=current.getNext();
current=current.getNext();
return (T) temp2.getInfo();
}
#Override
public int nextIndex() {
// TODO Auto-generated method stub
int counter=0;
if(!hasNext()) return size();
return curindex;
}
#Override
public T previous() {
// TODO Auto-generated method stub
if (!hasPrevious()) throw new NoSuchElementException();
temp2 = current.getPrev();
temp2 = temp2.getPrev();
return (T) temp2.getInfo();
}
#Override
public int previousIndex() {
// TODO Auto-generated method stub
int counter=0;
if(!hasPrevious()) return -1;
return curindex-1;
}
#Override
public void remove() {
// TODO Auto-generated method stub
throw new RuntimeException();
}
#Override
public void set(T e) {
// TODO Auto-generated method stub
throw new RuntimeException();
}
};
return listIterator;
}
This is a code sample from listIterator() method of LinkedList:
public E next() {
//check for modification
if (!hasNext())
throw new NoSuchElementException();
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.item;
}
public E previous() {
//check for modification
if (!hasPrevious())
throw new NoSuchElementException();
lastReturned = next = (next == null) ? last : next.prev;
nextIndex--;
return lastReturned.item;
}
public int nextIndex() {
return nextIndex;
}
public int previousIndex() {
return nextIndex - 1;
}
As you can see, you need to keep an variable like index to keep the track of next index.
The next index is incremented/decremented inside next() and previous() method and these methods already handles List size issue, hence no need to worry about size issue in nextIndex() and previousIndex() method.

JCombobox using hasmap/ no point model

Hey i am looking for solving a problem i need to make a model for jcombobox.
I have a :
Map<Integer, Pathes_format> profiles =new HashMap<Integer, Pathes_format>();
I wana to show on jcombobox pathes_format.getname will be displayed at index pathes_format.GetiD i never wrote or touch a abstract class or models.
Here what i made
package subDialogs;
import java.util.HashMap;
import java.util.Map;
import javax.swing.ComboBoxModel;
import javax.swing.event.ListDataListener;
import json.Pathes_format;
public class PatheseModel implements ComboBoxModel {
Map<Integer, Pathes_format> profiles =new HashMap<Integer, Pathes_format>();
int index=-1;
#Override
public int getSize() {
// TODO Auto-generated method stub
return profiles.size();
}
#Override
public Object getElementAt(int index) {
// TODO Auto-generated method stub
return profiles.get(index);
}
#Override
public void addListDataListener(ListDataListener l) {
// TODO Auto-generated method stub
}
#Override
public void removeListDataListener(ListDataListener l) {
// TODO Auto-generated method stub
}
#Override
public void setSelectedItem(Object anItem) {
// TODO Auto-generated method stub
}
#Override
public Object getSelectedItem() {
// TODO Auto-generated method stub
return null;
}
//void addElement(Object obj){
//
//}
void insertElementAt(Object obj, int index) {
profiles.put(index, (Pathes_format) obj);
}
void removeElement(Object obj) {
Pathes_format tmp = profiles.get(obj);
tmp=null;
}
void removeElementAt(int index){
profiles.remove(index);
}
}
I don't know is this correct :/. Mby i should make for a format patches single not for map; and add ability to add map??

java jlist - AbstractListModel - fireContentsChanged does not work properly

I have a simple ListModel, that is filterable and is used in a JList...
It uses the following code...
public class FilteredListModel extends AbstractListModel
{
private List<LineData> data = null;
private final ArrayList<Integer> indices = new ArrayList<Integer>();
public FilteredListModel()
{
}
public void setData(List<LineData> data)
{
this.data = data;
doFilter();
}
public void doFilter()
{
int oldSize = indices.size();
indices.clear();
if (data != null)
{
int count = data.size();
for (int i = 0; i < count; i++)
{
IFiltererListObject element = (IFiltererListObject) data.get(i);
if (element.isVisible())
indices.add(i);
}
}
fireContentsChanged(this, 0, getSize() - 1);
if (oldSize > getSize())
fireIntervalRemoved(this, getSize(), oldSize - 1);
}
#Override
public int getSize()
{
return indices.size();
}
#Override
public Object getElementAt(int index)
{
return data.get(indices.get(index));
}
#Override
public void addListDataListener(ListDataListener l)
{
// TODO Auto-generated method stub
//doFilter();
}
#Override
public void removeListDataListener(ListDataListener l)
{
// TODO Auto-generated method stub
//doFilter();
}
}
The strange thing about it is, that it is not working, just if I click for example outside the window, the JList with the ListModel get's correctly updated...
What am I missing here?
The problem is that the addListDataListener and removeListDataListener methods are empty. This means the JList can no longer attach its listener to the model. The call fireContentsChanged will do nothing, as the super class isn't aware of any listeners.
Either do not override those methods, or make sure you call super.addListDataListener as well.
#Robin please DYM???
import java.util.ArrayList;
import javax.swing.AbstractListModel;
import javax.swing.MutableComboBoxModel;
//usage == new JComboBox(new SectionComboBoxModel(new ArrayList());
public class SectionComboBoxModel extends AbstractListModel implements MutableComboBoxModel {
private static final long serialVersionUID = 1L;
private Object selectedItem;
private ArrayList<Object> sections;
public SectionComboBoxModel(ArrayList<Object> arrayList) {
sections = arrayList;
}
#Override
public Object getSelectedItem() {
return selectedItem;
}
#Override
public void setSelectedItem(Object newValue) {
selectedItem = newValue;
}
#Override
public int getSize() {
return sections.size();
}
#Override
public Object getElementAt(int i) {
return sections.get(i);
}
public void setElementAt(Object newValue, int i) {
this.fireContentsChanged(newValue, i, i);
this.sections.set(i, newValue);
}
#Override
public void addElement(Object obj) {
sections.add(obj);
this.fireIntervalAdded(obj, this.getSize() - 1, this.getSize() - 1);
}
#Override
public void removeElement(Object obj) {
this.fireIntervalRemoved(obj, sections.indexOf(obj), sections.indexOf(obj));
sections.remove(obj);
}
#Override
public void insertElementAt(Object obj, int index) {
sections.add(index, obj);
this.fireIntervalAdded(obj, index, index);
}
#Override
public void removeElementAt(int index) {
this.fireIntervalRemoved(sections.get(index), index, index);
sections.remove(index);
}
public void print() {
System.out.println("\nPrinting List");
for (int i = 0; i < this.sections.size(); i++) {
System.out.println(this.sections.get(i));
}
}
public boolean contains(Object o) {
return sections.contains(o);
}
public Object[] toArray() {
return this.sections.toArray();
}
}

Categories

Resources