Gnome have nifty little feature to show warning icon in the right part of entry box when CAPS LOCK key is on. Actually, it’s part of GtkEntry widget. Warning icon is shown when widget gain focus and disappear when focus is lost. You can see how that looks like:
![]()
This is my take to replicate this behavior in Java:
public class WarningPasswordField extends JPasswordField { private static final long serialVersionUID = -4334432525061916434L; private final int verticalInsets = 5; private final int rightOffset = 4; private BufferedImage warning = null; public WarningPasswordField() { super(); try { InputStream is = this.getClass() .getResourceAsStream("/warning.png"); if (is != null) { warning = ImageIO.read(is); } } catch (IOException e) { } } @Override public void paint(Graphics g) { super.paint(g); if (warning == null) { /* image is not loaded, behave like a normal password field */ return; } if (!this.isFocusOwner()) { /* don't paint warning icon if we don't have focus */ return; } boolean capsLockOn = false; try { capsLockOn = Toolkit.getDefaultToolkit().getLockingKeyState( KeyEvent.VK_CAPS_LOCK); } catch (UnsupportedOperationException e) { /* workaround sun java bug 5100701 when using XToolkit */ } if (capsLockOn) { int width = this.getWidth(); int height = this.getHeight(); int iconSize = height - 2 * verticalInsets; int dx1 = width - (iconSize + rightOffset); int dy1 = verticalInsets; /* * fill white rectangle where image will be, so password stars are * not visible if image is transparent */ g.setColor(Color.WHITE); g.fillRect(dx1, dy1, iconSize, iconSize); /* draw warning image */ g.drawImage(warning, dx1, dy1, dx1 + iconSize, dy1 + iconSize, 0, 0, warning.getWidth(), warning.getHeight(), null); } } }
As you can see, paint method is overridden and that’s basically it. Because warning icon’s position is dependent on used look & feel, I left two constants so you can tweak its position. If warning icon can’t be loaded, this code fails silently. I used warning icon from Gnome project, but it could (obviously) be any icon. So here is how it looks (this is nimbus L&F):
![]()
Hope you like it and hope it will integrate quickly and nicely into your code;)
Note: RTL languages are not supported, icon there should probably go to the left!