4
My question is whether it is possible to "decorate" a field, like Jtextfield or Jformattedtextfield, with an icon.
An example would be something like this:
Following an example, I made the following class.
package componentes;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JTextField;
import javax.swing.border.Border;
public class IconTextField extends JTextField
{
private static final int ICON_SPACING = 4;
private Border mBorder;
private Icon mIcon;
@Override
public void setBorder(Border border)
{
mBorder = border;
if (mIcon == null)
{
super.setBorder(border);
}
else
{
Border margin = BorderFactory.createEmptyBorder(0, mIcon.getIconWidth() + ICON_SPACING, 0, 0);
Border compoud = BorderFactory.createCompoundBorder(border, margin);
super.setBorder(compoud);
}
}
@Override
protected void paintComponent(Graphics graphics)
{
super.paintComponent(graphics);
if (mIcon != null)
{
Insets iconInsets = mBorder.getBorderInsets(this);
mIcon.paintIcon(this, graphics, iconInsets.left, iconInsets.top);
}
}
public void setIcon(Icon icon)
{
mIcon = icon;
resetBorder();
}
private void resetBorder()
{
setBorder(mBorder);
}
}
what is missing is to pass a variable with image path and pass a parameter in the instantiation.
Have you tried that? Decorating a Jtextfield with an image and hint
– user28595
Either that or put a jlabel with the icon next to it.
– user28595
So I tried to do with the example "Decorating a Jtextfield with an image and hint", but I did not see parameters to pass a path or variable with icon. Could you try to help me ? I will edit the question and put as I did by following the example.
– Gustavo Santos