How to refactor these two nearly idential classes?
I have two classes with a lot of identical code. One class extends JLabel and the other class extends JTextField.
Normally I'd push the identical code up to a superclass. However in this case I can't do that because I don't control those classes.
Is there an alternative way to properly refactor out the duplicate code here?
ViewLabel
package Screen;import java.awt.Color;import java.awt.event.FocusEvent;import java.awt.event.FocusListener;import javax.swing.BorderFactory;import javax.swing.JLabel;import javax.swing.border.Border;public class ViewLabel extends JLabel implements FocusListener { private static final long serialVersionUID = 1L; //CONSTRUCTOR public ViewLabel() { this(" "); } public ViewLabel(String s) { super(s); this.setBorder(null); this.setOpaque(true); this.setForeground(Color.BLACK); this.setBackground(Color.WHITE); Border border = BorderFactory.createLineBorder(Color.BLUE, 5); this.setBorder(border); //this.setBorder(null); //DWD set border for testing on/off this.addFocusListener(this); } public void setFieldHighlighting(Color foreground, Color background) { this.setForeground(foreground); this.setBackground(background); } public void highlightField() { setFieldHighlighting(Color.WHITE, Color.BLACK); } public void unhighlightField() { setFieldHighlighting(Color.BLACK, Color.WHITE); } @Override public void focusGained(FocusEvent e) { highlightField(); } @Override public void focusLost(FocusEvent e) { if (!e.isTemporary()) { //a temporary loss is when we change windows, in which case we don't want to unhighlight the line. unhighlightField(); } }}
package Screen;import java.awt.Color;import java.awt.event.FocusEvent;import java.awt.event.FocusListener;import javax.swing.BorderFactory;import javax.swing.JTextField;import javax.swing.border.Border;public class ViewTextField extends JTextField implements FocusListener { private static final long serialVersionUID = 1L; //CONSTRUCTOR public ViewTextField() { this(" "); } public ViewTextField(String s) { super(s); this.setBorder(null); this.setOpaque(true); this.setForeground(Color.BLACK); this.setBackground(Color.WHITE); Border border = BorderFactory.createLineBorder(Color.BLUE, 5); this.setBorder(border); //this.setBorder(null); //DWD set border for testing on/off this.addFocusListener(this); } public void setFieldHighlighting(Color foreground, Color background) { this.setForeground(foreground); this.setBackground(background); } public void highlightField() { setFieldHighlighting(Color.WHITE, Color.BLACK); } public void unhighlightField() { setFieldHighlighting(Color.BLACK, Color.WHITE); } @Override public void focusGained(FocusEvent e) { highlightField(); } @Override public void focusLost(FocusEvent e) { if (!e.isTemporary()) { //a temporary loss is when we change windows, in which case we don't want to unhighlight the line. unhighlightField(); } }}