Java swing JComponent “size”

As an alternative, consider the The Button API, which includes the method setRolloverIcon() “to make the button display the specified icon when the cursor passes over it.”

Addendum: For example,

import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class ButtonIconTest {

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }

    private static void createAndShowGui() {
        String base = "http://download.oracle.com/"
            + "javase/tutorial/uiswing/examples/components/"
            + "RadioButtonDemoProject/src/components/images/";
        ImageIcon dog = null;
        ImageIcon pig = null;
        try {
            dog = new ImageIcon(new URL(base + "Dog.gif"));
            pig = new ImageIcon(new URL(base + "Pig.gif"));
        } catch (MalformedURLException ex) {
            ex.printStackTrace(System.err);
            return;
        }
        JFrame frame = new JFrame("Rollover Test");
        JPanel panel = new JPanel();
        panel.add(new JLabel(dog));
        panel.add(new JLabel(pig));

        JButton button = new JButton(dog);
        button.setRolloverIcon(pig);
        panel.add(button);

        frame.add(panel);

        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

Leave a Comment