Using mutable objects as constants

Adding final to a primitive type variable makes it immutable .
Adding final to the object does not allow you to change its reference , but is still changed .

I am trying to use ImageIcon as the final constant, but at the same time I do not want the image to be mutable. Is it possible to simply use mutable objects as a constant or are there alternatives?

Examples of constants:

public static final ImageIcon bit0 = new ImageIcon("bit0.png");
public static final ImageIcon bit1 = new ImageIcon("bit1.png");

Using constants:

JButton button = new JButton(ClassName.bit0);
JLabel label = new JLabel(ClassName.bit1);
+4
source share
2 answers

ImageIcon , , . ?

, .:-) , , , , .

: JButton Icon Icon - , ImmutableIcon .

:.

class ImmutableIcon implements Icon {
    private Icon icon;

    public ImmutableIcon(Icon i) {
        this.icon = i;
    }

    public int getIconHeight() {
        return this.icon.getIconHeight();
    }

    public int getIconWidth() {
        return this.icon.getIconWidth();
    }

    public void paintIcon(Component c, Graphics g, int x, int y) {
        this.icon.paintIcon(c, g, x, y);
    }
}

public static final Icon bit0 = new ImmutableIcon(new ImageIcon("bit0.png"));
+6

ImageIcon ( ), final , . .

, - , , , Icon, ,

public static final Icon bit0 = new ImageIcon("bit0.png");

, . - , , .

, , , - , , . , , .

+2

Source: https://habr.com/ru/post/1622540/


All Articles