2017-03-22 34 views
1

我有一个15 x 15的二维数组JButtonJava:使用MouseListener更改相邻JButton的颜色

当我保持这些按钮(即Button[i][j]) 之一我想改变相邻按钮的颜色(即Button[i-1][j]Button[i+1][j]Button[i][j-1]Button[i][j+1])。

我该怎么做?

下面是我的2D数组实现的一部分。该按钮现在不做任何事情。

fb = new JButton[15][15]; 

    for(int i = 0; i < 15; i++){ 
     for(int j = 0; j < 15; j++){ 
      fb[i][j] = new JButton(); 
      fb[i][j].setBackground(Color.WHITE); 
      fb[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK, 2)); 
      fb[i][j].setPreferredSize(new Dimension(40, 40)); 
      //fb[i][j].setEnabled(false); 
      grid.add(fb[i][j]); 
     } 
    } 
+0

请添加代码 –

+0

我说我的代码,但我认为这不会是重要的,因为它是从字面上15 x 15 JButtons等等。 – Ned

回答

2

试块:

  if (i - 1 >= 0) { 
       if (fb[i - 1][j] != null) { 
        fb[i - 1][j].setBackground(Color.RED); 
       } 
      } else if (i + 1 < 15) { 
       if (fb[i + 1][j] != null) { 
        fb[i + 1][j].setBackground(Color.RED); 
       } 
      } else if (j - 1 >= 0) { 
       if (fb[i][j - 1] != null) { 
        fb[i][j - 1].setBackground(Color.RED); 
       } 
      } else if (j + 1 < 15) { 
       if (fb[i][j + 1] != null) { 
        fb[i][j + 1].setBackground(Color.RED); 
       } 
      } 

和监听:

  fb[i][j].addActionListener(new ActionListener() { 

       public void actionPerformed(ActionEvent e) { 
        JButton b = (JButton) e.getSource(); 
        int x, y; 
        for (int i = 0; i < 15; i++) { 
         for (int j = 0; j < 15; j++) { 
          if(fb[i][j].equals(b)){ 
           x = i; 
           y = j; 
           break; 
          } 
         } 
        } 

        if (x - 1 >= 0) { 
        if (fb[x - 1][y] != null) { 
         fb[x - 1][y].setBackground(Color.RED); 
        } 
        } else if (x + 1 < 15) { 
         if (fb[x + 1][y] != null) { 
          fb[x + 1][y].setBackground(Color.RED); 
         } 
        } else if (y - 1 >= 0) { 
         if (fb[x][y - 1] != null) { 
          fb[x][y - 1].setBackground(Color.RED); 
         } 
        } else if (y + 1 < 15) { 
         if (fb[x][y + 1] != null) { 
          fb[x][y + 1].setBackground(Color.RED); 
         } 
        } 

       } 
      }); 
+0

MouseListener如何知道我和j有什么价值? – Ned

+0

我想通了!谢谢。 – Ned

+0

我做到了通过这样做: \t \t \t J = arg0.getComponent()的getX()/ 40; \t \t \t i = arg0.getComponent()。getY()/ 40; 有没有更好的方法来做到这一点? (40是我为每个按钮设置的大小) – Ned