|
|
There are at least two ways we can optimize our bean.
-
First, we could pull in initial data for our three variables from a configuration
file, perhaps an XML file.
-
But we haven't really covered XML yet, much less file IO.
-
Needless to say, if you're feeling aggressive, here's what it should look
like:
File
f = new File(datasource.xml);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
Element root = doc.getRootElement();
-
Then we iterate through the children of root to find the XML elements of
interest. Again, let's save this discussion for a few weeks.
-
We really need to keep the data and the GUI separated. We could create
a GUI that interfaces with our database bean, but is a separate class.
There are still two ways to do this:
-
The GUI has buttons that simply set values in the database bean.
This is probably the best option because the data are not duplicated.
-
On the other hand, the GUI could be a bean as well.
-
It could have a local cache of data for display.
-
The database bean can register itself with the GUI bean as a listener,
and then listen for changes to properties.
-
When its setter methods are called on the GUI, it fires an event to the
database bean listener, and the database bean is updated as well.
-
Again, to avoid redundancy of data, Option 1 is probably our best bet.
It is also easiest to implement. But I chose Option 2, because there
are many times we want to have local caches, and this option further allows
us to demonstrate bound properties.
-
A side note when making GUI beans...
-
GUI beans are JPanels, but when we make a GUI form in an IDE, we make a
JFrame.
-
So..... I simply made a JFrame and then copy and pasted what I needed to
a traditional bean that extends JPanel. Granted, it took a
few attempts to get it to compile, but it is better than writing a GUI
from scratch!
DatabaseGUI
Database Bean (revised)
Screen Capture
Exercise
|