I want to create an array of 9 buttons (btn[3][3]) and then check to see if the button at index [2][2] was clicked. I just cant seem to get the code to work. Any help is appreciated.
Code:import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ButtonArray extends JFrame implements ActionListener { JButton btn[][]; public ButtonArray() { Container pane = getContentPane(); FlowLayout flo = new FlowLayout(); setSize(300,300); setTitle("Array of Buttons"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //here I want to create 9 buttons and add an actionListener to them and add them to the pane for (int x=0; x<3; x++) { for (int y=0; y<3; y++) { btn[x][y] = new JButton(); btn[x][y].addActionListener(this); pane.add(btn[x][y]); } } pane.setLayout(flo); setContentPane(pane); setVisible(true); } public void actionPerformed(ActionEvent e) { //I would like to check to see if the button that was clicked is at [2][2] //If so just a simple println method for (int x=0; x<3; x++) { for (int y=0; y<3; y++) { if (e.getSource == btn[2][2]) { System.out.println("Button at index[2][2] was clicked"); } } } } public static void main(String[] args) { ButtonArray ba = new ButtonArray(); } }


Reply With Quote