I need to know how I can set up a action listener for an array of buttons. I am trying to make a tic tac toe game. I am new to programming. I have seen someone on here ask a similar question but I could not grasp what they where doing because my program is set up different.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class tictactoe extends JFrame{
public static JMenuBar MenuBar = new JMenuBar();
JMenu File = new JMenu("File");
JMenu Help = new JMenu("Help");
JMenu Options = new JMenu("Options");
JMenuItem NewGame = new JMenuItem("New Game");
JMenuItem Exit = new JMenuItem("Exit");
JMenuItem About = new JMenuItem("About");
JMenuItem Sound = new JMenuItem("Sound");
JButton[] button = new JButton[9];
JPanel p1 = new JPanel();
int user = 1;// sets user count for X and Circle
public tictactoe(){
add(p1);
p1.setVisible(false);
MenuBar.add(File);
MenuBar.add(Help);
MenuBar.add(Options);
File.add(NewGame);
File.add(Exit);
Help.add(About);
Options.add(Sound);
Exit.addActionListener(new ExitListener1());
NewGame.addActionListener(new NewGameListener());
}
public void Xwin(){
JOptionPane.showMessageDialog(null,"X wins");}
public void Ywin(){
JOptionPane.showMessageDialog(null,"Y wins");}
public void reset(){
for(int i=1;i<10; i++){//adds 9 buttons
button[i] = new JButton("");//
button[i].addActionListener(new Button());//adds Button Listener. Will This work?
p1.add(button[i]);}
p1.setLayout(new GridLayout(3,3,0,0));
user = 1;// Makes sure that user is set back to X
p1.setVisible(true);}
public class Button implements ActionListener{
public void actionPerformed(ActionEvent b){
if(user == 1){
//button that user presses will equal x;?????????????
//(button user presses).setText("X");
user++;}//sets user to 2 for Circles Choice
else{
// button that user presses will read O
//(button user presses).setText("X");
user--;}//sets user back to one for X choice}
}}
public class NewGameListener implements ActionListener{
public void actionPerformed(ActionEvent a){
reset();}}
public class ExitListener1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(1);}}
public static void main(String[] args) {
JFrame Frame = new tictactoe();
Frame.setSize(500, 500);
Frame.setVisible(true);
Frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
Frame.setJMenuBar(MenuBar);}}