Java:使用MouseListener更改相邻按钮的颜色
我有一个15 x 15 2D的Java:使用MouseListener更改相邻按钮的颜色,java,jbutton,mouselistener,Java,Jbutton,Mouselistener,我有一个15 x 15 2D的JButton数组 当我按住其中一个按钮(即按钮[I][j])时, 我想更改相邻按钮的颜色(即按钮[I-1][j],按钮[I+1][j],按钮[I][j-1],按钮[I][j+1]) 我该怎么做 下面是我的2D阵列实现的一部分。这个按钮现在没有任何作用 fb = new JButton[15][15]; for(int i = 0; i < 15; i++){ for(int j = 0; j < 15; j++){
JButton
数组
当我按住其中一个按钮(即按钮[I][j]
)时,
我想更改相邻按钮的颜色(即按钮[I-1][j]
,按钮[I+1][j]
,按钮[I][j-1]
,按钮[I][j+1]
)
我该怎么做
下面是我的2D阵列实现的一部分。这个按钮现在没有任何作用
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]);
}
}
fb=newjbutton[15][15];
对于(int i=0;i<15;i++){
对于(int j=0;j<15;j++){
fb[i][j]=新的JButton();
fb[i][j].挫折地面(颜色.白色);
fb[i][j].setboorder(BorderFactory.createLineBorder(Color.BLACK,2));
fb[i][j].setPreferredSize(新维度(40,40));
//fb[i][j].setEnabled(假);
加上(fb[i][j]);
}
}
尝试此功能块:
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);
}
}
如果(i-1>=0){
如果(fb[i-1][j]!=null){
fb[i-1][j].立根背景(颜色.红色);
}
}否则如果(i+1<15){
如果(fb[i+1][j]!=null){
fb[i+1][j].立根背景(颜色.红色);
}
}如果(j-1>=0),则为else{
如果(fb[i][j-1]!=null){
fb[i][j-1].立根背景(颜色.红色);
}
}否则如果(j+1<15){
如果(fb[i][j+1]!=null){
fb[i][j+1].立根背景(颜色.红色);
}
}
和听众:
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);
}
}
}
});
fb[i][j].addActionListener(新ActionListener()){
已执行的公共无效操作(操作事件e){
JButton b=(JButton)e.getSource();
int x,y;
对于(int i=0;i<15;i++){
对于(int j=0;j<15;j++){
如果(fb[i][j].等于(b)){
x=i;
y=j;
打破
}
}
}
如果(x-1>=0){
如果(fb[x-1][y]!=null){
fb[x-1][y].立根背景(颜色.红色);
}
}否则如果(x+1<15){
如果(fb[x+1][y]!=null){
fb[x+1][y].立根背景(颜色.红色);
}
}如果(y-1>=0),则为else{
如果(fb[x][y-1]!=null){
fb[x][y-1].立根背景(颜色.红色);
}
}如果(y+1<15),则为else{
如果(fb[x][y+1]!=null){
fb[x][y+1]。立根背景(颜色:红色);
}
}
}
});
请添加您的代码我添加了我的代码,但我认为这并不重要,因为它实际上是15 x 15个按钮,仅此而已。MouseListener如何知道我和j的价值?我算出了!谢谢。我是这样做的:j=arg0.getComponent().getX()/40;i=arg0.getComponent().getY()/40;有没有更好的办法?(40是我为每个按钮设置的尺寸)