为什么当我再次为其各自的对象设置颜色时,它没有变成红色?
首先我将其设置为绿色,然后在实例化对象时将其设置为红色,但它似乎不适用...
(也许这是一个愚蠢的问题,但我从 Java 开始,我正在将观看一些教程所学到的知识付诸实践 xd)
public class Estatico extends JFrame{
private JLabel lbl1, lbl2, lbl3;
private Color backgroundColor;
private int xPosition = 20;
public Estatico() {
setBounds(0, 0, 450, 300);
setLayout(null);
setLocationRelativeTo(null);
backgroundColor = new Color(0, 255, 0);
lbl1 = new JLabel("Label1");
lbl1.setBounds(20, 20, 50, 20);
lbl1.setOpaque(true);
lbl1.setBackground(backgroundColor);
add(lbl1);
lbl2 = new JLabel("Label2");
lbl2.setBounds(120, 20, 50, 20);
lbl2.setOpaque(true);
lbl2.setBackground(backgroundColor);
add(lbl2);
lbl3 = new JLabel("Label3");
lbl3.setBounds(220, 20, 50, 20);
lbl3.setOpaque(true);
lbl3.setBackground(backgroundColor);
add(lbl3);
}
public static void main(String[] args) {
Estatico objeto1 = new Estatico();
objeto1.backgroundColor = new Color(255, 0, 0);
objeto1.setVisible(true);
}
}
在 main 方法中,您尝试在使用 new Color(255, 0, 0) 创建 Estatico 实例后将 backgroundColor 更改为红色。但此更改不会影响标签(lbl1、lbl2、lbl3),因为它们的背景颜色已在构造函数( Estatico() )中设置,并且随后更改 backgroundColor 变量不会更新标签的背景颜色。
要使用构造函数修复此通道backgroundColor uover
public class Estatico extends JFrame {
...
public Estatico(Color bgColor) {
...
}
public static void main(String[] args) {
Estatico objeto1 = new Estatico(new Color(255, 0, 0));
...
}
}