Created
December 10, 2016 00:12
-
-
Save anonymous/9a6e3f796ebf7a54c61f77b07da91392 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class IconTextComponentHelper { | |
private static final int ICON_SPACING = 4; | |
private Border mBorder; | |
private Icon mIcon; | |
private Border mOrigBorder; | |
private JTextComponent mTextComponent; | |
IconTextComponentHelper(JTextComponent component) { | |
mTextComponent = component; | |
mOrigBorder = component.getBorder(); | |
mBorder = mOrigBorder; | |
} | |
Border getBorder() { | |
return mBorder; | |
} | |
void onPaintComponent(Graphics g) { | |
if (mIcon != null) { | |
Insets iconInsets = mOrigBorder.getBorderInsets(mTextComponent); | |
mIcon.paintIcon(mTextComponent, g, iconInsets.left, iconInsets.top); | |
} | |
} | |
void onSetBorder(Border border) { | |
mOrigBorder = border; | |
if (mIcon == null) { | |
mBorder = border; | |
} else { | |
Border margin = BorderFactory.createEmptyBorder(0, mIcon.getIconWidth() + ICON_SPACING, 0, 0); | |
mBorder = BorderFactory.createCompoundBorder(border, margin); | |
} | |
} | |
void onSetIcon(Icon icon) { | |
mIcon = icon; | |
resetBorder(); | |
} | |
private void resetBorder() { | |
mTextComponent.setBorder(mOrigBorder); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class IconTextField extends JTextField { | |
private IconTextComponentHelper mHelper = new IconTextComponentHelper(this); | |
public IconTextField() { | |
super(); | |
} | |
public IconTextField(int cols) { | |
super(cols); | |
} | |
private IconTextComponentHelper getHelper() { | |
if (mHelper == null) | |
mHelper = new IconTextComponentHelper(this); | |
return mHelper; | |
} | |
@Override | |
protected void paintComponent(Graphics graphics) { | |
super.paintComponent(graphics); | |
getHelper().onPaintComponent(graphics); | |
} | |
public void setIcon(Icon icon) { | |
getHelper().onSetIcon(icon); | |
} | |
public void setIconSpacing(int spacing) { | |
getHelper().onSetIconSpacing(spacing); | |
} | |
@Override | |
public void setBorder(Border border) { | |
getHelper().onSetBorder(border); | |
super.setBorder(getHelper().getBorder()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment