gpt4 book ai didi

Java:使用MouseListener更改相邻JButton的颜色

转载 作者:行者123 更新时间:2023-11-30 02:36:23 25 4
gpt4 key购买 nike

我有一个 15 x 15 的 JButton 二维数组。

当我按住其中一个按钮(即 Button[i][j])时,我想更改相邻按钮的颜色(即 Button[i-1][j]Button[i+1][j]Button [i][j-1]按钮[i][j+1])。

我该怎么做?

下面是我的二维数组实现的一部分。该按钮目前不执行任何操作。

    fb = new JButton[15][15];

for(int i = 0; i < 15; i++){
for(int j = 0; j < 15; j++){
fb[i][j] = new JButton();
fb[i][j].setBackground(Color.WHITE);
fb[i][j].setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
fb[i][j].setPreferredSize(new Dimension(40, 40));
//fb[i][j].setEnabled(false);
grid.add(fb[i][j]);
}
}

最佳答案

尝试这个 block :

            if (i - 1 >= 0) {
if (fb[i - 1][j] != null) {
fb[i - 1][j].setBackground(Color.RED);
}
} else if (i + 1 < 15) {
if (fb[i + 1][j] != null) {
fb[i + 1][j].setBackground(Color.RED);
}
} else if (j - 1 >= 0) {
if (fb[i][j - 1] != null) {
fb[i][j - 1].setBackground(Color.RED);
}
} else if (j + 1 < 15) {
if (fb[i][j + 1] != null) {
fb[i][j + 1].setBackground(Color.RED);
}
}

和监听器:

            fb[i][j].addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {
JButton b = (JButton) e.getSource();
int x, y;
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
if(fb[i][j].equals(b)){
x = i;
y = j;
break;
}
}
}

if (x - 1 >= 0) {
if (fb[x - 1][y] != null) {
fb[x - 1][y].setBackground(Color.RED);
}
} else if (x + 1 < 15) {
if (fb[x + 1][y] != null) {
fb[x + 1][y].setBackground(Color.RED);
}
} else if (y - 1 >= 0) {
if (fb[x][y - 1] != null) {
fb[x][y - 1].setBackground(Color.RED);
}
} else if (y + 1 < 15) {
if (fb[x][y + 1] != null) {
fb[x][y + 1].setBackground(Color.RED);
}
}

}
});

关于Java:使用MouseListener更改相邻JButton的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42947061/

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