【问题标题】:Changing cell background on click in another cell单击另一个单元格时更改单元格背景
【发布时间】:2012-09-28 00:04:03
【问题描述】:

我正在尝试构建一个 9x9 数独游戏。对于 UI 部分,我想在单击时更改单元格的背景,并在单击任何其他单元格时恢复正常。下面是我的 Cell Class。

    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));
        }
    }

}

但是,在单击一个单元格然后再单击另一个单元格后恢复为正常的背景颜色和单元格边框不起作用。请帮忙。提前致谢。

【问题讨论】:

    标签: java swing background jpanel mouselistener


    【解决方案1】:

    您最好使用AbstractButton,例如JButton,它为每个受支持的外观和感觉都包含此功能。您可以使用UIManager.put() 覆盖下面列出的按钮相关键的默认值,如here 所示。这个CellTest 也可能提出一些想法。右键单击以查看上下文菜单,然后单击选项卡以查看焦点侦听器的工作原理。

    按钮.背景 按钮边框 Button.darkShadow Button.defaultButtonFollowsFocus Button.disabledText 按钮字体 按钮.前景 按钮高亮 Button.light 按钮边距 Button.opaque 按钮选择 按钮阴影 Button.textIconGap Button.textShiftOffset

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-14
      • 2021-01-04
      • 2011-11-07
      • 1970-01-01
      相关资源
      最近更新 更多