我正在尝试构建一个 9x9 数独游戏。对于 UI 部分,我想在单击时更改单元格的背景,并在单击任何其他单元格时恢复正常。下面是我的单元格类。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.BevelBorder;
public class Cell extends JPanel implements MouseListener{
Cell[][] cell;
private int x;//x pos;
private int y;//y pos;
private int num=0;
private JLabel lnum;
private Color bg;
private static int xpos=-1;
private static int ypos=-1;
private static Color back;
public Cell(Cell[][] cell,int x, int y)
{
this.cell=cell;
this.x=x;
this.y=y;
x+=1; y+=1;
setBorder(BorderFactory.createLineBorder(Color.yellow));
if((x%6>=1&&x%6<=3)&&(y%6==0||y%6>3)||(y%6>=1&&y%6<=3)&&(x%6==0||x%6>3))
bg=Color.BLUE;
else
bg=Color.BLACK;
setBackground(bg);
setPreferredSize(new Dimension(50,50));
lnum=new JLabel(String.valueOf(num),null,JLabel.CENTER);
lnum.setForeground(Color.green);
add(lnum,SwingConstants.CENTER);
addMouseListener(this);
}
@Override
public void mouseClicked(MouseEvent e) {
if(xpos!=-1)
{
cell[xpos][ypos].setBackground(back);
cell[xpos][ypos].setBorder(BorderFactory.createLineBorder(Color.yellow));
}
xpos=x;
ypos=y;
back=bg;
setBackground(Color.LIGHT_GRAY);
setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED,
Color.cyan,Color.BLUE));
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
if(x!=xpos&&y!=ypos)
{
setBackground(Color.WHITE);
setBorder(BorderFactory.createLineBorder(Color.RED));
}
}
@Override
public void mouseExited(MouseEvent e) {
if(x!=xpos&&y!=ypos)
{
setBackground(bg);
setBorder(BorderFactory.createLineBorder(Color.yellow));
}
}
}
但是,在单击一个单元格然后再单击另一个单元格后恢复为正常背景颜色和单元格边框不起作用。请帮忙。提前致谢。