gpt4 book ai didi

java - 如何使用二维按钮阵列刷新面板?

转载 作者:行者123 更新时间:2023-12-02 00:45:29 24 4
gpt4 key购买 nike

我正在用 Java 制作一个国际象棋游戏。因为我是 Swing 的初学者,所以我马上就遇到了问题。我为棋盘图 block 制作了一个二维按钮数组。问题是当我单击第一个按钮时,我不知道如何刷新该按钮或其所在的面板。

这是代码。

public class Table extends JFrame implements ActionListener{

public JButton[][]tile = new JButton[8][8];
JPanel gamePAN = new JPanel();
int size=8;
Tile[][] tileList = new Tile[8][8];

private final Color lightTileColor = Color.decode("#FFFACD");
private final Color darkTileColor = Color.decode("#593E1A");

public Table() {

this.setResizable(true);
this.setVisible(true);
this.setTitle("Chess");
initCompoments();

Toolkit tk = Toolkit.getDefaultToolkit();

int xsize = (int) tk.getScreenSize().getWidth();
int ysize = (int) tk.getScreenSize().getHeight();

this.setSize(xsize, ysize);

private void initCompoments() {

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);

gamePAN.setLayout(new java.awt.GridLayout(8, 8, 0, 0));
getContentPane().add(gamePAN);
gamePAN.setBounds(550, 100, 800, 800);

pack();
}

private void initialize() {
//gamePAN = new JPanel();
//gamePAN.setLayout(new GridLayout(size,size));
for(int i=0;i<size;i++) {
for(int j=0; j<size;j++) {
if(i%2==0) {
if(j%2==0) {
tile[i][j] = new JButton();
tile[i[j].setBackground(lightTileColor)
tile[i[j].addActionListener(this);
tile[i][j].setSize(10,10);
gamePAN.add(tile[i][j]);
}else {
tile[i][j] = new JButton();
tile[i[j].setBackground(darkTileColor);
tile[i[j].addActionListener(this);
tile[i][j].setSize(10,10);
gamePAN.add(tile[i][j]);
}
}else {
if(j%2==0) {
tile[i][j] = new JButton();
tile[i[j].setBackground(darkTileColor);
tile[i][j].addActionListener(this);
tile[i][j].setSize(10,10);
gamePAN.add(tile[i][j]);
}else {
tile[i][j] = new JButton();
tile[i[j].setBackground(lightTileColor);
tile[i][j].addActionListener(this);
tile[i][j].setSize(10,10);
gamePAN.add(tile[i][j]);
}
}
}
}

@Override
public void actionPerformed(ActionEvent ae) {

for(int r=0;r<size;r++) {
for(int c=0;c<size;c++) {
if(ae.getSource()==tile[r][c]) {
if(tileList[r[c].getPiece()!=null) {
tileList[r][c].getPiece().kretanje(tile, tileList);
}
}

}
}

最佳答案

The problem is when my first button is clicked I do not know how to refresh that button or the panel it is in

不需要 ActionListener 中的所有循环代码。

ActionEvent 将包含对所单击按钮的引用。

因此,在 ActionListener 中,您添加到按钮的基本代码将是:

JButton button = (JButton)ae.getSource();
button.setIcon(...); // do whatever you want with the button

关于java - 如何使用二维按钮阵列刷新面板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57903944/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com