Java Swing问题-使用调色板
我在这里遇到问题-选择颜色后(使用JColorChooser),十六进制值存储在文本字段中。我想做的是在十六进制值旁边的另一个文本框中显示颜色的 名称
,但是我不确定如何获得颜色名称?我包含了我的代码,也许有人可以给我一些有用的提示:
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
:(在中static final Color
定义的作品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问题-使用调色板 的全部内容, 来源链接: utcz.com/qa/411790.html