2012-12-14 102 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);