I experimented with MatteBorder
in order to display an icon at the start of a JTextField
(similiar to search icons being displayed in a textfield).
This is my current implementation:
JTextField textField = new JTextField("Filter", 8);
textField.setPreferredSize(new Dimension(getPreferredSize().width, 24));
Border outer = textField.getBorder();
// ugly workaround
Border padding = BorderFactory.createEmptyBorder(2, 2, 2, 2);
Border search = new MatteBorder(0, 16, 0, 0, icon);
textField.setBorder(new CompoundBorder(new CompoundBorder(outer, padding), search));
The icon is a 16x16px icon with no whitespace around it. The textfield is 24px high. I introduced a padding Border to have some whitespace around the icon (otherwise it would display a full icon and the first 4px of the icon under it). My problem is that there is no whitespace to the right of the icon (where the user enters text).
Question: Is there a way to have a defined amount of whitespace around the image, so it does not tile? Can I somehow add "padding" around the icon before I add it to the MatteBorder
?
P.S. I know that I could add whitespace around the image file, but it is used in other instances where there should not be any whitespace around it.