I have some functionality in my gui that updates a given text component over time. Ideally, I'd like it to accept anything that has a getText/setText
method. This is easily done with JTextField
and JTextPane
as they share the common parent class JTextComponent
(which hold the get/set methods). The issue comes in when I try to include JLabel
, as, unfortunately, it's get/setText
methods do not come from a common parent class or interface.
To solve this, I see two paths.
1:
create a common interface EditableText
, then have my own alias versions of JTextField
, JTextPane
, and JLabel
that implement the interface.
Ala:
public class MyJTextField extends JTextField implements EditableText {
}
My Issue with this is that I'm creating a ton of class bloat just so the compiler knows that I want to access two methods on these classes.
2:
Some kind of template pattern-ish thing that accepts a very general parent class and then casts it up to either a JLabel
or JTextComponent
.
Something along the lines of:
class JLabelImplementation {
private JLabel label;
public MyClass(JComponent componenet) {
this.label = (JLabel) component
}
}
class JTextComponentImplementation {
private JTextComponent textField;
public MyClass(JComponent componenet) {
this.textField = (JTextComponent) component
}
}
(Note: Haven't actually tried the above). So, again, the thing I don't like is that it's still three classes (base functionality + two implementation classes) just to accept an object.
My question is, is there a better way to handle this? Are any of my planned approached good?