Creating two RoundedFields, JTextField and JPasswordField
inheritance, java, multiple-inheritance
Solution
InPursuit is right. You can't solve your problem using inheritance.
But what about using a Factory design patern instead. You would create an external class that would take care of all the UI modification that you currently do in the constructor of your `RoundField`.
Ex:
class BorderUtil {
@SuppressWarnings({ "unchecked", "serial" })
public static <T extends JTextField> T createTextField(T field, String text, int x, int y, int width,
int height) {
T f = null;
if (field instanceof JPasswordField) {
f = (T) new JPasswordField(text) {
@Override
protected void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRoundRect(0, 0, getWidth(), getHeight(), 8, 8);
super.paintComponent(g);
}
};
} else {
f = (T) new JTextField(text) {
@Override
protected void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRoundRect(0, 0, getWidth(), getHeight(), 8, 8);
super.paintComponent(g);
}
};
}
f.setBounds(x, y, width, height);
f.setForeground(Color.GRAY);
f.setHorizontalAlignment(JTextField.CENTER);
f.setOpaque(false);
f.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4));
return f;
}
}
This way, you avoid most duplication and you gain in clarity.
To invoke the method, it's really easy:
JPasswordField pf = BorderUtil.createTextField(yourPasswordField, "Text", 0, 0, 10, 10);
Problem
Okay I have the following JTextField class. It creates a Rounded JTextField. Now I wanted to use the same setup for my JPasswordField since I thought that JPasswordField inherits from JTextField I could do the following : `JPasswordField new_field = new RoundField(SOME Parameters);` but that has been a big disaster. Any way to make the JPasswordField rounded without repeating code? ``` public class RoundField extends JTextField { public RoundField(String text, int x, int y, int width, int height) { setText(text); setBounds(x, y, width, height); setForeground(Color.GRAY); setHorizontalAlignment(JTextField.CENTER); setOpaque(false); setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4)); } protected void paintComponent(Graphics g) { g.setColor(getBackground()); g.fillRoundRect(0, 0, getWidth(), getHeight(), 8, 8); super.paintComponent(g); } } ``` P.S: It would be okay to move setText out of the constructor if necessary.