【问题标题】:If condition for 9 Jbuttons simultaneously?如果同时满足 9 个 Jbuttons 的条件?
【发布时间】:2020-12-29 18:13:00
【问题描述】:

if condition working for only one button at a time我已经编写了 9 个 Jbuttons 以在鼠标单击时随机返回 8 种颜色中的一种。我添加了一个返回结果的 Jlabel - 我希望结果返回一个“赢家!”如果所有 Jbutton 的颜色相同,则为字符串。

这是完整的代码!

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import static java.awt.Color.*;

public class buttonTest {

    public static void main(String[] args) {

        new buttonTest();
    }

    public buttonTest() { //CONSTRUCTOR.
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("Colour Button 4.0"); 
                frame.add(new colourButton()); 
                frame.pack(); 
                frame.setLocationRelativeTo(null); 
                frame.setVisible(true);
            }
        });
    }

    public class colourButton extends JPanel implements ActionListener { 
        Random rand = new Random(); 
        JButton buttons[]; // created a button array.
        JLabel gameRules = new JLabel("Match the colour buttons."); 
        JLabel timer = new JLabel("00:00 (placeholder)");
        JLabel result = new JLabel("Result: (placeholder)");
        byte value = 0;

        public colourButton() {

            add(gameRules); 
            buttons = new JButton[9];
            setLayout(new GridLayout(3, 3));
            for (int i = 0; i < buttons.length; i++) { 
                buttons[i] = new JButton("colour button"); 
                buttons[i].setBorderPainted(false); 
                buttons[i].setContentAreaFilled(false); 
                buttons[i].setOpaque(true);
                buttons[i].addActionListener(this); 
                add(buttons[i]);
                add(timer);
                add(result);
                setVisible(true); 
            }
        }

        @Override
        public void actionPerformed(ActionEvent e) {

            if (!(e.getSource() instanceof JButton)) { 
                return;
            }

            String clickedbutton = e.getActionCommand();
            System.out.println(clickedbutton + " button clicked.");
           
            JButton button = (JButton) e.getSource(); 

            value++; 
            value %= 9; 
            switch (rand.nextInt(9)) { 
                case 0:
                    button.setBackground(null); 
                case 1:
                    button.setBackground(red);
                    break;
                case 2:
                    button.setBackground(orange);
                    break;
                case 3:
                    button.setBackground(yellow);
                    break;
                case 4:
                    button.setBackground(green);
                    break;
                case 5:
                    button.setBackground(cyan);
                    break;
                case 6:
                    button.setBackground(blue);
                    break;
                case 7:
                    button.setBackground(MAGENTA);
                    break;
                case 8:
                    button.setBackground(pink);
                    break;
            }
            if (button.getBackground() == magenta) {
                result.setText("magenta");
            } else {
                result.setText("placeholder result");
            }
        }
    }
}

我想它在逻辑上是这样的:

如果按钮数是 9 并且都是 'this' 颜色,则返回这个字符串。

【问题讨论】:

  • 提供清晰的描述,显示所有相关代码,并准确告诉我们哪些(不)有效。
  • 循环遍历按钮列表并比较每个调用actionPerformed方法的结果
  • 另外,如果您可以添加 UI 图像并清楚地描述功能
  • 更好的是,让每个按钮更新一个模型并检查它的获胜状态
  • 好的,我已经添加了完整的代码 - 希望对您有所帮助!我还使用了一个按钮数组,我可以“展开循环”并将 9 个按钮放在 if 语句中吗?

标签: java swing if-statement colors jbutton


【解决方案1】:

创建 Swing 应用程序时,还应该创建应用程序的逻辑模型。这是model / view / controller 模式的示例。

通过分离 Swing 应用程序的逻辑部分,您可以一次专注于应用程序的一个部分。

这是我测试过的 GUI。如您所见,结果文本显示“Winner!”。

我创建了一个GameModel 类来保存游戏模型,并创建了一个ButtonModel 类来保存JButton 的值和颜色。

测试所有九个 ButtonModel 的方法是 GameModel 类的 isMatch 方法。您可以看到使用模型如何极大地简化了ColourButton 类的actionListener 方法。

这是代码。

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class JButtonTesting {

    public static void main(String[] args) {
        new JButtonTesting();
    }

    private GameModel model;

    public JButtonTesting() { // CONSTRUCTOR.
        this.model = new GameModel();
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("Colour Button 4.0");
                frame.add(new ColourButton());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class ColourButton extends JPanel implements ActionListener {
        private static final long serialVersionUID = 1L;

        Random rand = new Random();
        JButton buttons[]; // created a button array.
        JLabel gameRules = new JLabel("Match the colour buttons.");
        JLabel timer = new JLabel("00:00 (placeholder)");
        JLabel result = new JLabel("Result: (placeholder)");
        int value = 0;

        public ColourButton() {
            setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
            gameRules.setAlignmentX(JLabel.CENTER_ALIGNMENT);
            add(gameRules);
            JPanel buttonPanel = createButtonPanel();
            add(buttonPanel);
            timer.setAlignmentX(JLabel.CENTER_ALIGNMENT);
            add(timer);
            result.setAlignmentX(JLabel.CENTER_ALIGNMENT);
            add(result);
        }

        private JPanel createButtonPanel() {
            JPanel buttonPanel = new JPanel();
            buttons = new JButton[9];
            buttonPanel.setLayout(new GridLayout(0, 3));
            for (int i = 0; i < buttons.length; i++) {
                buttons[i] = new JButton("colour button");
                buttons[i].setActionCommand(Integer.toString(i));
                buttons[i].setBorderPainted(false);
                buttons[i].setContentAreaFilled(false);
                buttons[i].setOpaque(true);
                buttons[i].addActionListener(this);
                buttonPanel.add(buttons[i]);
            }
            return buttonPanel;
        }

        public void setButtonColour(int index, Color colour) {
            buttons[index].setBackground(colour);
        }

        @Override
        public void actionPerformed(ActionEvent event) {
            if (!(event.getSource() instanceof JButton)) {
                return;
            }

            int buttonIndex = Integer.valueOf(event.getActionCommand());
            System.out.println(buttonIndex + " button clicked.");

            value++;
            value %= 9;
            
            model.setColour(buttonIndex, value);
            setButtonColour(buttonIndex, model.getColour(buttonIndex));
            
            if (model.isMatch()) {
                result.setText("Winner!");
            }
        }

    }

    public class GameModel {

        private Color[] colours = { null, Color.RED, Color.ORANGE, Color.YELLOW, 
                Color.GREEN, Color.CYAN, Color.BLUE,
                Color.MAGENTA, Color.PINK };

        private ButtonModel[] buttonValues;

        public GameModel() {
            buttonValues = new ButtonModel[9];
            for (int i = 0; i < buttonValues.length; i++) {
                buttonValues[i] = new ButtonModel();
                setColour(i, 0);
            }
        }
        
        public Color getColour(int index) {
            return buttonValues[index].getColour();
        }
    
        public void setColour(int index, int value) {
            buttonValues[index].setValue(value);
            buttonValues[index].setColour(colours[value]);
        }

        public boolean isMatch() {
            int value = buttonValues[0].getValue();
            for (int i = 1; i < buttonValues.length; i++) {
                if (buttonValues[i].getValue() != value) {
                    return false;
                }
            }
            return true;
        }
    }

    public class ButtonModel {

        private int value;

        private Color colour;

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }

        public Color getColour() {
            return colour;
        }

        public void setColour(Color colour) {
            this.colour = colour;
        }

    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 2019-07-19
    • 1970-01-01
    相关资源
    最近更新 更多