Text input for choosing Colour

Hi, I want to choose a colour by typing the hex (or the RGB) into a field. Is my rough sketch (see below) the way to go?
Later, I will add a value for the Alpha to the string rather than type it into the text field and I will also add constraints so only correct numbers, etc. can be entered but first I wanted to check the general approach is correct.

String myText = "ff6fe442";
PFont font;

void setup() {
  colorMode(RGB, 255, 255, 255);
  size(300, 300);

  // create the font
  font = createFont("SansSerif", 14); //First use Processing > Tools > Create Font...
  textFont(font);
  textAlign(LEFT);

  //String[] fontList = PFont.list();
  //printArray(fontList);
}

void draw() {
  background(255); //white

  // text input
  fill(0, 102, 153);
  text(myText, 100, 20, 300, height);


  // mangle text from string to int
  String hs = myText;
  int hi = unhex(hs); // need the alpha but could add it here

  // text input presented as colour
  fill(hi);
  rect(100, 100, 60, 60);
}

void keyPressed() { // later, contrain so only usable characters poss, 
  if (keyCode == BACKSPACE) {
    if (myText.length() > 0) {
      myText = myText.substring(0, myText.length()-1);
    }
  } else if (keyCode == DELETE) {
    myText = "";
  } else if (keyCode != SHIFT) {
    myText = myText + key;
  }
}
1 Like

can also use a text edit field from a library like G4P

a shorter example:

/**
 GTextField  for Processing V2 and V3
 (c) 2015 Peter Lager
 */

import g4p_controls.*;

GTextField txf1;

public void setup() {
  size(500, 300);
  G4P.setGlobalColorScheme(GCScheme.PURPLE_SCHEME);
  txf1 = new GTextField(this, 10, 10, 80, 20);
  txf1.tag = "txf1";
  txf1.setPromptText("col HEX,NO #");

}

public void draw() {
  background(200, 128, 200);
}

public void displayEvent(String name, GEvent event) {
  String extra = " event fired at " + millis() / 1000.0 + "s";
  print(name + "   ");
  switch(event) {
  case CHANGED:
    println("CHANGED " + extra);
    break;
  case SELECTION_CHANGED:
    println("SELECTION_CHANGED " + extra);
    break;
  case LOST_FOCUS:
    println("LOST_FOCUS " + extra);
    break;
  case GETS_FOCUS:
    println("GETS_FOCUS " + extra);
    break;
  case ENTERED:
    println("ENTERED " + extra);
    println(" here do something ");
    break;
  default:
    println("UNKNOWN " + extra);
  }
}

public void handleTextEvents(GEditableTextControl textControl, GEvent event) { 
  displayEvent(textControl.tag, event);
}

1 Like

Thanks @kll G4P looks interesting. And thank you for the example, I didn’t see that earlier (in my email).

It would also be good for learning to know whether the code I have can be improved.