Icon in titledBorder title

Try subclassing TitledBorder, and override the paintBorder method:

 @Override
 public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) 
 {
     super.paintBorder(c, g, x, y, width, height);

     // Now use the graphics context to draw whatever needed
     g.drawImage(img, xImageOffset, yImageOffset, imgWidth, imgHeight, observer);
 }

Not desperately sure that this is entirely right method call, but you get the idea; once you have access to the Graphics object, you can paint pretty much whatever you need.


It's probably not what you want, but maybe a nice Unicode™ glyph or two would do.

Addendum: @rhu's approach is preferable, but I couldn't resist trying this:

enter image description here

TitledBorder titled = BorderFactory.createTitledBorder("\u2615");
titled.setTitleFont(new Font(Font.Dialog, Font.PLAIN, 32));
titled.setTitleColor(Color.blue);
label.setBorder(titled);

You can use reflection to get access to the JLabel used by the TitledBorder.

try
{
    // Get the field declaration
    Field f = TitledBorder.class.getDeclaredField("label");
    // Make it accessible (it normally is private)
    f.setAccessible(true);
    // Get the label
    JLabel borderLabel = (JLabel)f.get(titledBorder);
    // Put the field accessibility back to default
    f.setAccessible(false);
    // Set the icon and do whatever you want with your label
    borderLabel.setIcon(myIcon);
}
catch(Exception e)
{
    e.printStackTrace();
}

It is important to note that this will not work in Java 10, as it will have stricter rules on the use of setAccessible

Tags:

Java

Swing