Decorating a Jtextfield with an icone

Asked

Viewed 669 times

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:

inserir a descrição da imagem aqui

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.

  • 1
  • 1

    Either that or put a jlabel with the icon next to it.

  • 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.

1 answer

5


Using this answer Soen as the basis, simply create the classes IconTextComponentHelper and IconTextField, adding them to your project. And to use, simply instantiate an object of the type IconTextField, passing the icone of the type ImageIcon through the method setIcon:

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

Take 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();
                }
            }
        });
    }
}

Which results in:

inserir a descrição da imagem aqui

If the image is larger than the field, you can define the dimensions so that it fits correctly in the field by adding the line below:

//adicione esta linha e altere as dimensoes conforme o tamanho do campo
icone = icone.getScaledInstance(25, 25, Image.SCALE_DEFAULT);
field.setIcon(new ImageIcon(icone));

To be cool, prefer images of icons whose height and width are equal.

The classes IconTextComponentHelper and IconTextField can be found at this link.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.