将final添加到基本类型变量使其不可变.
将final添加到对象会阻止您更改其引用,但仍然是可变的.
我正在尝试使用ImageIcon作为最终常量,但与此同时,我不希望图像可以更改.是否可以将可变对象用作常量,还是有其他选择?
示例常量:
public static final ImageIcon bit0 = new ImageIcon("bit0.png");
public static final ImageIcon bit1 = new ImageIcon("bit1.png");
Run Code Online (Sandbox Code Playgroud)
使用常量:
JButton button = new JButton(ClassName.bit0);
JLabel label = new JLabel(ClassName.bit1);
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后
public static final Icon bit0 = new ImmutableIcon(new ImageIcon("bit0.png"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
138 次 |
| 最近记录: |