【问题标题】:How to set the background of a button to a random colour with set constraints?如何将按钮的背景设置为具有设置约束的随机颜色?
【发布时间】:2019-04-05 11:44:36
【问题描述】:

我有一个函数可以将所有按钮的背景颜色设置为红色,目前它的工作原理是这样的,但是,我想做的是让它设置为具有设置约束的随机颜色,这些是可以选择的随机颜色的最大数量,以及分配给每个按钮的相同颜色的最大数量。

例如,如果随机颜色的最大数量为 8,相同颜色的最大数量为 2,则只会选择 8 种随机颜色,并且相同的颜色将仅分配给 2 个按钮。

这是针对我正在创建的配对游戏。我已经创建了一个函数,当所有按钮被单击时,它会为所有按钮设置随机颜色,但是,这没有我之前所说的约束。

【问题讨论】:

    标签: java swing jbutton


    【解决方案1】:

    这是错误的:

    for (int i = 0; i < arrayButtons.length; i++) {
        arrayButtons[i].setDrawColor(new Color(rand.nextInt()));
    }
    

    你需要用它们创建一半的随机颜色和颜色 2 按钮,然后随机排列数组。我会使用 ArrayList - 更容易洗牌和添加东西。所以假设有一个List&lt;ColorButton&gt; 叫buttonList:

    for (int i = 0; i < buttonList.size() / 2; i++) {
        Color color = new Color(rand.nextInt();
        buttonList.get(2 * i).setDrawColor(color));
        buttonList.get(2 * i + 1).setDrawColor(color));
    }
    Collections.shuffle(buttonList);
    

    或者如果你必须使用数组,并且会打乱数组:

    for (int i = 0; i < arrayButtons.length / 2; i++) {
        Color color = new Color(rand.nextInt();
        arrayButtons[2 * i].setDrawColor(color));
        arrayButtons[2 * i + 1].setDrawColor(color));
    }
    // shuffle your array here
    

    编辑:我改变了主意。最简单的方法是创建List&lt;Color&gt;,用 8 对不同的颜色填充它,随机播放,然后将颜色添加到按钮上。而不是随机颜色,如果您希望所有颜色都明亮,请使用 Color 的 .getHSBColor(...) 方法使用 8 种不同的色调颜色:

        List<Color> colorList = new ArrayList<>();
        for (int i = 0; i < 8; i++) {
            float hue = i * 1f / 8;
            Color c = Color.getHSBColor(hue, 1f, 1f);
            colorList.add(c);
            colorList.add(c);
        }
        Collections.shuffle(colorList);
        // add colors to buttons in for loop
    

    或者...

    colorList = new ArrayList<>();
    for (int i = 0; i < ROWS * COLS / 2; i++) {
        float r = (float) Math.random();
        float g = (float) Math.random();
        float b = (float) Math.random();
        Color color = new Color(r, g, b);
        colorList.add(color);
        colorList.add(color);
    }
    Collections.shuffle(colorList);
    
    // add colors to buttons using for loop
    

    我自己,我会做一些不同的事情:

    • 我不会扩展 JButton
    • 我会使用模型-视图-控制器程序结构的变体将模型从视图中分离出来
    • 所有逻辑都将保存在模型中,包括在ArrayList&lt;Integer&gt; 中随机打乱的随机 8 个数字对

    例如:

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class ColorTest extends JPanel {
        private static final int ROWS = 4;
        private static final int COLS = 4;
        private static final int BTN_W = 100;
        private static final int BTN_H = 100;
        private static final Dimension BTN_SIZE = new Dimension(100, 100);
        // how long to show mismatched color pairs
        private static final int COLOR_DISPLAY_DELAY = 2000; // msecs
        private static final int NO_PICK = -1;
        private List<ColorButton2> buttonList = new ArrayList<>();
        private List<Color> colorList = new ArrayList<>();
        private int firstPick = NO_PICK;
        private int secondPick = NO_PICK;
        private ButtonListener buttonListener = new ButtonListener();
        private boolean listenerEnabled = true;
    
        public ColorTest() {
            JPanel gridPanel = new JPanel(new GridLayout(ROWS, COLS));
            for (int index = 0; index < ROWS * COLS; index++) {
                ColorButton2 button = new ColorButton2(index, BTN_W, BTN_H);
                button.addActionListener(buttonListener);
                button.setPreferredSize(BTN_SIZE);
                buttonList.add(button);
                gridPanel.add(button);
            }
            reset();
    
            JButton resetButton = new JButton("Reset");
            resetButton.addActionListener(e -> reset());
            resetButton.setMnemonic(KeyEvent.VK_R);
            JButton exitButton = new JButton("Exit");
            exitButton.setMnemonic(KeyEvent.VK_X);
            exitButton.addActionListener(e -> System.exit(0));
            JPanel btnPanel = new JPanel(new GridLayout(1, 0));
            btnPanel.add(resetButton);
            btnPanel.add(exitButton);
            setLayout(new BorderLayout());
            add(gridPanel);
            add(btnPanel, BorderLayout.PAGE_END);
        }
    
        public void reset() {
            colorList = new ArrayList<>();
            for (int i = 0; i < ROWS * COLS / 2; i++) {
                // Color color = randomRgbColor();
                float hue = (2f * i) / (ROWS * COLS); // non-random hue
                Color color = randomHsbColor(hue); // randomize the saturation and
                                                   // brilliance
                colorList.add(color);
                colorList.add(color);
            }
            Collections.shuffle(colorList);
    
            for (int i = 0; i < buttonList.size(); i++) {
                ColorButton2 btn = buttonList.get(i);
                btn.reset();
                btn.setColor(colorList.get(i));
            }
        }
    
        @SuppressWarnings("unused")
        private Color randomRgbColor() {
            float r = (float) Math.random();
            float g = (float) Math.random();
            float b = (float) Math.random();
            Color color = new Color(r, g, b);
            return color;
        }
    
        private Color randomHsbColor(float hue) {
            // float hue = (float) Math.random();
            float sat = ((int) (2 * Math.random()) + 1) / 2f;
            float bril = ((int) (2 * Math.random()) + 1) / 2f;
            return Color.getHSBColor(hue, sat, bril);
        }
    
        private class ButtonListener implements ActionListener {
    
            @Override
            public void actionPerformed(ActionEvent e) {
                if (!listenerEnabled) {
                    // if button listener disabled -- get out of here
                    return;
                }
                ColorButton2 source = (ColorButton2) e.getSource();
                if (source.getNumber() == firstPick) {
                    // if user chooses same button twice, a mistake, so exit
                    return;
                }
                if (source.isPairMatched()) {
                    // button already matched
                    return;
                }
    
                source.flip(true); // show button's real color
    
                // if user has selected first button
                if (firstPick == NO_PICK) {
                    firstPick = source.getNumber(); // set first button pick field
                } else {
                    // else user has selected 2nd button
                    secondPick = source.getNumber();
    
                    // check if the two buttons hold the same color
                    Color c1 = buttonList.get(firstPick).getColor();
                    Color c2 = buttonList.get(secondPick).getColor();
                    if (c1.equals(c2)) {
                        // matching picks, then disable both buttons
                        buttonList.get(firstPick).setPairMatched(true);
                        buttonList.get(secondPick).setPairMatched(true);
                        // reset these variables
                        firstPick = NO_PICK;
                        secondPick = NO_PICK;
                        // check that the game isn't over
                        checkForWin();
                    } else {
                        // start timer to display buttons for period of time, then
                        // flip back
                        listenerEnabled = false; // disable all button's action
                                                 // listeners
                        new Timer(COLOR_DISPLAY_DELAY, e2 -> {
                            // show background color for both buttons
                            buttonList.get(firstPick).flip(false);
                            buttonList.get(secondPick).flip(false);
    
                            // re-enable the action listener
                            listenerEnabled = true;
                            firstPick = NO_PICK;
                            secondPick = NO_PICK;
                            ((Timer) e2.getSource()).stop(); // non-repeating timer
                        }).start();
                    }
                }
            }
        }
    
        public void checkForWin() {
            boolean win = true;
            for (ColorButton2 button : buttonList) {
                win &= button.isPairMatched();
            }
            if (win) {
                String message = "You've matched all the colors";
                String title = "Congratulations!";
                int messageType = JOptionPane.INFORMATION_MESSAGE;
                JOptionPane.showMessageDialog(ColorTest.this, message, title, messageType);
            }
        }
    
        private static void createAndShowGui() {
            ColorTest mainPanel = new ColorTest();
    
            JFrame frame = new JFrame("ColorTest");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(mainPanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> createAndShowGui());
        }
    }
    

    @SuppressWarnings("serial")
    class ColorButton2 extends JButton {
        // background color
        private static final Color BG_COLOR = Color.LIGHT_GRAY;
        private int number;
        // non-background color
        private Color color = null;
        // true if a pair has been found for this button
        private boolean pairMatched = false;
    
        public ColorButton2(int number, int width, int height) {
            this.number = number;
            setPreferredSize(new Dimension(width, height));
            setBackground(BG_COLOR);
        }
    
        // reset back to initial conditions
        public void reset() {
            setPairMatched(false);
            setBackground(BG_COLOR);
        }
    
        // if true -- show real color, else show background color
        public void flip(boolean flip) {
            if (flip) {
                setBackground(color);
            } else {
                setBackground(BG_COLOR);
            }
        }
    
        public Color getColor() {
            return color;
        }
    
        public void setColor(Color color) {
            this.color = color;
        }
    
        public void setNumber(int number) {
            this.number = number;
        }
    
        public int getNumber() {
            return number;
        }
    
        public boolean isPairMatched() {
            return pairMatched;
        }
    
        // if match is found, disable the button and set the field
        public void setPairMatched(boolean pairMatched) {
            setEnabled(!pairMatched);
            this.pairMatched = pairMatched;
        }
    }
    

    【讨论】:

    • 问题是我需要扩展 JButton :/
    • @Kappa123:为什么?这是作业要求吗?
    • 不管怎样,你可以这样做,但答案中的概念是一样的
    • 是的,这是一个要求。 ColorButton 只是一个 ColorButton 类,它具有我正在制作的游戏的所有属性等,然后我将制作一定数量的这些对象并在游戏中使用它们
    • 我尝试了第二个,它似乎工作,即涉及洗牌阵列的那个。唯一的问题是,我该怎么做才能让它只从 8 种不同的颜色中挑选随机颜色?我还尝试使用不同的方法来做到这一点(创建一组颜色对象,选择两个随机按钮,为每一对分配一种颜色),所以其中一些可能有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    相关资源
    最近更新 更多