java中要实现,点击一个按钮,就同时改变周围按钮背景颜色的事件怎么写
如题,假如是一个9*9的网格布局81个按钮,我点其中一个按钮,就会同时改变这按钮上下左右和本身的背影颜色,请问一下,这个事件要怎么写?...
如题,假如是一个9*9的网格布局81个按钮,我点其中一个按钮,就会同时改变这按钮上下左右和本身的背影颜色,请问一下,这个事件要怎么写?
展开
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);
}
}
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);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询