Search code examples
javajbutton

JButton, uneven matrix of them ( like 1st row 7 colums, 2nd row 9, ectr)


My main problem is making a matrix of buttons, that when clicked sends me 2 integer values (row and column). The matrix is eneven, like 1st row has 7 columns, 2nd row has 5, 3rd row has 9, ectr... I found a pretty good solution that makes the matrix, BUT when i use the remove(), than the layout instantly changes the place of the buttons... here is part of the code.

private static JButton[][] buttons;
   public static JFrame f = new JFrame();

   public TEMPus(int row, int col) {
      super(new GridLayout(row, col));

      buttons = new JButton[row][col];

      for (int i = 0; i < buttons.length; i++) {
         for (int j = 0; j < buttons[i].length; j++) {
            final int curRow = i;
            final int curCol = j;
            buttons[i][j] = new JButton(j + ", " + i);
            buttons[i][j].addKeyListener(enter);
            buttons[i][j].addKeyListener(new KeyAdapter() {
               @Override
               public void keyPressed(KeyEvent e) {
                  switch (e.getKeyCode()) {
                  case KeyEvent.VK_UP:
                     if (curRow > 0)
                        buttons[curRow - 1][curCol].requestFocus();
                     break;
                  case KeyEvent.VK_DOWN:
                     if (curRow < buttons.length - 1)
                        buttons[curRow + 1][curCol].requestFocus();
                     break;
                  case KeyEvent.VK_LEFT:
                     if (curCol > 0)
                        buttons[curRow][curCol - 1].requestFocus();
                     break;
                  case KeyEvent.VK_RIGHT:
                     if (curCol < buttons[curRow].length - 1)
                        buttons[curRow][curCol + 1].requestFocus();
                     break;
                  default:
                     break;
                  } // end of switch
               }
            }); //end of key listener
            add(buttons[i][j]);
         }
      }
   }

and here is the main where i tried to remove certain buttons...

public static void main(String[] args) {

      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      TEMPus temp1 =new TEMPus(3, 5);
      temp1.remove(buttons[1][4]);
      f.add(temp1);
      f.pack();
      f.setVisible(true);
      }

Sorry for the long post :/ And thank you for your time :)


Solution

  • The layout cannot change the name of the buttons, only the place of the buttons.

    If you want to keep the place of the buttons, the simple solution is to hide a button (setVisible(false)) instead of removing it. A more flexible solution is to place all buttons in a JPanel and replace the button with an empty Canvas for example (see also this answer).