2 Replies Latest reply on Mar 31, 2008 1:17 AM by 807601

    trouble with background color in GridLayout

    807601
      Hi,

      I'm having trouble getting the background color of a specific part of my grid to change when clicked on.
      class BPanel extends JPanel implements MouseListener{
      
          private Game[][] bGame = new Game[10][10];
            
          public BedazzledPanel() {
              setLayout(new GridLayout(10, 10));
               setOpaque(true);
              setUp();
         } 
      
      public void setUp() { //set up board
              for (int i = 0; i < bGame.length; i++) {
                  for (int j = 0; j < bGame.length; j++) {
                      bGame[i][j] = new Game();
                      add(bGame[i][j], i, j);
                      repaint();
                  }
              }
          }
         
      
       public void mouseClicked(MouseEvent e) {
          }
          public void mousePressed(MouseEvent e) {
              for (int i = 0; i < bGame.length; i++) {
                  for (int j = 0; j < bGame.length; j++) {
      
                     if(bGame[i][j].getBackground()==Color.BLUE){
                  bGame[i][j].setBackground(Color.GREEN);
                   repaint();
              }  else if (bGame[i][j].getBackground()==Color.GREEN){
                   bGame[i][j].setBackground(Color.YELLOW);
                    repaint();
              }
                      repaint();
                  }
              }
                  }
          public void mouseReleased(MouseEvent e) {
          }
          public void mouseEntered(MouseEvent e) {
          }
          public void mouseExited(MouseEvent e) {
          }
          }
      thanks
        • 1. Re: trouble with background color in GridLayout
          807601
          More specifics please, at first glance I see that your grid will tend toward all yellow and then not convert any more, since you convert from blue to green to yellow. Yellow is a terminal color in your scheme, since it doesn't have a conversion.

          Also if you override paint(), you should show that code.
          • 2. Re: trouble with background color in GridLayout
            807601
            A couple of points:

            1. Don't you need to set all of the grid members Game objects' background colors to blue to start with?
            2. One way to do this is to add a MouseAdapter extended object to each of the grid's Game objects. Then when the Game panel is clicked, you can easily know which panel was clicked via the MouseEvent#getSource() method, check it's background color, and set the color appropriately.
            3. If you do this, then the BPanel class (BedazzledPanel? I'm confused as your class has two conflicting names here) doesn't have to implement the MouseListener interface -- something it probably shouldn't be doing anyway.