How do I add a Unicode symbol as a picture in a JFrame?

Viewed 51

I want to add a unicode symbol (for example, a sun or a chess pawn) to a JFrame. But not in a JLabel or something, but just in the JPanel. As a picture or whatever. I just don't want it to be in a JLabel, which I then have to display visibly or place somewhere. I want to place it at a certain position like an image. The alternative would be to create 8-bit graphics and place them, but that doesn't look so good.

1 Answers

My idea would be to draw on the component. To use it the ContentPane of the frame could be replaced by an object of this class.

public class JUnicodePanel extends JPanel {

    private String unicodeSymbol = "☼";
    private int symbolX = 0;//X offset to the upper left corner of the component
    private int symbolY = 0;//y offset to the upper left corner of the component

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(Color.red);//Color of symbol
        g2.setFont(getFont());//Font of symbol (size, style)
        Font font = g2.getFont();
        FontRenderContext frc = g2.getFontRenderContext();
        LineMetrics metrics = font.getLineMetrics(unicodeSymbol, frc);
        g2.drawString(unicodeSymbol, symbolX, symbolY + metrics.getHeight() - metrics.getDescent());
    }
}

To change the size set the font of the object to the desired one, or use g2.setFont(getFont().deriveFont((float)size));

Related