Updating Jframe based on JLabel Click

91 views Asked by At

I am currently making a "Super Tic-Tac-Toe" application in Java. Here is a description of what I am aiming for. http://mathwithbaddrawings.com/ultimate-tic-tac-toe-original-post. However I am having problems updating the Jframe on click. My application is made of individual cells (JLabels) that make up the Tic-Tac-Toe boards (JPanels) which will reside in a JFrame.

My problem is that using getSource on MouseClick will only get me as seep as my JPanel, and I cannot access which cell of the tic-tac-toe grid was pressed. Is there a way to check which one is pressed with my current method of organizing this project?

Here is My Code for viewing a ticTacToe Board that contains the listener:

public class TicTacToeView extends JPanel {
    public CellView[][] cv;
    public TicTacToe ttt;
    public TicTacToeView(TicTacToe t) {
        int rows = 3;
        int columns = 3;
        cv = new CellView[3][3];
        ttt = t;

        setSize(3 * 64, 3 * 64);
        setBackground(Color.white);
        setLayout(new GridLayout(rows, columns));
        setVisible(true);
        setFocusable(true);
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j ++) {
                System.out.println(ttt.getCellAt(i, j).toString());
                cv[i][j] = new CellView(ttt.getCellAt(i, j));
                cv[i][j].addMouseListener(new yourListener());
                add(cv[i][j]);
            }
        }

        setVisible(true);
    }

    public String toString() {
        return ttt.toString();
    }

    public class yourListener extends MouseAdapter{ 
        public void mouseClicked(MouseEvent e){

            CellView labelReference=(CellView)e.getSource();
            Cell cellClicked = labelReference.getCell();

            System.out.println(cellClicked.getCol() +"," + cellClicked.getRow());
            cellClicked.setState(CellState.O);
            ttt.setCellAt(cellClicked.getCol(), cellClicked.getRow(), CellState.O);
            System.out.println(ttt.toString());

       }
    }
}

Right now when i System.out it changes the correct cell to O as expected. But I don't know how I would update the frame from here as the gameFrame is made out of this.

2

There are 2 answers

4
nom On

First of all, stop using a separate class for the MouseListener, this is the source of your problem. Directly add a mouse listener to cv[i][j]. You will be able to update your frame because now the mouse listener is also in the same class.

Cheers.

0
MadProgrammer On

My problem is in telling the Frame to update that cell. Sorry that my explanation is unclear.

While there are ways to find the frame from the CellView, it's not required, instead, when CellView#setState is called, it should be calling revalidate and repaint on itself