public class IconField extends JTextField {
private final Icon icon;
public IconField(Icon icon) {
super(20);
this.icon = icon;
setBorder(getBorder());
}
@Override
public void setBorder(Border border) {
Border newBorder = border;
if (icon != null) {
int height = getPreferredSize().height;
Border outerMargin = BorderFactory.createEmptyBorder(icon.getIconHeight() - height, 0, 0, 0);
Border innerMargin = BorderFactory.createEmptyBorder(0, 0, 0, icon.getIconWidth());
Border innerBorder = BorderFactory.createCompoundBorder(border, innerMargin);
newBorder = BorderFactory.createCompoundBorder(outerMargin, innerBorder);
}
super.setBorder(newBorder);
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (icon != null) {
icon.paintIcon(this, g, getWidth() - icon.getIconWidth(), 0);
}
}
public static void main(String[] args) throws Exception {
Image image = ImageIO.read(
URI.create("https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Achtung.svg/64px-Achtung.svg.png")
.toURL());
Icon icon = new ImageIcon(image);
SwingUtilities.invokeLater(() -> {
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(new IconField(icon));
panel.add(new IconField(icon));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(panel, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
});
}
}