【问题标题】:Java game involving adjacent JButtons涉及相邻 JButton 的 Java 游戏
【发布时间】:2020-01-10 15:38:50
【问题描述】:

我正在制作一个涉及 JButtons (MxN) 网格的小游戏,主要前提是点击buttonA,然后点击buttonB,为buttonB 和与@987654326 相同颜色的相邻按钮着色@ 的颜色为buttonA。我已经做到了,因此您可以选择 3 个可能的困难。颜色是随机生成的。主要问题是改变颜色。

这是我选择游戏难度后调用的方法:

 public static void gameMechanics(int m, int n) {
    final String[] pickedColour = {""};
    final String[] placedColour = {""};
    JButton[][] picked = new JButton[m][n];
    JButton[][] placed = new JButton[m][n];
    picked[m][n].addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            pickedColour[0] = picked[m][n].getText();
        }
    });
    placed[m][n].addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            placedColour[0] = placed[m][n].getText();
        }
    });
    if (pickedColour[0] == "R" && placedColour[0] != "R") {
        placed[m][n].setBackground(Color.RED);
        placed[m][n].setText("R");
    }
    else if (pickedColour[0] == "G" && placedColour[0] != "G") {
        placed[m][n].setBackground(Color.GREEN);
        placed[m][n].setText("G");
    }
    else if (pickedColour[0] == "B" && placedColour[0] != "B") {
        placed[m][n].setBackground(Color.BLUE);
        placed[m][n].setText("B");
    }
}

【问题讨论】:

标签: java swing jbutton actionlistener


【解决方案1】:

我会考虑使用JPanels 并使用MouseListener 来绘制它们。

但是,如果您打算使用 JButtons,请尝试以下操作:

button.setBackground(Color.GREEN);
button.setOpaque(true);

请注意,如果您使用UIManager 设置外观和感觉,这可能不起作用

此外,您还需要做大量额外的工作来将颜色映射到按钮 - 这可能会让人感到困惑并导致错误。相反,您可以尝试创建自己的类:

class ColoredButton extends JButton {

        private static final long serialVersionUID = 3040767030924461426L;

        private Color color;

        public ColoredButton(Color c) {
            this.color = c;

            this.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    changeColor();
                }
            });
        }

        public void changeColor() {
            this.setBackground(this.color);
            this.setOpaque(true);
        }
    }

现在,您可以构造一个新的 ColoredButton:

// Now, this button will turn green when clicked
ColoredButton temp = new ColoredButton(Color.GREEN);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-22
    • 2017-02-10
    • 2013-01-14
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 2014-04-05
    相关资源
    最近更新 更多