如何通过其构造函数中的 String 参数更改 JPanel 的背景颜色?
How can I change the background color of a JPanel through a String parameter in its constructor?
我有一个程序,我想在通过其构造函数创建对象时设置 JPanel
的颜色。现在这就是我所拥有的。
但这显然是很低效的。我想知道是否有某种方法可以将字符串参数直接传递给 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);
}
最简单的方法是在构造函数中将您想要的颜色的 RGB 值传递给它。
MyPanel(int r, int g, int b){
super();
setBackground(new Color(r,g,b));
}
如果你真的非常想使用字符串,你可以这样做
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));
I was wondering if there was some way I could pass the string parameter directly into the setBackground() method to set the color?
不,显然,因为没有 setBackground(String)
方法。
现在,您可能会采用多种可能的解决方案,您当前的一系列 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);
}
}
我有一个程序,我想在通过其构造函数创建对象时设置 JPanel
的颜色。现在这就是我所拥有的。
但这显然是很低效的。我想知道是否有某种方法可以将字符串参数直接传递给 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);
}
最简单的方法是在构造函数中将您想要的颜色的 RGB 值传递给它。
MyPanel(int r, int g, int b){
super();
setBackground(new Color(r,g,b));
}
如果你真的非常想使用字符串,你可以这样做
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));
I was wondering if there was some way I could pass the string parameter directly into the setBackground() method to set the color?
不,显然,因为没有 setBackground(String)
方法。
现在,您可能会采用多种可能的解决方案,您当前的一系列 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);
}
}