[英]Can't change color
您好,我正在用Java創建一個應用程序(練習),在該應用程序中,我必須更改繪圖類中變量的顏色。 當應用程序啟動並且我在color變量上運行sysout時,它說為null,但是例如當我按下鼠標右鍵時,它會更改控制器類中的顏色,而不是我的繪圖類中的顏色。.有人可以看一下並告訴我什么嗎我做錯了嗎?
這是一段代碼
這是繪圖類的相關部分
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();
}
我希望有人能弄清楚我在做什么錯..
在我所看到的代碼中,您從未真正為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);
}
我假設除了打印出這種顏色外,您還希望將其設置為您的Drawing類,然后觸發重新繪制。
在您的類Drawing
添加一個setter方法,並在鼠標右鍵單擊上計算出實際顏色后傳遞實際顏色:
public void setColor(Color color) {
this.color = 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);
draw.setColor(color);
}
由於它們是單獨的類,因此每個color
都是單獨的對象。
如果在你的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;
您也可以在Drawing類中創建一個setter,並使用它來設置控制器的顏色。
public setColor(Color color) {
this.color = color;
}
此外,在構造函數中將顏色設置為任何值都將阻止顏色打印為null。
在控制器中,您具有color屬性,並在右鍵單擊上進行設置,但從未在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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.