所以,我正在制作一个棋盘,每当我尝试按下按钮时,它们都会不断重新定向,并且在右下角变得越来越乱。右上角的第一个按钮 (squareB[0][0]) 看起来不错,但所有其他 JButton 都搞砸了。
所以我的问题是如何解决这个问题或允许我将按钮放置在特定坐标处?
import java.awt.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.io.*;
public class Test implements ActionListener
{
private JFrame frame = new JFrame();
private JPanel[][] square = new JPanel[8][8];
private JButton[][] button = new JButton[8][8];
public static void main(String[] args)
{
new Test();
}
Test()
{
frame.setLayout(new GridLayout(8,8));
for(int x=0; x<8; x++)
{
for(int y=0; y<8; y++)
{
square[x][y] = new JPanel();
frame.add(square[x][y]);
square[x][y].setSize(100,100);
square[x][y].setLayout(new GridLayout(1,1));
if(y%2==0)
if(x%2==0)
square[x][y].setBackground(Color.white);
else
square[x][y].setBackground(Color.black);
if(y%2!=0)
if(x%2==0)
square[x][y].setBackground(Color.black);
else
square[x][y].setBackground(Color.white);
button[x][y] = new JButton();
button[x][y] = new TestMethods(x,y);
square[x][y].add(button[x][y]);
button[x][y].setOpaque(false);
button[x][y].setContentAreaFilled(true);
button[x][y].setBorderPainted(true);
button[x][y].addActionListener(this);
}
}
frame.setSize(800,800);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
}
}
class TestMethods extends JButton
{
private int x, y;
public TestMethods(int x, int y)
{
this.x = x;
this.y = y;
}
public int getX() {return x;}
public int getY() {return y;}
}