是否可以在不创建变量的情况下为JFrame选择两种背景颜色,并为其指定0或1的随机数?

时间:2014-10-16 19:52:30

标签: java swing jframe

我是java的新手。我有一个猜数字游戏作业。用户输入猜测,JFrame上的JLabel显示猜测是否太高或太低或是否正确。输入猜测时,JFrame的背景颜色应更改为红色或蓝色。我知道如何将其更改为一种颜色,但有没有办法我可以选择红色或蓝色之间的颜色而不使用math.random将0或1分配给变量然后使用if else语句?谢谢。

1 个答案:

答案 0 :(得分:0)

您的问题有点模糊,所以我不确定这是否符合您的要求,但是......

你可以做的是设置一个混合过程,这样你就会有最糟糕的"和#34;最好"案例场景,例如,下面是红色,上面是蓝色,上面是绿色。然后根据用户远离猜测的距离,您可以生成两种颜色的混合(更差 - 更好,基于方向),例如......

Blend

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ColorBlend {

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

    public ColorBlend() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            add(new JLabel("Enter a value between 1-100 (press enter)"), gbc);
            JTextField field = new JTextField(4);
            field.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    // Colors to be used
                    Color[] colors = new Color[]{Color.RED, Color.GREEN, Color.BLUE};
                    // The ratio at which the colors applied across the band...
                    float[] ratios = new float[]{0f, 0.5f, 1f};

                    String text = field.getText();
                    try {

                        int value = Integer.parseInt(text);
                        if (value >= 1 && value <= 100) {
                            float percentage = value / 100f;
                            // Get the color that best meets out needs
                            Color color = blendColors(ratios, colors, percentage);
                            setBackground(color);
                        } else {
                            field.setText("Out of range");
                            field.selectAll();
                        }

                    } catch (NumberFormatException exp) {
                        field.setText("Bad Value");
                        field.selectAll();
                    }
                }
            });
            add(field, gbc);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 200);
        }

    }

    public static Color blendColors(float[] fractions, Color[] colors, float progress) {
        Color color = null;
        if (fractions != null) {
            if (colors != null) {
                if (fractions.length == colors.length) {
                    int[] indicies = getFractionIndicies(fractions, progress);

                    float[] range = new float[]{fractions[indicies[0]], fractions[indicies[1]]};
                    Color[] colorRange = new Color[]{colors[indicies[0]], colors[indicies[1]]};

                    float max = range[1] - range[0];
                    float value = progress - range[0];
                    float weight = value / max;

                    color = blend(colorRange[0], colorRange[1], 1f - weight);
                } else {
                    throw new IllegalArgumentException("Fractions and colours must have equal number of elements");
                }
            } else {
                throw new IllegalArgumentException("Colours can't be null");
            }
        } else {
            throw new IllegalArgumentException("Fractions can't be null");
        }
        return color;
    }

    public static int[] getFractionIndicies(float[] fractions, float progress) {
        int[] range = new int[2];

        int startPoint = 0;
        while (startPoint < fractions.length && fractions[startPoint] <= progress) {
            startPoint++;
        }

        if (startPoint >= fractions.length) {
            startPoint = fractions.length - 1;
        }

        range[0] = startPoint - 1;
        range[1] = startPoint;

        return range;
    }

    public static Color blend(Color color1, Color color2, double ratio) {
        float r = (float) ratio;
        float ir = (float) 1.0 - r;

        float rgb1[] = new float[3];
        float rgb2[] = new float[3];

        color1.getColorComponents(rgb1);
        color2.getColorComponents(rgb2);

        float red = rgb1[0] * r + rgb2[0] * ir;
        float green = rgb1[1] * r + rgb2[1] * ir;
        float blue = rgb1[2] * r + rgb2[2] * ir;

        if (red < 0) {
            red = 0;
        } else if (red > 255) {
            red = 255;
        }
        if (green < 0) {
            green = 0;
        } else if (green > 255) {
            green = 255;
        }
        if (blue < 0) {
            blue = 0;
        } else if (blue > 255) {
            blue = 255;
        }

        Color color = null;
        try {
            color = new Color(red, green, blue);
        } catch (IllegalArgumentException exp) {
            NumberFormat nf = NumberFormat.getNumberInstance();
            System.out.println(nf.format(red) + "; " + nf.format(green) + "; " + nf.format(blue));
            exp.printStackTrace();
        }
        return color;
    }

}