1

I am new to java. I have a guessing number game homework. The user inputs a guess and the JLabel on JFrame shows if the guess is too high or too low or is it correct. The background color for the JFrame should change to either red or blue when a guess is entered. I know how to change it to one color but is there any way I can pick a color between red or blue without using math.random to assign 0 or 1 to a variable and then using if else statements? Thank you.

workthat
  • 123
  • 10
  • Depends on how random you want the colour to be. You could read current colour and change it to the other, or do a `enteredResponse%2`, or something else. It really depends on what you want. – AntonH Oct 16 '14 at 19:55
  • Oh okay. If let us say JFrame displays either red or blue irrespective of the previous color it is showing, is there any other way I can do it without asking the user for a color? – workthat Oct 16 '14 at 20:06
  • If you want it randon, you'll have to use `Random`. Otherwise, you'll have to use an information that you can read or deduce at some point. Maybe you have a counter with `numberOfTries`, and you can use that. Maybe one colour if guess too high, another for too low. Maybe one colour if guess even, another if guess is odd. It depends on what you want. – AntonH Oct 16 '14 at 20:09
  • No problem. Hope you find something that works for you. – AntonH Oct 16 '14 at 20:13
  • You could set up a color blending algorithm, so based on the distance between the guess and the value, you could create a color which a percentage of the worse case and best case scenarios, [for example](http://stackoverflow.com/questions/21270610/java-smooth-color-transition/21270957#21270957) – MadProgrammer Oct 16 '14 at 20:26
  • oh okay. It is a different approach. I will try it now. – workthat Oct 16 '14 at 20:31

1 Answers1

0

Your questions a little vague, so I'm not sure if this will meet your requirements, but...

What you could do is set up a blending process, so you would have "worst" and "best" case scenarios, for example, red for way below, blue for way above and green for spot on. Then based on the distance that the user was away from your guess, you could generate a blend of the two colors (worse-good-worse, based on direction), for example...

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

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366