2012-12-14 38 views
0

你好我正在Java中创建一个应用程序(练习),我必须更改我的绘图类中变量的颜色。当应用程序启动时,我在颜色变量上运行sysout它说空,但是当我按下我的鼠标右键,例如它改变控制器类中的颜色,但不是在我的绘图类。可以有人看看,告诉我什么我做错了?无法更改颜色

这里是一段代码

这是绘画班

private Color color; 
private ArrayList<Point> p = new ArrayList<Point>(); 

public Drawing(Color color) { 
    this.color = color; 
    System.out.println("color " + color); 
} 

public void draw(Graphics g) { 
    for(int i = 0; i < p.size(); i++) { 
     g.setColor(color); 
     g.fillRect(p.get(i).x, p.get(i).y, 10, 10); 
    } 
} 

的相关部分,这是我的控制器的相关代码。

Color color; // kleur vasthouden 
Drawing draw; // class definieren 
private ArrayList<Drawing> tekening = new ArrayList<Drawing>(); 
int x, y; 

public DrawingPanel() { 
    setBackground(Color.WHITE); // zorg voor een witte achtergrond. 
    this.addMouseListener(this); // control de mouselistener 
    draw = new Drawing(color); 
} 

public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    draw.draw(g); 
} 

@Override 
public void mouseClicked(MouseEvent e) { 

    if(e.getButton() == MouseEvent.BUTTON1) { 
     Point k = new Point(e.getX(), e.getY()); 

     draw.addPoint(k); 
     System.out.println("punt gezet op " + k); 
    } 
    if(e.getButton() == MouseEvent.BUTTON3) { 
     color = new Color(r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0); 
     System.out.println("new color " + color); 
    } 
    repaint(); 
} 

我希望有人能找出我在做什么错..

回答

1

添加二传手方法您Drawing类,并通过实际的颜色已经上右鼠标键点击计算后:

public void setColor(Color color) { 
    this.color = color; 
} 

和Controller:

if(e.getButton() == MouseEvent.BUTTON3) { 
    color = new Color(r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0); 
    System.out.println("new color " + color); 
    draw.setColor(color); 
} 
2

你从来没有真正在,我可以看到代码的任何地方分配初始值color。您只能在发生鼠标事件时进行设置。

if(e.getButton() == MouseEvent.BUTTON3) { 
    color = new Color(r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0); 
    System.out.println("new color " + color); 
} 

我认为,除了打印出这种颜色,你也想把它设置为你的绘图类,然后触发重绘。

+0

我必须设置初始值吗? (所以不为空) – Reshad

+0

假设你不想让初始值为null,那么这是个好主意! – Perception

0

由于它们是分开的类,因此它们中的每一个都是独立的对象。
如果在您的Drawing类中将color更改为公开,则可以将color设置为在控制器内创建的新颜色。

color = new Color(r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0); 
draw.color = color; 

你也可以创建绘图类中的setter和使用该设置从控制器的颜色。

public setColor(Color color) { 
    this.color = color; 
} 

此外,将颜色设置为构造函数中的任何值将使其停止打印为空。

+0

通过一个setter或更改变量,哪种方法更好? – Reshad

+0

二传可能是更好的选择。通常只允许一个班级运用自己的变量是很好的。 – jonhopkins

0

在您的控制器中,您有一个颜色属性,并在右键单击时设置它,但是您从未将它设置在Drawing类上。 尝试:

if(e.getButton() == MouseEvent.BUTTON3) { 
    color = new Color(r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0, r.nextInt(255 - 0 + 1) + 0); 
draw.setColor(color);