2012-12-28 176 views
1

我正在練習Java swing。我創建了一個矩陣作爲Rectangle2D對象的二維數組。我已經設置了MouseListener來繪製被點擊的方塊。我已經設置了用於檢查哪個方塊被點擊的for循環。當我點擊一個正方形時,它被塗成藍色。事情是,當我點擊另一個廣場時,第一個變成白色,另一個變成藍色。我的問題是,如何保持第一次點擊廣場的顏色?在Java中繪製方形矩陣

這裏的Matrica(Matrix)類(這是我的母語的代碼,crtanjeMatrice意味着drawMatrixduzinalength

public class Matrica extends JPanel implements MouseListener { 
Rectangle2D[][] matrica = new Rectangle2D[8][8]; 
Color boja = Color.white; 
int a = 0; 
int b = 0; 

    public Matrica() { 
     addMouseListener(this); 
    } 

    public void paint(Graphics g){ 
     Graphics2D g2 = (Graphics2D)g; 
     g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
     g2.clearRect(0, 0, this.getWidth(), this.getHeight()); 
     crtanjeMatrice(g2); 
     g2.setColor(boja); 
     g2.fill(matrica[a][b]); 

    } 




    private void crtanjeMatrice(Graphics2D g2){ 
     g2.setColor(Color.black); 
     int startX = 0; 
     int startY =0; 
     int duzina = 50; 
     for(int i=0; i < matrica.length; i++){ 
      for(int j = 0; j < matrica.length; j++){ 
       matrica[i][j] = new Rectangle2D.Double(startX,startY,duzina,duzina); 
       g2.draw(matrica[i][j]); 
       startX = startX + duzina; 
      } 
      startY = startY + duzina; 
      startX = 0; 
     } 

    } 


    @Override 
    public void mouseClicked(MouseEvent e) { 
    } 

    @Override 
    public void mousePressed(MouseEvent e) { 
     int m,n; 
     int x = e.getX(); 
     int y = e.getY(); 
     for(int i = 0; i < matrica.length; i++) 
     for(int j =0; j < matrica.length; j++) 
      if(matrica[i][j].contains(x, y)){ 
       boja = Color.blue; 
       a = i; 
       b = j; 
       repaint(); 
      } 
    } 


    @Override 
    public void mouseReleased(MouseEvent e) { 
    } 

    @Override 
    public void mouseEntered(MouseEvent e) { 
    } 

    @Override 
    public void mouseExited(MouseEvent e) { 
    } 

} 
+3

你可以發佈你的代碼的相關部分? – MAK

+0

你可以顯示一些代碼嗎?否則,解決方案是將點擊時的顏色存儲到臨時變量中。 –

回答

0

您正在畫一個單一基質細胞在paint方法:

g2.fill(matrica[a][b]); 

但您需要「記住」哪個矩形已被點擊。爲此,可以使用簡單的List o存儲已經點擊的矩形的索引。基於Point類的課程提供了將行列索引信息存儲在列表中的好方法。

@Override 
protected void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    Graphics2D g2 = (Graphics2D) g; 
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
    g2.clearRect(0, 0, this.getWidth(), this.getHeight()); 
    crtanjeMatrice(g2); 
    for (MyRowColumn index : indexList) { // MyRowColumn based on Point 
    g2.setColor(Color.blue); 
    g2.fill(matrica[index.x][index.y]); 
    } 
} 

旁白:,不使用覆蓋paint,覆蓋paintComponent反而記得打電話super.paintComponent渲染子組件。

+0

謝謝。有用。 – Balthazar