Невозможно ввести что-либо в текстовые поля после добавления KeyListener - PullRequest
0 голосов
/ 11 апреля 2019

Я делаю судоку, но после добавления KeyListener в текстовое поле я не могу ничего ввести в текстовое поле.Что не так с моим кодом?

Я уже пробовал код ниже:

//add listener in the previous code

for (int row = 0; row < GRID_SIZE && !found; ++row) {
    for (int col = 0; col < GRID_SIZE && !found; ++col) {
         tfCells[row][col].addKeyListener(new KeyAction());
     }
}

//implements the listener
private class KeyAction implements KeyListener {
    public void keyPressed(KeyEvent ev){}
    public void keyReleased(KeyEvent evt){}
    public void keyTyped(KeyEvent e){
    // Get the source object that fired the event
       JTextField source = (JTextField)e.getSource();

       // Scan JTextFileds for all rows and columns, and match with the source object
      boolean found = false;
      for (int row = 0; row < GRID_SIZE && !found; ++row) {
              for (int col = 0; col < GRID_SIZE && !found; ++col) {
             if (tfCells[row][col] == source) {
                 rowSelected = row;
                 colSelected = col;
                  found = true;  // break the inner/outer loops
              }
            }
      }
          /* 1. Get the input String 
             2. Assume that the solution is unique. Compare the input number 
                with the number in the puzzle[rowSelected][colSelected].  
                If they are the same,set the background to green(Color.GREEN); 
                otherwise, set to red (Color.RED).
       */

           String inputString = tfCells[rowSelected][colSelected].getText();
       if(Integer.parseInt(inputString)==puzzle[rowSelected][colSelected]) {

           tfCells[rowSelected[colSelected].setBackground(OPEN_CELL_TEXT_YES);
           masksGen.setCellMasks(rowSelected, colSelected, false);
       tfCells[rowSelected][colSelected].setEditable(false);
       }else {
    tfCells[rowSelected][colSelected].setBackground(OPEN_CELL_TEXT_NO);
    }


    //Check conflicts in row and col, the bg turn blue
    for(int row = 0; row < GRID_SIZE; ++row){
        if((tfCells[row][colSelected] == tfCells[rowSelected][colSelected]) && (row != rowSelected)){
        tfCells[row][colSelected].setBackground(CONFLICT_BGCOLOR);
        }
    }

    for(int col = 0; col < GRID_SIZE; ++col){
        if((tfCells[rowSelected][col] == tfCells[rowSelected][colSelected]) && (col != colSelected)){
        tfCells[rowSelected][col].setBackground(CONFLICT_BGCOLOR);
        }
    }

     }
}

Я хочу, чтобы слушатель проверял и отвечал, когда я набираю номер.Не могли бы вы помочь мне выяснить, почему я ничего не могу ввести?

1 Ответ

0 голосов
/ 11 апреля 2019

Кажется, это виновник:

tfCells[rowSelected][colSelected].setEditable(false);

Он запрещает ввод символа в JTextField, потому что символ будет добавлен ПОСЛЕ выполнения ключевого слушателя.Поэтому ваш напечатанный символ никогда не появляется в текстовом поле.

Я позволил себе немного переформатировать ваш код, прежде чем сделать несколько предложений.

//add listener in the previous code
KeyAction action = new KeyAction();
for (int row = 0; row < GRID_SIZE; ++row) {
    for (int col = 0; col < GRID_SIZE; ++col) {
        tfCells[row][col].addKeyListener(action);
    }
}

//implements the listener
protected class KeyAction extends KeyAdapter {
    @Override
    public void keyTyped(KeyEvent e){
        // Get the source object that fired the event
        JTextField source = (JTextField)e.getSource();

        // Scan JTextFileds for all rows and columns, and match with the source object
        FIND_FIELD:
        for (int row = 0; row < GRID_SIZE; ++row) {
            for (int col = 0; col < GRID_SIZE; ++col) {
                if (tfCells[row][col] == source) {
                    rowSelected = row;
                    colSelected = col;
                    break FIND_FIELD;
                }
            }
        }
        /* 1. Get the input String 
           2. Assume that the solution is unique. Compare the input number 
              with the number in the puzzle[rowSelected][colSelected].  
              If they are the same,set the background to green(Color.GREEN); 
              otherwise, set to red (Color.RED).
         */

        String inputString = tfCells[rowSelected][colSelected].getText();
        if (Integer.parseInt(inputString)==puzzle[rowSelected][colSelected]) {

            tfCells[rowSelected[colSelected].setBackground(OPEN_CELL_TEXT_YES);
            masksGen.setCellMasks(rowSelected, colSelected, false);
            tfCells[rowSelected][colSelected].setEditable(false);
        } else {
            tfCells[rowSelected][colSelected].setBackground(OPEN_CELL_TEXT_NO);
        }


        //Check conflicts in row and col, the bg turn blue
        for (int row = 0; row < GRID_SIZE; ++row) {
            if ((tfCells[row][colSelected] == tfCells[rowSelected][colSelected])
                    && (row != rowSelected)){
                tfCells[row][colSelected].setBackground(CONFLICT_BGCOLOR);
            }
        }

        for (int col = 0; col < GRID_SIZE; ++col) {
            if ((tfCells[rowSelected][col] == tfCells[rowSelected][colSelected])
                    && (col != colSelected)) {
                tfCells[rowSelected][col].setBackground(CONFLICT_BGCOLOR);
            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...