所以我正在尝试创建国际象棋,并开始构建我将用作棋盘的东西。在这段代码中,我能够“切换”两个按钮的位置,但是,每次我点击任何一个按钮时,为了测试目的调用Rook类,它会导致一个新的JFrame打开一个未知的原因。
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;
}
}
}
}
我知道目前代码没有那么多,但我想知道如何阻止新的JFrame在每次点击时打开。
任何帮助将不胜感激!谢谢!
答案 0 :(得分:1)
您正在对您的作品进行ChessTesting1
扩展,因此,当您实例化new Bishop (x, y);
之类的内容时,您也会调用超级构造函数,因此正在创建一个新的{{1} }} 每次。从一个OOP来看,棋子延伸JFrame
是没有意义的,因此,你应该仔细重新考虑你的设计。我建议阅读有关设计模式的内容,例如模型视图控制器(MVC)。
请考虑以下事项:
ChessTesting1
将出现两个import java.awt.EventQueue;
import javax.swing.JFrame;
public class SuperClass {
public SuperClass() {
JFrame frame = new JFrame();
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new SuperClass();
new ChildClass();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
public class ChildClass extends SuperClass {
public ChildClass() {
// implicit super() call
}
}
元素,因为JFrame
通过ChildClass
的构造函数中的隐式SuperClass
调用扩展了super()
的功能。