So I'm trying to create Chess and to start I'm building what I will use as the board. In this code, I'm able to "switch" the positions of two buttons, however, every time I click any one of the buttons, which for testing purposes calls on the Rook class, it causes a new JFrame to open for an unknown reason.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ChessTesting1 extends JFrame implements ActionListener
{
JButton tiles[] [] = new JButton [8] [8];
public int x, y, turn;
String buttonSwitch, buttonText = "";
JFrame frame;
public static void main (String args[])
{
new ChessTesting1 ();
}
public ChessTesting1 ()
{
frame = new JFrame ();
frame.setSize (800, 800);
frame.setLocation (150, 50);
frame.setResizable (false);
frame.setDefaultCloseOperation (WindowConstants.EXIT_ON_CLOSE);
JPanel contentPane = (JPanel) frame.getContentPane ();
contentPane.setLayout (new GridLayout (8, 8));
for (int x = 0 ; x < 8 ; x++)
{
for (int y = 0 ; y < 8 ; y++)
{
tiles [x] [y] = new JButton ("" + (y + 1));
}
}
for (int x = 0 ; x < 8 ; x++)
{
for (int y = 0 ; y < 8 ; y++)
{
contentPane.add ((tiles [x] [y]));
tiles [i] [j].addActionListener (this);
}
}
frame.show ();
}
public void actionPerformed (ActionEvent e)
{
Object command = e.getSource ();
for (int i = 0 ; i < 8 ; i++)
{
for (int j = 0 ; j < 8 ; j++)
{
if (command == tiles [i] [j])
{
if (turn == 0)
{
buttonText = tiles [i] [j].getText ();
x = i;
y = j;
new Bishop (x, y);
frame.dispose ();
buttonSwitch = buttonText;
turn++;
}
else
{
tiles [x] [y].setText (tiles [i] [j].getText ());
tiles [i] [j].getText ();
tiles [i] [j].setText ("" + buttonSwitch);
turn = 0;
}
buttonText = tiles [x] [y].getText ();
}
}
}
}
}
Bishop Class:
public class Bishop extends ChessTesting1
{
public Bishop (int x, int y)
{
for (int i = 0 ; i < 8 ; i++)
{
for (int j = 0 ; j < 8 ; j++)
{
this.tiles [i] [j].setEnabled (false);
}
}
for (int i = 0 ; i < 8 ; i++)
{
this.tiles [x + 1] [y + 1].setEnabled (true);
if ((x + 1) >= 8 || (y + 1) >= 8)
{
break;
}
}
for (int i = 0 ; i < 8 ; i++)
{
this.tiles [x + 1] [y - 1].setEnabled (true);
if ((x + 1) >= 8 || (y + 1) >= 8)
{
break;
}
}
for (int i = 0 ; i < 8 ; i++)
{
this.tiles [x - 1] [y + 1].setEnabled (true);
if ((x + 1) >= 8 || (y + 1) >= 8)
{
break;
}
}
for (int i = 0 ; i < 8 ; i++)
{
this.tiles [x - 1] [y - 1].setEnabled (true);
if ((x + 1) >= 8 || (y + 1) >= 8)
{
break;
}
}
}
}
I'm aware that currently the code doesn't do much, but I was wondering how I could stop a new JFrame from opening on each click.
Any help would be appreciated! Thanks!