Forked from anonymous/IconTextComponentHelper.java
Created
September 1, 2017 17:42
-
-
Save diegofelipem/52566bd60542618a10517601960baf3e 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