Icon in title title

Hi, you can put an icon in the subtitle header, for example, the following code:


import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;

public class TitledExample extends JPanel {

  public TitledExample() {
    super(true);

    this.setLayout(new GridLayout(1, 1, 5, 5));

    JLabel label = new JLabel("Titled Border");
    label.setHorizontalAlignment(JLabel.CENTER);

    TitledBorder titled = new TitledBorder("Image here ?? Title");
    label.setBorder(titled);

    add(label);
  }

Thank you greetings

+5
source share
4 answers

Most likely, this is not what you want, but perhaps a good Unicode ™ glyph or two.

Addition: @rhu's approach is preferable, but I could not help it:

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);
+5
source

Try subclassing TitledBorderand overriding the method paintBorder:

 @Overide
 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);
 }

I'm not desperately sure that this is a completely correct method call, but you get an idea; as soon as you access the object Graphics, you can draw everything you need.

+8

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

, Java 10, setAccessible

+1

TitledBorder uses JLabel to draw text on the border. Unfortunately, JLabel is a private field. There are two ways to add an icon:

  • Log in to your JLabel field and set the icon to JLabel.

  • a subclass of TitledBorder and reimplementation of the paintBorder method. I
    probably also add a constructor that accepts JLabel so that you can control what is painted on the border.

0
source

All Articles