【问题标题】:How I check the color is match or not? (memory game with match color)我如何检查颜色是否匹配? (匹配颜色的记忆游戏)
【发布时间】:2018-07-19 14:44:39
【问题描述】:

我有 2 个数组,用于颜色和按钮

private JButton[] buttons = new JButton[16];
private Color[] c={
    Color.red,Color.yellow,Color.black,Color.magenta,
    Color.blue,Color.green,Color.cyan,Color.pink,
    Color.green,Color.black,Color.red,Color.pink,
    Color.magenta,Color.blue,Color.cyan,Color.yellow
};

布局是

DrawingPanel c=new DrawingPanel();
c.setLayout(new GridLayout(4,4));

当我点击 2 按钮时,2 按钮将被移除,那么如何检查 2 颜色(颜色在按钮背面)是否匹配?

public class bl implements ActionListener{
    public void actionPerformed(ActionEvent e){
        Component c = (Component)e.getSource();
        Color c1=Color.black,c2=Color.black;
        if(clickCount == 2){
            c.hide();
            c1 = c.getBackground();
            clickCount--;
        }if(clickCount ==1){
            c.hide();
            c2 = c.getBackground();
            clickCount--;
        }
        if(clickCount == 0 ){
            if(bx == by){
                System.out.println("Corret");
                clickCount=2;
            }
        }else{
            c.show();
        }
    }
} 

Full code

【问题讨论】:

标签: java swing awt graph-drawing


【解决方案1】:

您可以扩展 Button 类,使其能够保存其颜色的记录,然后每次都获取它以进行比较。

按钮需要记录它有什么颜色,或者无论如何都必须记录。

一般建议兄弟: 1. 给你的变量起有意义的名字:

    DrawingPanel c=new DrawingPanel();        
    c.setLayout(new GridLayout(4,4));

这样更好,让您的代码更易于阅读:

    DrawingPanel drawingPanel = new DrawingPanel();
    drawingPanel.setLayout(new GridLayout(4,4));
  1. 在各处添加描述性 cmets 也无妨,使代码更易于阅读。

要扩展 Button,你可以这样做:

    public class ColourButton extends JButton{

    private final String colourOfButton;

    public ColourButton(String colourOfButton){

    this.colourOfButton = colourOfButton;
    }

    public String getColour(){
     return colourOfButton;            
     }

      }

然后使用类似的东西来检查颜色匹配:

     public boolean hasColourMatch(ColourButton colourButton1, ColourButton colourButton2){
          if(colourButton1.getColour().equals(colourButton2.getColour())){
            return true;         
           }
            return false;
      }

希望这会有所帮助..

【讨论】:

    猜你喜欢
    • 2017-01-13
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 2021-01-11
    相关资源
    最近更新 更多