Alex Buell wrote:
> I'm learning Java and I'm writing a number base calculator just like the
> one in Arachnophilia 5.2. It has four JTextFields, for binary, octal,
> decimal, and hexadecimal. The user can enter a number into any of these
> four fields and see the converted number in the other fields in real time,
> just as they type in the number.
>
> The problem I've run into is that trying to update the other fields often
> throws exceptions.
>
> What is the best way to do what I've got in mind?
A good way to do this is to link the models for the fields together,
perhaps this is already what you're doing. In this case, part of the
problem is that the various text fields' immediate models (each one a
Document instance) are really part of the view -- they present different
representations of the same underlying model, a number.
What I would probably do for your particular problem is write a custom
Document class whose instances could be used as the models for your text
fields. This class would be configurable with a particular number
radix, so that I would only need one class instead of several. (I.e. it
would replace your four (!) custom documents with one. It would handle
conversion of the underlying number into the correct display format,
validation of new input, and update of the underlying number. Then I
would write a class to encapsulate the underlying number, complete with
a listener API that the custom Documents would use to keep abreast of
changes to the number applied by any other instances using the same
number instance.
In comparison to your code, that replaces eight classes with two, and
relieves you from having to wire things together at the front end. It
prevents any fundamental data inconsistency because there is only one
copy of the number being represented. (There is still an issue
regarding getting the display to update everywhere when a change has
been made, but once you get that once it is solved for good.) It also
relieves the application from the tight coupling imposed by the
KeyListener implementations you are currently using -- with my suggested
approach any number of numeric fields displaying data in the same or
different bases could be supported without any class knowing about the
others. (The relevant _instance_ of the number class would know about
all the dependant instances of the Document classes, but that's it.)
John Bollinger