import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.function.IntConsumer;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Board {
private int cellRow,cellCol;
private JFrame frame;
private JButton [][] btnArr;
private IntConsumer clickButton;
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int [] idx;
if (e.getSource() instanceof JButton) {
idx = getBtnIdx((JButton)e.getSource());
String text = "row = "+idx[0]+" col = "+idx[1];
cellRow = idx[0];
cellCol = idx[1];
clickButton.accept(0);
}
}
};
public void dansMethod(int x, IntConsumer aMethod) {
clickButton = aMethod;
}
public void messagBox(String message,String title){
JOptionPane.showMessageDialog(null, message,title,1);
}
public Board(int [][] arr){
cellRow = -1;
cellCol = -1;
frame = new JFrame();//creating instance of JFrame
frame.setSize(arr.length*50+arr.length*3,arr[0].length*50+arr[0].length*4);//400 width and 500 height
btnArr = new JButton[arr.length][arr[0].length];
for (int row=0;row<btnArr.length;row++){
for (int col=0;col<btnArr[0].length;col++){
btnArr[row][col] = new JButton("");
btnArr[row][col].setBounds(row*50+row, col*50+col, 50, 50);
btnArr[row][col].addActionListener(listener);
frame.add(btnArr[row][col]);
}
}
updateBoard(arr);
frame.setLayout(null);//using no layout managers
frame.setVisible(true);//making the frame visible
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
if (JOptionPane.showConfirmDialog(frame,
"Are you sure you want to end the game?", "End Game?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){
System.exit(0);
}
}
});
}
public int getCellRow() {
return cellRow;
}
public int getCellCol() {
return cellCol;
}
public void updateBoard(int [][] arr){
for (int row=0;row<btnArr.length;row++){
for (int col=0;col<btnArr[0].length;col++){
if (arr[row][col] == 1){
btnArr[row][col].setBackground(Color.red);
}
else if (arr[row][col] == 2){
btnArr[row][col].setBackground(Color.blue);
}
if (arr[row][col] == 3){
btnArr[row][col].setBackground(Color.green);
}
else if (arr[row][col] == 4){
btnArr[row][col].setBackground(Color.orange);
}
if (arr[row][col] == 5){
btnArr[row][col].setBackground(Color.yellow);
}
else if (arr[row][col] == 6){
btnArr[row][col].setBackground(Color.black);
}
else{
btnArr[row][col].setBackground(Color.gray);
}
}
}
}
private int[] getBtnIdx(JButton b){
int [] ret = {-1,-1};
for (int row=0;row<btnArr.length;row++){
for (int col=0;col<btnArr[0].length;col++){
if (btnArr[row][col] == b){
ret[0] = row;
ret[1] = col;
return ret;
}
}
}
return ret;
}
}