2013-09-28 25 views
2

我一直在嘗試了很長時間纔得到這個工作,並做了大量的研究,但我不能解決它爲什麼不會發生:我的最終目標是獲得一個由y綠色方塊,當你點擊一個方塊時,它會改變顏色。 (這是一個更大的項目的一部分)畫的矩形沒有顯示

現在我知道,這可能是一個非常低效的方式,但我嘗試了不同的方式,似乎沒有任何工作。

在我的網格類我有這樣的:

squares = new Square[width][height]; 
for (int i = 0; i < width; i++){ 
    for (int j = 0; j < height; j++){ 
     squares[i][j] = new Square(i,j); 
     frame.getContentPane().add(squares[i][j]); 
    } 
} 

這是我的Square類:

public class Square extends JLabel implements MouseListener{ 

private int x,y,width,height, mouseX,mouseY; 
private Color colour = Color.GREEN; 


public Square(int width, int height){ 
this.x = width*45; 
this.y = height*45; 
addMouseListener(this); 
this.setBounds(x, y, 45, 45); 
} 

public void paintComponent(Graphics g){ 
    Graphics2D g2 = (Graphics2D) g; 
    g2.setColor(colour); 
    g2.fillRect(x, y, 45, 45); 
} 

@Override 
public void mouseClicked(MouseEvent e) { 
    mouseX = e.getX(); 
    mouseY = e.getY(); 
    if(mouseX > x && mouseX < x+45 && mouseY > y && mouseY < y+45){ 
    if(colour.equals(Color.GREEN)){ 
     colour = Color.RED; 
    } else{ 
     colour = Color.GREEN; 
    } 
    repaint(); 
    } 
} 

}

然而,當我運行的代碼,我看到的是第一廣場和最後一個廣場;怎麼來的?

如果您有任何關於如何更有效地完成此任務的提示,請告訴並批評此代碼。

回答

0

解決你的問題。您需要在某些地方更改您的代碼。

1)您不需要傳遞x,y座標與Square()構造函數。聲明像這樣的空構造函數:

public Square() { 
     addMouseListener(this); 
     this.setBounds(x, y, 45, 45); 
} 

2)將GridLayout設置爲您的JFrame。

frame.setLayout(new GridLayout(width, height)); 

3)在循環中調用空構造函數。

Square[][] squares = new Square[width][height]; 
    for (int i = 0; i < width; i++) { 
     for (int j = 0; j < height; j++) { 
      squares[i][j] = new Square(); 
      frame.add(squares[i][j]); 
     } 
    } 
+0

this.setBounds(x,y,45,45); == GridLayout – mKorbel

+0

謝謝你這麼多Masud,現在工作正常:) 但有一個問題,爲什麼我的方法不工作? – user2826525

+0

編號setBounds指定x,y和寬度和高度。 – Masudul