Create two RoundedFields, JTextField and JPasswordField

Ok, I have the following JTextField class. It creates a Rounded JTextField. Now I wanted to use the same setting for my JPasswordField, since I thought JPasswordField was inheriting from JTextField, I could do the following: JPasswordField new_field = new RoundField(SOME Parameters); but it was a big disaster. Any way to make 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); } } 

PS: It would be nice to move setText from the constructor, if necessary.

+4
source share
2 answers

InPursuit is right. You cannot solve your problem using inheritance.

But what about using Factory patern design. You would create an external class that takes care of all the user interface changes that you are currently RoundField in the constructor of your RoundField .

Example:

 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 of the duplication and get clarity.

To call a method, it is very simple:

 JPasswordField pf = BorderUtil.createTextField(yourPasswordField, "Text", 0, 0, 10, 10); 
+3
source

You cannot change the class that the jpasswordfield field inherits, so no, there is no way to do this without repeating the code.

+1
source

All Articles