Search code examples
javaswingimageiconjtabbedpane

Set icon size of JTabbedPane tab icon


Is there a way to easily set the size of an icon for a JTabbedPanetab. The icon is the same size as the original image and therefore makes for a very ridiculous looking tab with it taking up half the screen.

How would I easily rescale this icon to be a similar size to my text "Settings" and just have it appear normally?

URL cogIconUrl = getClass().getResource("/images/cog.png");
ImageIcon cogImg = new ImageIcon(cogIconUrl);

JTabbedPane jtp = new JTabbedPane();
getContentPane().add(jtp);
JPanel jp1 = new JPanel();
jtp.addTab("Settings", cogImg,jp1);

Furthermore, how would you go about setting the font of the tab text? I assume the two are potentially related.


Solution

  • Resize the Image:

    BufferedImage image = ImageIO.read(...);
    Image scaled = image.getScaledInstance(...);
    Icon icon = new ImageIcon( scaled );
    

    Note: the getScaledInstance(...) method may not be the best approach as it is slow, but for a single image you won't notice any problems.

    You can read Perils of Image.getScaledImage for more information.