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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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:

A Program Window with the Resized Icon
A Program Window with the Resized Icon

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.

A Blowup of the Resized Corner Icon
A Blowup of the Resized Icon

Seems to work pretty well.