I have a ListView, and every time the selection is changed, I want to call a class with this name. For example, if an element is called a "Text String", then the TextString class must be called. The code I have gives me an error saying The method insert(ArrayList<Element>) is undefined for the type Object ... Eclipse gives me a suggestion to pass the object as an Element, but it does nothing. The Element class is a superclass, and TextString will implement this class.
Here is the code that I still have:
elementList.itemsProperty().bind(listProperty); listProperty.set(FXCollections.observableArrayList(elementListItems)); elementList.setOnMouseClicked(new EventHandler<MouseEvent>() { public String selectedElement = "Text String"; @Override public void handle(MouseEvent event) { selectedElement = (String)elementList.getSelectionModel().getSelectedItem(); selectedElement = selectedElement.replace(" ", ""); Class<?> clazz; try { clazz = Class.forName("elements."+selectedElement); Constructor<?> ctor = clazz.getConstructor(); Object object = ctor.newInstance(); Method meth = clazz.getClass().getMethod("insert", new Class<?>[] { Canvas.class, ArrayList.class, GraphicsContext.class }); meth.invoke(object, canvas, objects, gc); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } });
Element.java
public abstract class Element { public String name; public String description; public Canvas canvas; public ArrayList<Element> objects; public GraphicsContext gc; void remove(){ } void toggle(){ } void setBounds(int x, int y, int w, int h){ } public abstract void insert(Canvas canvas, ArrayList<Element> objects, GraphicsContext gc); }
TextString.java
public class TextString extends Element { private GraphicsContext gc; TextString() { super(); this.name = "Text String"; this.description = "A literal readable string of text."; } @Override public void insert(Canvas canvas, ArrayList<Element> objects, GraphicsContext gc) { this.gc = gc; this.canvas = canvas; this.objects = objects; System.out.println("Text string created."); } }
How can I pass an object to any object selected in the list?
source share