java - 是否可以在 JFrame 的两种背景颜色之间进行选择,而无需创建变量并为其分配随机数 0 或 1?

标签 java swing jframe

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

最佳答案

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

您可以做的是设置一个混合过程,这样您就会有“最差”和“最好”的情况,例如,红色表示低于,蓝色表示高于,绿色表示正确。然后,根据用户与您猜测的距离,您可以生成两种颜色的混合(更差-好-更差,基于方向),例如...

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;
    }

}

关于java - 是否可以在 JFrame 的两种背景颜色之间进行选择,而无需创建变量并为其分配随机数 0 或 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26412730/

相关文章:

Java循环遍历图像中的像素?

java - 默认变量的值与默认初始化

Java Swing - 如何在Jpanel的北部添加图像

java - Swing 中的水平滚动

java - 如何在文本冒险游戏中获取用户输入(Java/Applet)

java - 从字符串正则表达式java中删除字符

java - 如何将此方法 AsyncTask 转换为 RxAndroid

java - 内容更改时 Swing 组件重叠

java - .getSize() 在 JScrollPane 中更新,但不在 JPanel 中更新

java - 将 Applet 添加到 JFrame