Getting a Color from a String input

后端 未结 5 1294
不知归路
不知归路 2021-01-23 18:41

I am making an application where at some point i need the user to select a color, but as to not just have 50 radioButtons, I was wondering if it is possible to actually get the

相关标签:
5条回答
  • 2021-01-23 19:02

    Wouldn't it be easier to just make a JComboBox or something alike?

    But to answer your question: Yes it is possible. I'll give a piece of code that you could use as a start to get you going (assuming you still want the string to color)

    String text = "red";
    Color color;
    Field field = Class.forName("java.awt.Color").getField(text.toLowerCase()); // toLowerCase because the color fields are RED or red, not Red
    color = (Color)field.get(null);
    
    0 讨论(0)
  • 2021-01-23 19:06

    you can always use a select box.

    info on how to create a JComboBox

    0 讨论(0)
  • 2021-01-23 19:07

    TRy

    Color aColor   = (Color) Color.class.getField("white").get(null);
    

    ALso,

    See if the static method Color.decode() will serve your purpose.

    0 讨论(0)
  • 2021-01-23 19:09

    Try using Color.parseColor(text);

    0 讨论(0)
  • 2021-01-23 19:21

    Why don't you use a JColorChooser that is a standard Swing component?

    You can read a tutorial here but it is quite straightforward to use, as every Swing dialog, the result is something like:

    color chooser

    0 讨论(0)
提交回复
热议问题