Adding unknown subclass
I am developing a multi touch desktop in java, just for the fun of it,
and i would like to add widgets to the desktop.
I have thought about it, and cant find a way to do it.
I have created a class, Widget, that every widget should descent from, if they want to be added to the Desktop.
I could do it this way:
Widget w = new Widget();
w.addComponent(new Button("Bla bla"));
but then i cant use graphics, without adding the graphic to the Widgets "add" method as components that got graphic via paintComponent.
What i would like to be able to, is subclassing Widget,
add the core graphics with paintComponent and then add the buttons, scrollers and so forth.
But then i cant have a list of Widgets, without recompiling every time i have made a new widget or what.
Could someone please try and explain how i can, should, may do this?
public class Widget extends JPanel
public class Widget extends Container
make an interface or abstract class
public class myWidget extends Widget
public void paintComponent(Graphics g)
Yeah i know how to extend a class, but that was not my question :)
Let me try an explain:
I have a desktop (Desktop extends JFrame).
I press a button on the desktop, to bring up a list of widgets (a JPanel with an ArrayList of Widgets. The list is display either with a component or graphicly).
In that list, there is a button to add another Widget ( which subclass is unknown, but extends Widget).
How do i update the list on the fly, with the new unkwown Widget in the list.
The desktop should be able to add the widget to, but then it needs to import the widget, but how, when the desktop is viewed at at the moment.
The desktop app can not be restarted, cause that would ruin the way a desktop behaves.
Does this make any sense and is it possible?
I can think of a number of approaches to this. :)
You can have a Thread that checks at some interval the list of components attached the Desktop (JFrame) that are an instanceof Widget which then updates the list and tells the panel to update it's view.
Or, you could setup a listener that listens for add widget event. When the event is fired the Widget-display-panel would then update with the change.
It just really depends on how you structured things.
It sounds like you want dynamic loading of class files. I Googled "java dynamic class loading" and got pointers to several blogs describing how to dynamically load classes.
I also did a little googling myself, and found something about reflection.
After a couple of hours, i got a working widget loader.
So now the widget list finds the widgets in a given folder, list the names, and when the user clicks on a name, an instance of the widget is returned, as Widget, so that the desktop can add the widget, without knowing what the subclass name is :)
Thank you guys very for your answers