Decorating a JTextField with an icon

4

My question is whether it is possible to "decorate" a field, such as JTextField or JFormattedTextField, with an icon.

An example would look 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 the image path and pass a parameter in instantiation.

    
asked by anonymous 09.12.2016 / 23:36

1 answer

5

Using SOEn's this answer as a base, you just need to create the IconTextComponentHelper and IconTextField by adding them to your project. And to use, just instantiate an object of type IconTextField , passing the icon of type ImageIcon through method setIcon :

IconTextField field = new IconTextField();
//...
field.setIcon(new ImageIcon(icone));

See an example:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Image;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.WindowConstants;

/**
 *
 * @author diego
 */
public class JTextFieldDecoratedIcon {

    public void start() throws IOException {

        final JFrame frame = new JFrame();
        frame.setPreferredSize(new Dimension(200, 100));

        IconTextField field = new IconTextField();

        URL path = new URL("https://i.imgur.com/WKfl8uV.png");
        Image icone = ImageIO.read(path);

        field.setIcon(new ImageIcon(icone));

        frame.add(field, BorderLayout.NORTH);
        frame.pack();
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);

        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        }

        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new JTextFieldDecoratedIcon().start();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
}

That results in:

Iftheimageislargerthanthefield,youcandefinethedimensionssothatitfitscorrectlyinthefieldbyaddingthelinebelow:

//adicioneestalinhaealtereasdimensoesconformeotamanhodocampoicone=icone.getScaledInstance(25,25,Image.SCALE_DEFAULT);field.setIcon(newImageIcon(icone));

Tostaycool,you'dpreferimagesoficonswhoseheightandwidtharethesame.

TheIconTextComponentHelperandIconTextFieldclassescanbefound this link .     

10.12.2016 / 01:00