Reputation: 207
This is a 1st step of making tictactoe game using Java.
I want to print number 1 when click the button 1. There are 9 buttons but it doesn't work what is the wrong I printed the e.getsource
method and B1
button they are not same. Why is this happening?
package tictactoe;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TicTacToe implements ActionListener{
JFrame frame1;
JButton B1 = new JButton();
JButton B2 = new JButton();
JButton B3 = new JButton();
JButton B4 = new JButton();
JButton B5 = new JButton();
JButton B6 = new JButton();
JButton B7 = new JButton();
JButton B8 = new JButton();
JButton B9 = new JButton();
public void createGui(){
frame1 = new JFrame();
frame1.setTitle("TicTacToe");
frame1.setSize(600, 600);
frame1.setLayout(new GridLayout(3,3,0,0));
frame1.setLocationRelativeTo(null);
frame1.add(B1);
frame1.add(B2);
frame1.add(B3);
frame1.add(B4);
frame1.add(B5);
frame1.add(B6);
frame1.add(B7);
frame1.add(B8);
frame1.add(B9);
TicTacToe A1 = new TicTacToe();
B1.addActionListener(A1);
B2.addActionListener(A1);
B3.addActionListener(A1);
B4.addActionListener(A1);
B5.addActionListener(A1);
B6.addActionListener(A1);
B7.addActionListener(A1);
B8.addActionListener(A1);
B9.addActionListener(A1);
// frame1.pack();
frame1.setVisible(true);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==B1){
B1.setText("1");
}
}
public static void main(String[] args) {
TicTacToe T1 = new TicTacToe();
T1.createGui();
}
}
Upvotes: 0
Views: 123
Reputation: 5709
The reason for you program does not work is that you create a new TicTacToe that you use as parameter to the JButton.addActionListener()
. Try using this
instead and remove A1
.
B2.addActionListener(this);
Then it will work.
However I have a suggestion to a different approach than using JButton.addActionListener()
.
Instead you could use the JButton
constructor that takes an Action
as parameter. Implement your own Action
that extends AbstractAction
and then set the text in the actionPerformed()
method you need to implement.
You could let the Action
take a parameter with the text you want to write when pressed.
private class PressedAction extends AbstractAction {
private final String text;
public PressedAction(String text) {
this.text = text;
}
@Override
public void actionPerformed(ActionEvent e) {
((JButton) e.getSource()).setText(text);
}
}
Upvotes: 2