Java Swing问题 - 使用调色板 [英] Java Swing issue - Using color palette
问题描述
我有一个问题 - 我选择了一种颜色后使用十六进制值存储在文本字段中(使用JColorChooser)。我想要做的是在具有十六进制值的另一个文本字段旁边显示颜色的名称,但我不确定如何获取颜色名称?我包含了我的代码,也许有人可以给我一些有用的提示:
I have a problem here - I have a hexadecimal value being stored in a textfield after I have selected a color (using JColorChooser). What I would like to do is display the name of the color in another textfield right beside the one with the hexadecimal value, but I am unsure as to how to get the color name? I am including my code, maybe someone can give me some useful hints:
public class Main extends JComponent implements Accessible {
public ColorSelectionModel selectionModel;
public static final String SELECTION_MODEL_PROPERTY = "selectionModel";
public JColorChooser chooser;
public Color color;
public void process() {
JFrame frame;
JButton button;
final JTextField text1, text2;
// Initialize variables
chooser = new JColorChooser();
frame = new JFrame();
JPanel panel = new JPanel();
button = new JButton("Show color Palette");
text1 = new JTextField(20);
text2 = new JTextField(20);
// Setup UI
frame.add(panel);
panel.add(button);
panel.add(text1);
panel.add(text2);
panel.add(chooser)
chooser.setVisible(false);
button.setLocation(800, 600);
button.setActionCommand("");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
color = chooser.showDialog(chooser, "SHOW THE COLOR",
chooser.getColor());
{
if (color != null) {
String hex = Integer.toHexString(color.getRGB() & 0xffffff);
hex = "#" + hex;
text1.setText(hex);
}
}
}
});
frame.setVisible(true);
frame.setSize(1000, 800);
}
public static void main(String[] argv) {
// Run the code
Main m1 = new Main();
m1.process();
}
}
推荐答案
我通过 Java Reflection
实现:(适用于静态最终颜色
在 java.awt中定义。颜色
)
I achieved this by Java Reflection
: (works for static final Color
defined in java.awt.Color
)
这是我的代码:
public static String getNameReflection(Color colorParam) {
try {
//first read all fields in array
Field[] field = Class.forName("java.awt.Color").getDeclaredFields();
for (Field f : field) {
String colorName = f.getName();
Class<?> t = f.getType();
// System.out.println(f.getType());
// check only for constants - "public static final Color"
if (t == java.awt.Color.class) {
Color defined = (Color) f.get(null);
if (defined.equals(colorParam)) {
System.out.println(colorName);
return colorName.toUpperCase();
}
}
}
} catch (Exception e) {
System.out.println("Error... " + e.toString());
}
return "NO_MATCH";
}
来源: http://ganeshtiwaridotcomdotnp.blogspot.com/2011/12/java-reflection-getting-name-of-color .html
这篇关于Java Swing问题 - 使用调色板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!