Hmmm... there are several possibilities. The one I like best offhand it to put the list of valid values in the Address class - let's switch that char[2] representation to
String for simplicity:
<code><pre>class Address {
...
public static final String[] validStates = {"AB", "AL", "AZ", ...};
public String state;
...
}</pre></code>
And then in the GUI, use a JList created thus:
<code><pre> JList stateField = new JList(Address.validStates);</pre></code>
It will populate the list of possible values using your list. The user will not be able to select any value other than a valid value, so no further validation should be necessary. Later you can retrieve the state string from within the GUI code using
<code><pre> address.state = (String)stateField.getSelectedValue();</pre></code>
Of course, there are lots of other things to figure out when you start using Swing
. But many of the components are designed for easy separation of the data from the GUI view of it (MVC paradigm).
For the more general problem, if you can't find a simple way to design the GUI so that invalid choices are impossible, then I'd recommend giving your data classes methods which can determine if a given input is valid, so that the GUI code can call these methods when deciding whether to accept a value. Say that you want to make sure the zip code is valid for the city & state combination selected. This may be a fairly elaborate bit of code, and it's logically associated with the data, not with the GUI. GUI code can be ugly enough without unrelated stuff cluttering it up. So put a method in Address:
<code><pre> public boolean isValidZip(int zip) {
// complex code which accesses this.state and this.city
// (which must have already been set)
}</pre></code>
or
<code><pre> public static boolean isValidZipCombo(String state, String city, int zip) {
// complex code using all three variables passed
}</pre></code>
Then your GUI validation code can be relatively simple looking:
<code><pre> int zipCandidate = zipField.getValue();
if (address.isValidZip(zipCandidate)) {
address.setZip(zipCandidate);
} else {
zipField.clear();
showMessage("Hey schmuck, your zip code didn't work.
");
}
</pre></code>
That's my opinion, anyway.