Create a dynamic icon : Icon « 2D Graphics GUI « Java

Create a dynamic icon


import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Graphics;

import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main{
  Icon icon = new DynamicIcon();
  final JSlider width = new JSlider(JSlider.HORIZONTAL, 1, 150, 75);
  final JSlider height = new JSlider(JSlider.VERTICAL, 1, 150, 75);
  final JLabel dynamicLabel = new JLabel(icon);
    Updater updater = new Updater();
    JFrame f = new JFrame();
    f.add(width, BorderLayout.NORTH);
    f.add(height, BorderLayout.WEST);
    f.add(dynamicLabel, BorderLayout.CENTER);
    f.setSize(210, 210);

  public static void main(String[] args) {
    new Main();
  class Updater implements ChangeListener {
    public void stateChanged(ChangeEvent ev) {

  class DynamicIcon implements Icon {
    public int getIconWidth() {
      return width.getValue();

    public int getIconHeight() {
      return height.getValue();

    public void paintIcon(Component c, Graphics g, int x, int y) {
      g.fill3DRect(x, y, getIconWidth(), getIconHeight(), true);


Related examples in the same category

1.A simple application to test the functionality of the OvalIcon classA simple application to test the functionality of the OvalIcon class
2.Icon DisplayerIcon Displayer
3.Implement the Icon interfaceImplement the Icon interface
4.Calendar Page icons with Weekday, Day and MonthCalendar Page icons with Weekday, Day and Month
5.MemImage is an in-memory icon showing a Color gradientMemImage is an in-memory icon showing a Color gradient
6.Example of an icon that changes formExample of an icon that changes form
7.Custom Icon DemoCustom Icon Demo
8.Create Image Icon from PNG file
9.Reading an Image or Icon from a File
10.Draw an Icon object
11.Plain Color Icon
12.Color Icon
13.Arrow Icon
14.Icon Line
15.Return a filled oval as an Icon
16.Layered Icon
17.An icon for painting a square swatch of a specified Color.
18.An empty icon with arbitrary width and height.
19.Transparent icon with no content
20.Creates a transparent icon.
21.Icon Codec