Is this the right approach to extends all Java Swing GUI with validation feature
While i am writing a GUI Swing App quite sometime ago, i have 开发者_C百科created 18 classes. Each extends a swing class( JTextField, JList, JTable, JTextArea and etc..) and every single one implements a similar interface for data access and validation.
I am having a problem on Lines of code, as it is getting too long to maintain; and part of the reason is because many codes are either duplicated or alot of silly condition likes "if" Textbox or "else if" JList on a validation class.
I wonder if there is any object oriented way to help structure the validation codes within an abstract class, that will be nice. all my 18 classes already extends its very own swing class, that means i am unable to extend another abstract class within the same file.
Ultimately, i wish to keep it simple, short total Lines of Codes, ease of understanding and try without using third party framework (as this may cause problem in the future).
We don't have that much context to go on, and honestly it sounds like you might have some overarching design problems, but there are a couple techniques you can use to clean up "parallel classes" like this. One is to keep the mapping of one to the other isolated to one area and create concrete validator classes based on the type of field.
Another option is the visitor pattern. You could have a ValidationVisitable
interface that each of your subclasses implement:
public interface ValidationVisitable {
public void acceptVisitor(ValidationVisitor visitor);
}
//... in your concrete subclass:
public void acceptVisitor(ValidationVisitor visitor) {
visitor.visit(this);
}
Then your visitor class would have overloads for each concrete type of component:
public class ValidationVisitor {
public void visit(MyTextField field) {
//validate MyTextField
}
public void visit(MyCheckBox cb) {
//validate MyCheckBox
}
}
I'm not sure what you've tried, but InputVerifier
was designed for this. It's no panacea from a human factors point of view, but it may help when applied judiciously and with reliable user feedback.
精彩评论