为什么要使用其属性绘制多个对象,而第二个对象使用先前的对象值?
Why to paint more that one object using its attributes, the second object use the previous object values?
我用一个带有属性的对象做了一个代码,它的属性用于绘制一个组件,到时候从同一个 class 创建其他对象时,方法:paint(Graphics g),是使用了之前创建的对象的值。
Object class - 扩展 JPanel
public RoundedPanel(int x){
this.x = x;
System.out.println(x);
} // End of builder
public void paint(Graphics g){
g.setColor(Color.WHITE);
g.fillRect(x, 0, 100, 100);
System.out.println(x);
setBounds(x, 0, 100, 100);
setBackground(0, 0, 0, 0);
} // End of method - paint
RoundedPanel的使用
RoundedPanel firstPanel = new RoundedPanel(4),
secondPanel = new RoundedPanel(0);
我在生成器和绘制方法中设置了 System.out.println("x: " + x) 消息以了解属性值,并且在生成器中值是正确的,但是在paint 方法,值来自第一个对象:
打印:
建设者:
第一个对象 x: 4,
第二个对象 x: 0.
绘画:
第一个对象 x: 4,
第二个对象 x: 4.
我希望在绘制时 x 值是,第一个:4,第二个:0
原因是我在 paint(Graphics g)、setBounds() 和 setBackground() 中使用了 class 自己的方法,我认为这样做,它会重绘。我删除了那些方法并且它起作用了。
我用一个带有属性的对象做了一个代码,它的属性用于绘制一个组件,到时候从同一个 class 创建其他对象时,方法:paint(Graphics g),是使用了之前创建的对象的值。
Object class - 扩展 JPanel
public RoundedPanel(int x){
this.x = x;
System.out.println(x);
} // End of builder
public void paint(Graphics g){
g.setColor(Color.WHITE);
g.fillRect(x, 0, 100, 100);
System.out.println(x);
setBounds(x, 0, 100, 100);
setBackground(0, 0, 0, 0);
} // End of method - paint
RoundedPanel的使用
RoundedPanel firstPanel = new RoundedPanel(4),
secondPanel = new RoundedPanel(0);
我在生成器和绘制方法中设置了 System.out.println("x: " + x) 消息以了解属性值,并且在生成器中值是正确的,但是在paint 方法,值来自第一个对象:
打印:
建设者: 第一个对象 x: 4, 第二个对象 x: 0.
绘画: 第一个对象 x: 4, 第二个对象 x: 4.
我希望在绘制时 x 值是,第一个:4,第二个:0
原因是我在 paint(Graphics g)、setBounds() 和 setBackground() 中使用了 class 自己的方法,我认为这样做,它会重绘。我删除了那些方法并且它起作用了。