java中要实现,点击一个按钮,就同时改变周围按钮背景颜色的事件怎么写

2024-11-15 01:56:35
推荐回答(1个)
回答1:

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

/**
*
* @description:
*
* @author Daniel
*
*/
public class City extends JFrame implements ActionListener {
private JButton[][] btns = new JButton[9][9];

public City() {
super("81个按钮");
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 455, 475);
init();
setResizable(false);
setVisible(true);
}

private void init() {
int width = 50;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
btns[i][j] = new JButton(i + "" + j);
btns[i][j].setBounds(i * width, j * width, width, width);
this.add(btns[i][j]);
btns[i][j].addActionListener(this);
}
}
}

public static void main(String[] args) {
new City();
}

public void actionPerformed(ActionEvent e) {
int i = 0, j = 0;
for (i = 0; i < 9; i++) {
boolean find = false;
for (j = 0; j < 9; j++) {
if (btns[i][j] == e.getSource()) {
find = true;
break;
}
}
if (find) {
break;
}
}
// 改变上,下,左,右
changeBg(i, j);
changeBg(i - 1, j);
changeBg(i + 1, j);
changeBg(i, j - 1);
changeBg(i, j + 1);
}

private void changeBg(int i, int j) {
if (i < 0 || i >= 9) {
return;
} else if (j < 0 || j >= 9) {
return;
}
btns[i][j].setBackground(Color.BLUE);
}
}