Search code examples
javaswingawtscaling

how to instantiate different size icons based on the button pressed java


How can I change the size of icons that are instantiated based on a button pressed in a method.

so for instance this is what the buttons are instantiated as

private ExitProgramAction exitProgramAction = new ExitProgramAction("Quit",
      Resources.getIcon("exit16"), "Quit HEAT", new Integer(KeyEvent.VK_Q),
      KeyStroke.getKeyStroke(KeyEvent.VK_Q, java.awt.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false));

but I am trying to change the getIcon() via the below method (which i created button for) when clicked.

protected class ZoomButtonAction extends AbstractAction {
    public ZoomButtonAction(String text, String desc)
    {
        super(text);
        putValue(SHORT_DESCRIPTION, desc);
    }

    public void actionPerformed(ActionEvent e){


    }
}

Solution

  • You can resize icons with the code below anytime you want.

    protected class ZoomButtonAction extends AbstractAction {
        public ZoomButtonAction(String text, String desc)
        {
            super(text);
            putValue(SHORT_DESCRIPTION, desc);
        }
    
        public void actionPerformed(ActionEvent e){
    
            ImageIcon icon = (ImageIcon)getValue(Action.SMALL_ICON);
            Image newImage = icon.getImage().getScaledInstance(width, height, Image.SCALE_SMOOTH);
            putValue(Action.SMALL_ICON, new ImageIcon(newImage));
        }
    }