I have a class extending BufferedImage
which should display as a string provided to it's constructor. The reason I wish to do this is to allow the anti-aliasing functionality of graphics2D
(see my previous question for more details, and if you have any better suggestions then by all means suggest them!). I now have the BufferedImage
class working, however I cannot figure out how to determine the required width and height in order to display the input string before actually setting the font. I also cannot find a way to resize the BufferedImage
parent once its initial size has been set. Here is my code:
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class Test extends JFrame{
public Test(){
this.add(new JLabel(new ImageIcon(new IconImage("Test", new Font("Sans-Serif", Font.PLAIN, 16)))));
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.pack();
}
class IconImage extends BufferedImage{
public IconImage(String text, Font font){
super(..., ..., BufferedImage.TYPE_INT_ARGB);//*****Unknown dimensions*****
Graphics2D g2d = (Graphics2D) this.getGraphics();
g2d.setFont(font);
g2d.setColor(Color.BLACK);
int stringHeight = (int) g2d.getFontMetrics().getStringBounds(text, g2d).getHeight();
g2d.drawString(text, 0 , stringHeight);
g2d.dispose();
}
}
public static void main(String[] args){
new Test();
}
}
Any advice? Thanks.