Re-sizing an Icon in Java for Swing

Sometimes you have a resource like an icon or image that almost work, but not quite. For example, there was a question on StackOverflow about how to re-size an existing icon to fit in the smaller location at the lower right corner of a JScrollPane. The original poster was close. Here’s the code I came up with that actually worked.

import javax.swing.*;
import java.awt.*;

public class CornerButton extends JFrame
{
    public CornerButton()
    {
        JTextArea area = new JTextArea(20, 20);
        JScrollPane scroll = new JScrollPane(area);
        Icon icn = UIManager.getIcon("OptionPane.questionIcon");
        int neededWidth = scroll.getVerticalScrollBar().getPreferredSize().width;
        int neededHeight = scroll.getHorizontalScrollBar().getPreferredSize().height;
        Image img = ((ImageIcon) icn).getImage();
        ImageIcon icon = new ImageIcon(img.getScaledInstance(neededWidth, neededHeight, Image.SCALE_AREA_AVERAGING));
        JButton smallBtn = new JButton(icon);
        scroll.setCorner(ScrollPaneConstants.LOWER_RIGHT_CORNER, smallBtn);
        this.add(scroll);
    }

    public static void main(String[] args)
    {
        CornerButton mainFrame = new CornerButton();

        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setVisible(true);
        mainFrame.setSize(200,200);
    }
}

This produces the following result:

See that little green question mark in the corner? That is the standard Java Swing icon used in JOptionPanes shrunk down to the size needed. Here’s a blow up.

Seems to work pretty well.