I'm trying to make a chess-board kind of thing with each tile being a JButton. I want to add the same actionListener to every button. Here's the code:
package checker;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class mainClass extends JFrame {
JPanel board = new JPanel();
ActionListener btnPrs = new btnPressed();
public mainClass()
{
board.setLayout(new GridLayout(8,8,0,0));
for(int i = 0; i<8; i++)
for(int j = 0; j<8; j++)
{
if( i%2 == 0 && j%2 == 0 || i%2 == 1 && j%2 == 1)
{
board.add(new DrawWhite());
//board.add(new DrawWhite().addActionListener(btnPrs));
}
else board.add(new DrawBlack());
}
add(board);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
mainClass frame = new mainClass();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
frame.setTitle("Checker");
frame.setLocationRelativeTo(null);
}
class DrawWhite extends JButton
{
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.WHITE);
g.fillRect(0,0, 50,50);
}
}
class DrawBlack extends JButton
{
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, 50, 50);
}
}
class btnPressed implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("pressed!");
}
}
}
I don't want to explicitly define 64 buttons and add ActionListeners to each of them manually. I tried they way that is included as a comment on line 23. Is there a proper way to do it?
Any help would be highly appreciated.