About the author

Related Articles

3 Comments

  1. 1
    phflack@email.null'

    phflack

    Since Color only accepts integers 0-255, you could instead use a regex

    inputString.matches("[12]?\d?\d")

    The regex accepts 1/2/nothing for the first digit, a number or nothing for the second digit, and requires the third digit

    This works for 0-255, but also accepts numbers like 05, 00, and 260 (but not 005, unless you make it [012]), but Integer.parseInt() will figure them out

    You may want to also exclude values like 260, which is covered in: Validate if input string is a number between 0-255 using regex

    inputString.matches("1?[0-9]{1,2}|2[0-4][0-9]|25[0-5]")) will exclude values like 260, but not 05 or 00

    Reply
  2. 2
    Andreas@email.null'

    Andreas

    How would I merge all these three if possible?

    Move common code to helper method. I added value range check too.

    private static int getChannelValue(JTextField field) {
        String error;
        try {
            int value = Integer.parseInt(field.getText());
            if (value >= 0 && value <= 255)
                return value;
            error = "Out of range";
        } catch (NumberFormatException f) {
            error = "Not an integer number";
        }
        JOptionPane.showMessageDialog(null, "No. " + error);
        field.setText("");
        return -1; // invalid
    }
    
    int r = getChannelValue(codeR);
    int g = getChannelValue(codeG);
    int b = getChannelValue(codeB);
    if (r != -1 && g != -1 && b != -1)
        centreName.setForeground(new Color(r, g, b));
    
    Reply
  3. 3
    Aliics@email.null'

    Aliics

    I assume that you are having all of these values gather once a JButton is clicked? Well, instead of doing that why not store the values when the client is done writing to the TextFields and then use parseInt on that specific field?

    field.addFocusListener(new FocusListener() {
                @Override
                public void focusGained(FocusEvent e) { }
    
                @Override
                public void focusLost(FocusEvent e) {
                    // parse and store int here
                }
            });
    
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2017 SolutionMmyself.com