[英]How can I change the background color of a JPanel through a String parameter in its constructor?
I have a program where I want to set the color of a JPanel
when its object is created through its constructor. 我有一个程序,当通过其构造函数创建其对象时,我想在其中设置
JPanel
的颜色。 Right now this is what I have. 现在这就是我所拥有的。
However this is obviously quite inefficient. 但是,这显然效率很低。 I was wondering if there was some way I could pass the string parameter directly into the setBackground() method to set the color?
我想知道是否可以通过某种方式将字符串参数直接传递到setBackground()方法中以设置颜色?
MyPanel(String bcolor) {
super();
if (bcolor.equals("red"))
setBackground(Color.RED);
if (bcolor.equals("blue"))
setBackground(Color.BLUE);
if (bcolor.equals("green"))
setBackground(Color.GREEN);
if (bcolor.equals("white"))
setBackground(Color.WHITE);
if (bcolor.equals("black"))
setBackground(Color.BLACK);
}
I was wondering if there was some way I could pass the string parameter directly into the setBackground() method to set the color?
我想知道是否可以通过某种方式将字符串参数直接传递到setBackground()方法中以设置颜色?
No, obviously, as there is no setBackground(String)
method. 不,显然,因为没有
setBackground(String)
方法。
Now, there are a number of possible solutions you might employee, your current series of if
statements is one solution, another might be to use some king of static
Map
which acts as a look up between the String
value and the Color
you want to use, for example... 现在,您可能会使用多种可能的解决方案,当前的
if
语句系列是一种解决方案,另一种可能是使用一些static
Map
王,这可以在String
值和要使用的Color
之间进行查找, 例如...
public class MyPanel extends JPanel {
protected static final Map<String, Color> COLOR_MAP = new HashMap<>();
public MyPanel(String color) {
setBackground(COLOR_MAP.get(color.toLowerCase()));
}
static {
COLOR_MAP.put("red", Color.RED);
COLOR_MAP.put("blue", Color.BLUE);
COLOR_MAP.put("green", Color.GREEN);
COLOR_MAP.put("white", Color.WHITE);
COLOR_MAP.put("black", Color.BLACK);
}
}
The simplest way would be to pass it the RGB values for the color you want in the constructor. 最简单的方法是将构造函数中想要的颜色的RGB值传递给它。
MyPanel(int r, int g, int b){
super();
setBackground(new Color(r,g,b));
}
If you really, really, want to use Strings, you could do this 如果确实要使用字符串,则可以执行此操作
String colorName; //note that this has to be exact spelling and capitalization of the fields in the Color class.
Field field = Class.forName("java.awt.Color").getField(colorName);
setBackground((Color) field.get(null));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.